WIS*_*SHY 1 java encryption aes
我试图加密字符串如下
public class AES256Cipher {
static byte[] ivBytes = new byte[]{0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76};
static String EncryptionKey = "abc123";
public static byte[] encrypt(String plainText)
throws java.io.UnsupportedEncodingException,
NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
IllegalBlockSizeException,
BadPaddingException {
byte[] keyBytes = EncryptionKey.getBytes("UTF-8");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = null;
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
byte[] cipherData = cipher.doFinal(plainText.getBytes("UTF-8"));
Log.e("cipher", Base64.encodeToString(cipherData, Base64.DEFAULT));
return cipher.doFinal(plainText.getBytes("UTF-8"));
}
}
Run Code Online (Sandbox Code Playgroud)
我得到了这个例外
java.security.InvalidKeyException: Unsupported key size: 6 bytes
at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER$AES.checkSupportedKeySize(OpenSSLCipher.java:686)
at com.android.org.conscrypt.OpenSSLCipher.checkAndSetEncodedKey(OpenSSLCipher.java:442)
at com.android.org.conscrypt.OpenSSLCipher.engineInit(OpenSSLCipher.java:272)
at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:608)
at javax.crypto.Cipher.tryCombinations(Cipher.java:532)
at javax.crypto.Cipher.getSpi(Cipher.java:437)
at javax.crypto.Cipher.init(Cipher.java:909)
at javax.crypto.Cipher.init(Cipher.java:859)
at com.vfirst.util.netwrok.AES256Cipher.encrypt(AES256Cipher.java:36)
at com.vfirst.LoginActivity.onCreate(LoginActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6321)
Run Code Online (Sandbox Code Playgroud)
要加密的字符串
AES256Cipher.encrypt("12345");
Run Code Online (Sandbox Code Playgroud)
小智 13
AES仅支持16,24或32字节的密钥大小...因此您必须更改EncryptionKey.
SecureRandom random = new SecureRandom();
byte[] EncryptionKey = new byte[16];
random.nextBytes(EncryptionKey);
Run Code Online (Sandbox Code Playgroud)
您可以使用上面的代码示例.
| 归档时间: |
|
| 查看次数: |
6827 次 |
| 最近记录: |