我正在尝试使用登录屏幕中的密钥创建Aes 256位加密。我需要一个大的加密字符串,因为我使用256位但它导致小的加密字符串。我已经检查了很多样本但是所有的都是Windows桌面应用程序而不是Windows Phone应用程序。请帮忙解决这个问题。
这是我的代码
namespace SampleEncription
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
byte[] encryptedPassword;
// Create a new instance of the RijndaelManaged
// class. This generates a new key and initialization
// vector (IV).
using (var algorithm = new AesManaged())
{
algorithm.KeySize = 256;
algorithm.BlockSize = 128;
// Encrypt the string to an array of bytes.
encryptedPassword = Cryptology.EncryptStringToBytes("Password", algorithm.Key, algorithm.IV);
//string chars = encryptedPassword.Aggregate(string.Empty, (current, b) => current + b.ToString());
string chars = System.Convert.ToBase64String(encryptedPassword);
Debug.WriteLine(chars);
}
}
}
}
另一个名为cryptology的类:
namespace SampleEncription
{
class Cryptology
{
private const string Salt = "603deb1015ca71be2b73aef0857d7781";
private const int SizeOfBuffer = 1024 * 8;
internal static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
{
throw new ArgumentNullException("plainText");
}
if (key == null || key.Length <= 0)
{
throw new ArgumentNullException("key");
}
if (iv == null || iv.Length <= 0)
{
throw new ArgumentNullException("key");
}
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (var rijAlg = new AesManaged())
{
rijAlg.Key = key;
rijAlg.IV = iv;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
}
}
答案 0 :(得分:0)
而不是
string chars = System.Convert.ToBase64String(encryptedPassword);
这样做
Encoding.UTF8.GetString(encryptedPassword, 0, encryptedPassword.Length);
我认为wp8不允许你使用System.Text.Encoding.Default.GetString,你可以尝试将它默认为UTF8,我认为密文都是拉丁字符..
答案 1 :(得分:0)
你忘了冲洗:)
您在关闭之前调用encrypted = msEncrypt.ToArray();
,因此会刷新CryptoStream
。由于需要填充最后一个块,因此不会写入所有字节。如果使用分组密码加密模式或经过身份验证的密码,则始终需要刷新。只有流加密模式的加密可能不需要您刷新流,因为每个位都可以单独加密。
在您的实施中,如果我没有弄错的话,您应该能够msEncrypt.ToArray()
将using
移到CryptoStream
的{{1}}范围之下。