bouncy castle
[bouncy castle] TDES CBC Example
레인Maker
2023. 7. 29. 21:44
Triple DES CBC Example
2Key를 이용한 16 byte block을 Triple DES CBC mode로 암호화 / 복호화하는 예제
public byte[] desCbcEncrypt(byte[] key, byte[] text, byte[] iv) throws InvalidCipherTextException {
// create default initialize vector
if (iv == null) {
iv = new byte[8];
}
// create TDES cipher
BlockCipher engine = new DESedeEngine();
BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(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[] desCbcDecrypt(byte[] key, byte[] text, byte[] iv) throws InvalidCipherTextException {
// create default initialize vector
if (iv == null) {
iv = new byte[8];
}
// create TDES cipher
BlockCipher engine = new DESedeEngine();
BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(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;
}
public static void main(String[] args) throws Exception {
// TDES 2 key
byte[] key = {
(byte)0x40, (byte)0x41, (byte)0x42, (byte)0x43, (byte)0x44, (byte)0x45, (byte)0x46, (byte)0x47,
(byte)0x48, (byte)0x49, (byte)0x4a, (byte)0x4b, (byte)0x4c, (byte)0x4d, (byte)0x4e, (byte)0x4f
};
Des ex = new Des();
byte[] ret;
byte[] text;
text = "jetbrainintellij".getBytes(StandardCharsets.UTF_8);
ret = ex.desCbcEncrypt(key, text, null);
print(ret);
ret = ex.desCbcDecrypt(key, ret, null);
System.out.println(new String(ret, StandardCharsets.UTF_8));
}
결과: 첫번째 라인은 암호화한 결과, 두번째 라인은 복호화한 결과
A9:76:48:A3:AB:A5:BE:36:42:1D:CB:23:7A:94:11:9C
jetbrainintellij
코드위치