bouncy castle

[bouncy castle] TDES CBC with padding example

레인Maker 2023. 7. 30. 15:14

Triple DES CBC with padding Example

 

 

2Key를 이용한 block size에 맞게 padding하여  암호화 /  복호화하는 예제

참고사항) Bouncy castle에서 Padding 방식을 지정하지 않을 경우 default padding 방식은 PKCS7 방식을 사용한다.

 

public byte[] desCbcPaddEncrypt(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();
    // Padding cipher (adjust input data length to des block size)
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine));
    // set key
    cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv));

    // 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[] desCbcPaddDecrypt(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();
    // Padding cipher (adjust input data length to des block size)
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine));
    // set key
    cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));

    // 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.desCbcPaddEncrypt(des2key, text, null);
    
    ret = ex.desCbcPaddDecrypt(des2key, text, null);
    System.out.println(new String(ret, StandardCharsets.UTF_8));
}

 

결과: 첫번째 라인은 암호화한 결과, 두번째 라인은 복호화한 결과

3C:05:C5:05:BE:37:C5:40:CF:44:C4:88:87:FE:95:61
hello world

 

코드위치

https://github.com/coolbong/BouncyCastleExample/blob/master/src/main/java/io/github/coolbong/Des.java