他のリンクは役に立ちません。mysqlデータベースに保存する前に文字列を暗号化しています。これは正常に機能していますが、取得したいときに、暗号化するデータの長さが無効なエラーです。暗号化が必要になる前は、varchar サイズ 500 のデータ型を使用していましたが、現在はサイズ 800 の varbinary を使用しています。
暗号化方法:
public static byte[] encryptStringToBytes(string plainText)
{
byte[] encrypted;
//create an Rijndael object
using (Rijndael rijAlg = Rijndael.Create())
{
//create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
//create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
復号化方法:
public static string decryptStringFromBytes(byte[] cipherText)
{
string plaintext = null;
//create an Rijndael object
using (Rijndael rijAlg = Rijndael.Create())
{
//create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
//create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
//read the decrypted bytes from the decrypting stream and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
結果セットからの取得
using (Rijndael myRijndael = Rijndael.Create())
{
temp5 = EncryptDecrypt.decryptStringFromBytes((byte[])reader.GetValue(reader.GetOrdinal("Body")));
}