我在java中做了一个简单的加密/解密字符串类并对其进行了测试。它工作正常,现在我试图在一个 android 设备中使用它来加密一个字符串,将它发送到我的服务器并在那里解密它。全部使用相同的自定义类。为什么这不起作用?它根本不支持吗?为此,我还能做些什么来轻松加密/解密字符串?不接受 Base64 :)
package crypto;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class Crypto {
public static byte[] encrypt(String message) throws Exception
{
String symmetricKey = "25Ae1f1711%z1 )1";
SecretKeySpec aesKey = new SecretKeySpec(symmetricKey.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(message.getBytes());
}
public static String decrypt(byte[] encryptedMessage) throws Exception
{
String symmetricKey = "25Ae1f1711%z1 )1";
SecretKeySpec aesKey = new SecretKeySpec(symmetricKey.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(encryptedMessage));
}
}
在 logcat 我可以看到以下异常弹出: java.security.NoSuchProviderException: Provider not avalible: SunJCE
我从该行中删除了指定的提供者“SunJCE”。
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
现在我在服务器端收到此错误:
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:750)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:317)
at javax.crypto.Cipher.doFinal(Cipher.java:1813)
at crypto.Crypto.decrypt(Crypto.java:20)
at io.network.UDPServer.run(UDPServer.java:37
尝试使用 BC 但我仍然有同样的错误