因工作需要,需要在winphone7手机上实现AES的加密,解密算法。经过自己的查找,终于找到了一个可以实现的代码,来和大家共享,代码如下:
- using System;
- using System.Security.Cryptography;
- using System.Text;
- using System.IO;
- namespace SheenClient.classes.eventhandler
- {
- ///
- /// AES解密算法类
- ///
- public class AESEncryption
- {
- ///
- /// 默认密钥向量
- ///
- private static string salt = "PasswordSalt";
- ///
- /// 进行AES加密算法
- ///
- /// 要进行加密的字符串
- /// 进行加密的键
- /// 加密后的字符串
- public static string AesEncrypt(string dataToEncrypt, string key)
- {
- AesManaged aes = null;
- MemoryStream memoryStream = null;
- CryptoStream cryptoStream = null;
- try
- {
- //Generate a Key based on a Password, Salt and HMACSHA1 pseudo-random number generator
- Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(key, Encoding.UTF8.GetBytes(salt));
- //Create AES algorithm with 256 bit key and 128-bit block size
- aes = new AesManaged();
- aes.Key = rfc2898.GetBytes(aes.KeySize / 8);
- aes.IV = rfc2898.GetBytes(aes.BlockSize / 8);
- //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();
- }
- }
- ///
- /// 进行AES解密
- ///
- /// 要进行解密的字符串
- /// 解密使用的键
- /// 解密后的明文字符串
- public static string AesDecrypt(string dataToDecrypt, string key)
- {
- AesManaged aes = null;
- MemoryStream memoryStream = null;
- CryptoStream cryptoStream = null;
- try
- {
- //Generate a Key based on a Password, Salt and HMACSHA1 pseudo-random number generator
- Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(key, Encoding.UTF8.GetBytes(salt));
- //Create AES algorithm with 256 bit key and 128-bit block size
- aes = new AesManaged();
- aes.Key = rfc2898.GetBytes(aes.KeySize / 8);
- aes.IV = rfc2898.GetBytes(aes.BlockSize / 8);
- //Create Memory and Crypto Streams
- memoryStream = new MemoryStream();
- cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write);
- //Decrypt Data
- byte[] data = Convert.FromBase64String(dataToDecrypt);
- cryptoStream.Write(data, 0, data.Length);
- cryptoStream.FlushFinalBlock();
- //Return Decrypted String
- byte[] decryptBytes = memoryStream.ToArray();
- return Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);
- }
- finally
- {
- if (cryptoStream != null)
- cryptoStream.Close();
- if (memoryStream != null)
- memoryStream.Close();
- if (aes != null)
- aes.Clear();
- }
- }
- }
- }
直接调用,就可以进行字符串的加密,解密了。
阅读(3327) | 评论(0) | 转发(0) |