Android DES解密ECB模式

Android DES decryption ECB mode

我正在尝试解密数据,
这是用 mcrypt
加密的 DES、ECB 模式
然后包装成Base64。 这是我的代码:

static {
    Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
}
// ...

// Crypted input data and the key
String criptedInput = "vsm1/sLWAUxW7JjKT/Amww==";
final String KEY = "jf7746yghndd";

// Decoding base64
byte[] bytesDecoded = Base64.decodeBase64(criptedInput.getBytes());

SecretKeySpec key = new SecretKeySpec(KEY.getBytes(), "DES");

Cipher cipher = null;
String result = null;

try {
    cipher = Cipher.getInstance("DES/ECB/PKCS7Padding", "BC");

    // Initialize the cipher for decryption
    cipher.init(Cipher.DECRYPT_MODE, key);

    // Decrypt the text
    byte[] textDecrypted = cipher.doFinal(bytesDecoded);

    result = new String(textDecrypted);

} catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
} catch (NoSuchProviderException e) {
    e.printStackTrace();
} catch (NoSuchPaddingException e) {
    e.printStackTrace();
} catch (IllegalBlockSizeException e) {
    e.printStackTrace();
} catch (BadPaddingException e) {
    e.printStackTrace();
} catch (InvalidKeyException e) {
    e.printStackTrace();
}

现在我正在捕获 java.security.invalidkeyexception:des 密钥太长 - 应该是 8 个字节..

怎么了?

DES 仅支持 56 位的密钥大小(64 位带奇偶校验)。所以你不能用更大的钥匙。 Mcrypt 知道这一点并默默地只使用前 8 个字节。 Mcrypt 也没有实现适当的填充。相反,它用 0x00 字节填充。您应该能够在 BouncyCastle 中使用类似但不相同的填充:

Cipher.getInstance("DES/ECB/ZeroBytePadding", "BC");

切勿使用 ECB mode. It's deterministic and therefore not semantically secure. You should at the very least use a randomized mode like CBC or CTR. It is better to authenticate your ciphertexts so that attacks like a padding oracle attack are not possible. This can be done with authenticated modes like GCM or EAX, or with an encrypt-then-MAC 方案。