Triple DES ECB with padding Example
2Key를 이용한 block size에 맞게 padding하여 암호화 / 복호화하는 예제
참고사항) Bouncy castle에서 Padding 방식을 지정하지 않을 경우 default padding 방식은 PKCS7 방식을 사용한다.
public byte[] desEcbPaddEncrypt(byte[] key, byte[] text) throws InvalidCipherTextException {
// create TDES cipher
BlockCipher engine = new DESedeEngine();
// Padding cipher (adjust input data length to des block size)
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
// set key
cipher.init(true, new KeyParameter(key));
// get output buffer size
int outputSize = cipher.getOutputSize(text.length);
// create output buffer
byte[] outBuff = new byte[outputSize];
int offset = cipher.processBytes(text, 0, text.length, outBuff, 0);
cipher.doFinal(outBuff, offset);
return outBuff;
}
public byte[] desEcbPaddDecrypt(byte[] key, byte[] text) throws InvalidCipherTextException {
// create TDES cipher
BlockCipher engine = new DESedeEngine();
// Padding cipher (adjust input data length to des block size)
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
// set key
cipher.init(false, new KeyParameter(key));
// get output buffer size
int outputSize = cipher.getOutputSize(text.length);
// create output buffer
byte[] outBuff = new byte[outputSize];
int offset = cipher.processBytes(text, 0, text.length, outBuff, 0);
int ret = cipher.doFinal(outBuff, offset);
return Arrays.copyOf(outBuff, offset+ret);
}
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[] text;
byte[] ret;
text = "hello world".getBytes(StandardCharsets.UTF_8);
ret = ex.desEcbPaddEncrypt(key, text);
print(ret);
ret = ex.desEcbPaddDecrypt(key, ret);
System.out.println(new String(ret, StandardCharsets.UTF_8));
}
결과: 첫번째 라인은 암호화한 결과, 두번째 라인은 복호화한 결과
3C:05:C5:05:BE:37:C5:40:CA:10:5B:9C:2F:AD:62:DC
hello world
코드위치
'bouncy castle' 카테고리의 다른 글
[bouncy castle] AES CBC (128, 192, 256) example (0) | 2023.07.30 |
---|---|
[bouncy castle] AES ECB (128, 192, 256) example (0) | 2023.07.30 |
[bouncy castle] TDES CBC with padding example (0) | 2023.07.30 |
[bouncy castle] TDES CBC Example (0) | 2023.07.29 |
[bouncy castle] TDES ECB example (0) | 2023.07.28 |