首先尝试Java DES解密异常

时间:2014-03-11 13:15:52

标签: java android encryption des spongycastle

在我的项目中,在android客户端和服务器之间使用安全通信,因此它们之间的所有消息都被加密为DES算法。 我使用了默认的Java Provider和SpongyCastle,但是在第一次尝试解密时,它给出了以下异常。

javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
at org.spongycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:815)
at javax.crypto.Cipher.doFinal(Cipher.java:1111)

下面的编码字符串
SB1DbM9MbtFYY62OtDwkU4+CxlHi7wj9MQIPVMsoktVyPZDoi79V2Hx5pzjLgQvxXKJSLP7BpNYZg4hlbVGzkCE8x4LTmTbdQzwweMjlOGfTbZSNA+iL1sx0ctRYFIVLu7c0ZnsSnJ4Fq2tdL2XS3YQW3/MokoAlyFK6lhBf/4t+VpZ/cy+s9g==

在第二次尝试中,它成功解密了String。我找不到问题。

加密和解密的源代码

private Cipher encryptCipher = null;
private Cipher decryptCipher = null;

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

public void initialize(SecretKey key) throws Exception {
    try {
        encryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding", "SC");
        decryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding", "SC");
    } catch (Exception e) {
    }

    encryptCipher.init(Cipher.ENCRYPT_MODE, key);
    decryptCipher.init(Cipher.DECRYPT_MODE, key);
}

public String encryptBase64(String unencryptedString) throws Exception {
    byte[] unencryptedByteArray = unencryptedString.getBytes("UTF-8");
    byte[] encryptedBytes = encryptCipher.doFinal(unencryptedByteArray);
    return new String(Base64.encodeBase64(encryptedBytes), "UTF-8");
}

public String decryptBase64(String encryptedString) throws Exception {
    try {
        byte[] unencryptedByteArray = decryptCipher.doFinal(Base64.decodeBase64(encryptedString.getBytes("UTF-8")));
        String message = new String(unencryptedByteArray, "UTF-8");
        return message;
    } catch (Exception e) {
    }

    return null;
}

0 个答案:

没有答案