TripleDES encryption error in java

◇◆丶佛笑我妖孽 提交于 2019-12-03 21:52:13

Triple DES requires a 24 byte key, not an 8 byte one.

I've found solution by changing these lines:

try {
    // get bytes representation of the password
    key = passphrase.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
    throw new IllegalArgumentException(e);
}

key = padKeyToLength(key, MAX_KEY_LENGTH);
key = addParity(key);
keySpec = new SecretKeySpec(key, ENCRYPTION_KEY_TYPE);

into these:

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
byte[] keyBytes = GetKeyAsBytes(key);
keySpec = new SecretKeySpec(keyBytes, "DESede");

while GetKeyAsBytes method is this:

public byte[] GetKeyAsBytes(String key) {
    byte[] keyBytes = new byte[24]; // a Triple DES key is a byte[24] array

    for (int i = 0; i < key.length() && i < keyBytes.length; i++) 
        keyBytes[i] = (byte) key.charAt(i);

    return keyBytes;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!