[英]How to create Aes 256bit Encryption with key in C# Windows Phone application?
我正在嘗試使用登錄屏幕中的密鑰創建Aes 256位加密。 我需要一個較大的加密字符串,因為我使用的是256位,但是它導致加密的字符串很小。 請對此提供幫助。
這是我的代碼
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);
}
}
}
}
另一類稱為密碼學:
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;
}
}
}
代替
string chars = System.Convert.ToBase64String(encryptedPassword);
做這個
Encoding.UTF8.GetString(encryptedPassword, 0, encryptedPassword.Length);
我認為wp8不允許您使用System.Text.Encoding.Default.GetString,您可以嘗試將其默認設置為UTF8,我假設密文全部使用拉丁字符。
你忘了沖洗:)
您正在調用encrypted = msEncrypt.ToArray();
在關閉並因此刷新CryptoStream
。 由於需要填充最后一個塊,因此並非所有字節都會被寫入。 如果使用加密的塊密碼模式或經過身份驗證的密碼,則始終需要刷新。 僅加密流密碼模式可能不需要您刷新流,因為每個位都可以單獨加密。
在實現中,如果我沒有記錯的話,您應該可以將msEncrypt.ToArray()
移到CryptoStream
的using
范圍之下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.