javades首次尝试解密异常

wz3gfoph  于 2021-07-09  发布在  Java
关注(0)|答案(0)|浏览(233)

在我的项目中,android客户端和服务器之间使用安全通信,因此它们之间的所有消息都按照des算法加密。我使用了默认的java提供程序和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==

在第二次尝试中,它成功地解密了字符串。我找不到问题。
加密和解密的源代码

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;
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题