他正在研究如何在我的应用程序中实现加密算法。他见过RC2。
一方面,我设法从 c# 加密和解密。
另一方面,我还设法从 SQL Server 加密和解密。
但是从 SQL Server 加密的内容,我无法从 C# 解密它,而且当你从 C# 加密时,我也无法从 SQL Server 解密。
当然加密密钥和初始向量是相同的。
我猜想使 SQL 服务器保持数据加密的原因不仅仅是二进制加密,而是增加了一些东西。
编辑:C#代码:
public static byte[] Cifrar(string dato, string clave, string vectorInicial)
{
byte[] plainText = Encoding.ASCII.GetBytes(dato);
byte[] keys = Encoding.ASCII.GetBytes(clave);
byte[] vecI = Encoding.ASCII.GetBytes(vectorInicial);
MemoryStream memdata = new MemoryStream();
RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
ICryptoTransform transform;
rc2.Mode = CipherMode.CBC;
transform = rc2.CreateEncryptor(keys, vecI);
CryptoStream encStream = new CryptoStream(memdata,transform,CryptoStreamMode.Write);
encStream.Write(plainText, 0, plainText.Length);
encStream.Close();
return memdata.ToArray();
}
public static string Descrifrar(byte[] dato,string clave, string vectorInicial)
{
byte[] keys = Encoding.ASCII.GetBytes(clave);
byte[] vecI = Encoding.ASCII.GetBytes(vectorInicial);
MemoryStream memdata = new MemoryStream();
RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
ICryptoTransform transform;
rc2.Mode = CipherMode.CBC;
transform = rc2.CreateDecryptor(keys, vecI);
CryptoStream encStream = new CryptoStream(memdata,transform,CryptoStreamMode.Write);
encStream.Write(dato, 0, dato.Length);
encStream.Close();
return Encoding.ASCII.GetString(memdata.ToArray());
}
对于加密我使用:
CifradoRC2.Cifrar("Perico", "sdsdfdsf323", "huihuihuih123");
T-SQL 代码:
CREATE SYMMETRIC KEY NuevaClaveDeCifrado WITH IDENTITY_VALUE = 'huihuihuih123',ALGORITHM = RC2,KEY_SOURCE = 'sdsdfdsf323' ENCRYPTION BY Password = 'dsjdkflJ435907NnmM#sX003';
CREATE PROCEDURE OpenSqlKeys
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
OPEN SYMMETRIC KEY NuevaClaveDeCifrado DECRYPTION BY PASSWORD ='dsjdkflJ435907NnmM#sX003';
END TRY
BEGIN CATCH
-- Handle non-existant key here
END CATCH
END
GO
CREATE FUNCTION Encrypt(@ValueToEncrypt varchar(max))
RETURNS varbinary(256)
AS
BEGIN
-- Declare the return variable here
DECLARE @Result varbinary(256)
SET @Result = EncryptByKey(Key_GUID('NuevaClaveDeCifrado'), @ValueToEncrypt)
-- Return the result of the function
RETURN @Result
END
GO
CREATE FUNCTION Decrypt(@ValueToDecrypt varbinary(256))
RETURNS varchar(max)
AS
BEGIN
-- Declare the return variable here
DECLARE @Result varchar(max)
SET @Result = DecryptByKey(@ValueToDecrypt)
-- Return the result of the function
RETURN @Result
END
加密“Perico”T-SQL的二进制结果:0x009C6828879054489426381EFD2E3FD501000000266B3AF2ED7029C1F567AF8119C5D458FCDE1E984B2262A0
C#:
0x9FC66B77905837F5
谢谢!