我正在 Android、Windows 8 Tablet/Desktop 和 Windows phone 8 中开发应用程序。我在 Android 和 Windows 8 Tablet/Desktop 应用程序中使用 AES CBC 算法,并且能够正确加密和解密。我必须在 Windows 中使用相同的算法phone 8.我从网络上的一个示例中尝试过,但问题是在 Windows 8 Tab/Desktop 应用程序和 Windows phone 8 中加密相同的字符串时两者都不同。我确信 Windows Tab/Desktop 可以正常工作已经在 appstore 中,它适用于 Android 应用程序。
算法的安卓代码
公共静态字符串加密(字符串纯文本,字符串密码)抛出异常 {
if (plainText == null || plainText.length() == 0)
return "";
// 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);
}
视窗电话 8
public static string Encrypt1(string dataToEncrypt, string password, string salt)
{
AesManaged aes = null;
MemoryStream memoryStream = null;
CryptoStream cryptoStream = null;
try
{
byte[] b = new byte[16];
byte[] pwd = System.Text.UTF8Encoding.UTF8.GetBytes(password);
byte[] pwd1 = new byte[16];
for (int i = 0; i < 16;i++ ) // take first 16 bits of the password
{
pwd1[i] = pwd[i];
}
String newPwd = System.Text.Encoding.UTF8.GetString(pwd1, 0 ,pwd1.Length);
//Generate a Key based on a Password, Salt and HMACSHA1 pseudo-random number generator
Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(newPwd, b);
//Create AES algorithm with 256 bit key and 128-bit block size
aes = new AesManaged();
//aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = 128;
aes.Key = rfc2898.GetBytes(128 / 8);
aes.IV = rfc2898.GetBytes(128 / 8);
//aes.IV = b;
//Create Memory and Crypto Streams
memoryStream = new MemoryStream();
cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
//Encrypt Data
byte[] data = Encoding.UTF8.GetBytes(dataToEncrypt);
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
//Return Base 64 String
return Convert.ToBase64String(memoryStream.ToArray());
}
finally
{
if (cryptoStream != null)
cryptoStream.Close();
if (memoryStream != null)
memoryStream.Close();
if (aes != null)
aes.Clear();
}
}
我知道我的 win phone 8 算法有问题。请帮我找出答案。非常感谢任何帮助。