问题描述
public static class CryptoHelper {
// This size of the IV (in bytes) must = (keysize / 8). Default keysize is 256,so the IV must be
// 32 bytes long. Using a 16 character string here gives us 32 bytes when converted to a byte array.
private const string initVector = "pemgail9uzpgzl88";
// This constant is used to determine the keysize of the encryption algorithm
private static int keysize = 256;
private static int getKeySize()
{
return 256;
}
//Encrypt
//public static byte[] EncryptString( string plainText,string passphrase ) {
public static byte[] EncryptString(string toEncrypt,string salt)
{
byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(toEncrypt);
byte[] keyBytes = new byte[126];
try
{
PasswordDeriveBytes password = new PasswordDeriveBytes(Encoding.UTF8.GetBytes(salt),null);
Debug.WriteLine(CryptoHelper.getKeySize());
Debug.WriteLine(password.ToString());
keyBytes = password.GetBytes(256 / 8);
} catch (Exception e)
{
Debug.WriteLine(e.StackTrace);
}
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes,initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream,encryptor,CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes,plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return cipherTextBytes;
}
........
调用“password.GetBytes(256 / 8);”导致不可捕获的 NullReferenceException 这仅在 UWP 应用处于发布模式时发生; UWP Debug以及Andorid和IOS都可以。
我还收到一条奇怪的调试消息:
“this._hash”战争“空”。
或
"this._hash" 是 "null"。 (已翻译)
在这里你可以看到它在行动 VS2019 Screenshot
toEncrypt “承载eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwiZXhwIjoxNjE3MDAyMTEyfQ.C0CaGgfibM4z55MoANI2CiohUyew09r3_D_TpcQ6n1c8LmQd8BusSyF1SMEIQ3cO5uxE9Tnau0ZAT6D3kN3NcQ”
盐 "9x83m74tzrx9387x4mz98374zt90x8m273z948734z59"
因为我看不到此问题的详细原因,因此无法找到解决方法。
解决方法
我试图使相同的代码工作。我找到的解决方案是替换:
PasswordDeriveBytes password = new PasswordDeriveBytes(Encoding.UTF8.GetBytes(salt),null);
与:
Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(passPhrase,Encoding.UTF8.GetBytes("12345678"));
并添加:
symmetricKey.Padding = PaddingMode.Zeros;