본문 바로가기

bouncy castle

[bouncy castle] TDES ECB example

Triple DES ECB Example

 

 

2Key를 이용한 8 byte block을 암호화 /  복호화하는 예제

public byte[] desEcbEncrypt(byte[] key, byte[] text) throws InvalidCipherTextException {
    // create TDES cipher
    BlockCipher engine = new DESedeEngine();
    BufferedBlockCipher cipher = new BufferedBlockCipher(engine);
    // set key
    cipher.init(true, new KeyParameter(key));

    byte[] outBuff = new byte[text.length];
    int offset = cipher.processBytes(text, 0, text.length, outBuff, 0);
    cipher.doFinal(outBuff, offset);

    return outBuff;
}


public byte[] desEcbDecrypt(byte[] key, byte[] encrypted) throws InvalidCipherTextException {
    // create TDES cipher
    BlockCipher engine = new DESedeEngine();
    BufferedBlockCipher cipher = new BufferedBlockCipher(engine);
    // set key
    cipher.init(false, new KeyParameter(key));

    byte[] outBuff = new byte[encrypted.length];
    int offset = cipher.processBytes(encrypted, 0, encrypted.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 = "intellij".getBytes(StandardCharsets.UTF_8);
    ret = ex.desEcbEncrypt(key, text);

    ret = ex.desEcbDecrypt(key, ret);
    System.out.println(new String(ret, StandardCharsets.UTF_8));
}

 

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

DF:CF:5D:F2:19:28:8D:D5
intellij

 

코드위치

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