我是新加密的java。嘗試實現輕量級加密字符串並將其存儲在某個地方,並在使用之前將其解密。在java解密期間BadPaddingException
隨着一些網絡搜索我想出了這個加密和解密。
public static String base64Encode(byte[] bytes)
{
return new BASE64Encoder().encode(bytes);
}
public static byte[] base64Decode(String property) throws IOException
{
return new BASE64Decoder().decodeBuffer(property);
}
public static String encrypt(String mystring) throws GeneralSecurityException, UnsupportedEncodingException
{
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(mystring.toCharArray()));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return base64Encode(pbeCipher.doFinal(mystring.getBytes("UTF-8")));
}
public static String decrypt(String estring) throws GeneralSecurityException, IOException
{
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(estring.toCharArray()));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return new String(pbeCipher.doFinal(base64Decode(estring)), "UTF-8");
}
我看到加密工作,但我在解密部分,從doFinal塊看到一個填充相關的異常。這是...
encrypted string:zdrtgOKfkZMgpCOflr1ILQ== -> Encrypted String
exceptionjavax.crypto.BadPaddingException: Given
final block not properly padded -> Exception from the doFinal block.
好像當我加密它,我需要做一些填充。
任何人都可以告訴我哪裏出了問題,怎麼解決?
感謝
塔斯
此工程 - 感謝您的幫助。 – Tas