bouncy castle
[bouncy castle] AES CTR (128, 192, 256) example
레인Maker
2023. 7. 30. 17:10
AES CTR Example
128, 192, 256의 의미는 키 길이의 bit수를 의미한다.
128 bit은 16 byte key 길이, 192 bit은 24 byte key 길이, 192 bit은 32 byte key 길이를 의미한다.
32 byte block을 암호화 / 복호화하는 예제
static byte[] aes_128bit_16byte = "ABCDEFGHIJKLMNOP".getBytes(StandardCharsets.UTF_8);
static byte[] aes_192bit_24byte = "ABCDEFGHIJKLMNOPQRSTUVWX".getBytes(StandardCharsets.UTF_8);
static byte[] aes_256bit_32byte = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef".getBytes(StandardCharsets.UTF_8);
public byte[] aesCtrEncrypt(byte[] key, byte[] text, byte[] iv) throws InvalidCipherTextException {
// create default initialize vector
if (iv == null) {
iv = new byte[16];
}
// create AES cipher
BlockCipher engine = new AESEngine();
BufferedBlockCipher cipher = new BufferedBlockCipher(new SICBlockCipher(engine));
// set key with iv
cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv));
byte[] outBuff = new byte[text.length];
int offset = cipher.processBytes(text, 0, text.length, outBuff, 0);
cipher.doFinal(outBuff, offset);
return outBuff;
}
public byte[] aesCtrDecrypt(byte[] key, byte[] text, byte[] iv) throws InvalidCipherTextException {
// create default initialize vector
if (iv == null) {
iv = new byte[16];
}
// create AES cipher
BlockCipher engine = new AESEngine();
BufferedBlockCipher cipher = new BufferedBlockCipher(new SICBlockCipher(engine));
// set key with iv
cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
byte[] outBuff = new byte[text.length];
int offset = cipher.processBytes(text, 0, text.length, outBuff, 0);
cipher.doFinal(outBuff, offset);
return outBuff;
}
void aesEcbExample() throws InvalidCipherTextException {
byte[] text = "jetbrainintellijpasswordoverflow".getBytes(StandardCharsets.UTF_8);
byte[] ret;
ret = aesCtrEncrypt(aes_128bit_16byte, text, null);
ret = aesCtrDecrypt(aes_128bit_16byte, ret, null);
System.out.println(new String(ret, StandardCharsets.UTF_8));
ret = aesCtrEncrypt(aes_192bit_24byte, text, null);
ret = aesCtrDecrypt(aes_192bit_24byte, ret, null);
System.out.println(new String(ret, StandardCharsets.UTF_8));
ret = aesCtrEncrypt(aes_256bit_32byte, text, null);
ret = aesCtrDecrypt(aes_256bit_32byte, ret, null);
System.out.println(new String(ret, StandardCharsets.UTF_8));
}
결과: 각 키 길이별 첫번째 라인은 암호화한 결과, 두번째 라인은 복호화한 결과
// 128 bit 16 byte key
EF:10:A5:8A:E1:F0:10:B3:C1:0B:6A:8B:44:94:F4:17:32:4F:6F:E6:23:0B:80:12:FC:49:0D:43:BF:67:C9:4A
jetbrainintellijpasswordoverflow
// 192 bit 24 byte key
23:90:A0:65:D4:48:76:70:2A:53:AA:17:6F:4E:50:80:F1:C1:F8:F9:24:B7:9F:73:CC:3B:94:28:F0:9B:AC:32
jetbrainintellij
// 256 bit 32 byte key
EA:C0:1D:5F:2D:62:F9:F2:76:14:B7:E3:FA:A8:97:EF:2C:55:5D:9A:D1:83:40:63:E5:D9:39:94:F8:A8:4E:E0
jetbrainintellij
코드위치