这个问题通常是因为在解密密文时使用的密钥与加密时使用的密钥不相同导致的。要解决这个问题,需要先确保密钥是正确的,然后再尝试解密。
以下是一个使用AES加密和解密的示例代码,可以参考:
// 加密 public static byte[] encrypt(String key, String content) { try { byte[] rawKey = getRawKey(key.getBytes()); byte[] result = encrypt(rawKey, content.getBytes()); return result; } catch (Exception e) { e.printStackTrace(); return null; } }
private static byte[] encrypt(byte[] key, byte[] content) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(content); return encrypted; }
// 解密 public static String decrypt(String key, byte[] encrypted) { try { byte[] rawKey = getRawKey(key.getBytes()); byte[] result = decrypt(rawKey, encrypted); return new String(result); } catch (Exception e) { e.printStackTrace(); return null; } }
private static byte[] decrypt(byte[] key, byte[] encrypted) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] decrypted = cipher.doFinal(encrypted); return decrypted; }
private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(seed); kgen.init(128, sr); // 为AES使用128位密钥 SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); return raw; }
注意:加密和解密方法中的密钥必须相同。如果在加密时生成了密钥,应该将