好吧,尽管网络上有很多与此相关的文章,但问这个问题很尴尬,但我无法弄清楚。我对这个感到震惊。
我正在使用AES/CBC/PKCS5
算法在 Android 中加密文本,但无法在 Windows 8 appstore 应用程序中解密它。这是我的加密代码
public static String encrypt(String plainText,String password) throws Exception {
// convert key to bytes
byte[] keyBytes = password.getBytes("UTF-8");
// Use the first 16 bytes (or even less if key is shorter)
byte[] keyBytes16 = new byte[16];
System.arraycopy(keyBytes, 0, keyBytes16, 0,
Math.min(keyBytes.length, 16));
// convert plain text to bytes
byte[] plainBytes = plainText.getBytes("UTF-8");
// setup cipher
SecretKeySpec skeySpec = new SecretKeySpec(keyBytes16, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[16]; // initialization vector with all 0
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv));
// encrypt
byte[] encrypted = cipher.doFinal(plainBytes);
String encryptedString = Base64.encodeToString(
cipher.doFinal(plainBytes), Base64.NO_WRAP);
// encryptedString
return Base64.encodeToString(encrypted, Base64.NO_WRAP);
}
我在 Windows 8 应用程序中使用以下代码进行加密
public string AES_Encrypt(string input, string pass)
{
SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
string encrypted = "";
try
{
byte[] test1 = System.Text.Encoding.UTF8.GetBytes(pass);
byte[] test2 = new byte[16];
for (int i = 0; i < test1.Length;i++ )
{
test2[i] = test1[i];
}
CryptographicKey key =
SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(test2));
IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(input));
encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(key, Buffer, null));
return encrypted;
}
catch (Exception ex)
{
return null;
}
}
以下是解密算法
public string AES_Decrypt(string input, string pass)
{
SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
string decrypted = "";
try
{
byte[] test1 = System.Text.Encoding.UTF8.GetBytes(pass);
byte[] test2 = new byte[16];
for (int i = 0; i < test1.Length;i++ )
{
test2[i] = test1[i];
}
CryptographicKey key =
SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(test2));
IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(input);
byte[] Decrypted;
CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(key, Buffer, null), out Decrypted);
decrypted = System.Text.Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);
return decrypted;
}
catch (Exception ex)
{
return null;
}
}
我知道生成的 IV 有问题。如果我给 Iv 作为null
,解密算法会生成一些结果(虽然它是错误的),如果我给 IV 一些值,它会引发异常,例如“值不在预期范围内” 。
任何帮助深表感谢。