我寫了下面的類編碼和解碼字符串數據(對稱算法用一個密鑰):解碼和編碼字符串 - 爲對稱算法硬編碼KEY
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace MyProject.Classes
{
public static class SymmetricEncryption
{
private const string MyKey = "bla bla bla";
private static string _AlgorithmName;
public static string AlgorithmName
{
get { return _AlgorithmName; }
set { _AlgorithmName = value; }
}
public static string EncryptData(string ClearData)
{
// Convert string ClearData to byte array
byte[] ClearData_byte_Array = Encoding.UTF8.GetBytes(ClearData);
// Now Create The Algorithm
SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
Algorithm.Key = Encoding.UTF8.GetBytes(MyKey);
// Encrypt information
MemoryStream Target = new MemoryStream();
// Append IV
Algorithm.GenerateIV();
Target.Write(Algorithm.IV, 0, Algorithm.IV.Length);
// Encrypt Clear Data
CryptoStream cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(ClearData_byte_Array, 0, ClearData_byte_Array.Length);
cs.FlushFinalBlock();
// Output
byte[] Target_byte_Array = Target.ToArray();
string Target_string = Convert.ToBase64String(Target_byte_Array);
return Target_string;
}
public static string DecryptData(string EncryptedData)
{
byte[] EncryptedData_byte_Array = Convert.FromBase64String(EncryptedData);
// Now Create The Algorithm
SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
Algorithm.Key = Encoding.UTF8.GetBytes(MyKey);
// Decrypt information
MemoryStream Target = new MemoryStream();
// Read IV
int ReadPos = 0;
byte[] IV = new byte[Algorithm.IV.Length];
Array.Copy(EncryptedData_byte_Array, IV, IV.Length);
Algorithm.IV = IV;
ReadPos += Algorithm.IV.Length;
// Decrypt Encrypted Data
CryptoStream cs = new CryptoStream(Target, Algorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(EncryptedData_byte_Array, ReadPos, EncryptedData_byte_Array.Length - ReadPos);
cs.FlushFinalBlock();
// Output
byte[] Target_byte_Array = Target.ToArray();
string Target_string = Encoding.UTF8.GetString(Target_byte_Array);
return Target_string;
}
}
}
和使用象下面這樣:
protected void Page_Load(object sender, EventArgs e)
{
SymmetricEncryptionUtility.AlgorithmName = "TripleDES";
Response.Write(SymmetricEncryptionUtility.EncryptData("1234-4567-8910-2345"));
}
我對MyKey有一些問題 - >我們如何爲對稱算法使用硬編碼密鑰並將其用於上層類?
上部碼ERROR是象下面這樣:在當前web請求的
Server Error in '/' Application.
Specified key is not a valid size for this algorithm. Description: An unhandled exception occurred during the
執行。請查看堆棧跟蹤 以獲取有關該錯誤的更多信息以及源自 代碼的位置。
Exception Details:
System.Security.Cryptography.CryptographicException:指定鍵爲 不是這個算法有效的大小。
我該如何解決這個錯誤?
由於事先
親愛的喬諾謝謝你的回答... – MoonLight