1
我一直在嘗試使用由服務器發送給我的公共RSA密鑰來加密密碼。C#使用公共RSA-1280十六進制密鑰加密字符串
var csp = new CspParameters(1, "Microsoft Strong Cryptographic Provider");
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(1280, csp);
byte[] key = ByteUtils.HexToBytes(client.RSAKey);
RSA.ImportCspBlob(key);
byte[] encrypted = RSA.Encrypt(Encoding.ASCII.GetBytes(password), true);
六角鍵以這樣的形式提供:
string key = "30819D300D06092A864886F70D010101050003818B0030818702818100C7BD672D8C634D443840AD809790852770D3A2E99F456D6516329E0205D0645C23FD001D4D070CEE368A20526FEB2402358C915D7E86102B1659AA8651C449C344599F72BE904B8E338E7002E9978453C5BBCCA51AC165AA265069E0EAB1411D11A2FFDD35E5A8296A6A2AF238945874E8206979B0A16E2E4260A161CAB5C905020111";
作爲字符串是320字節長十六進制格式,我假定關鍵是160個字節(RSA 1280) 使用這種方法,提供商一直在說「提供商的錯誤版本\ r \ n」。 我試過幾種方法,將其轉換爲Base64,只需將其導入爲ASCII/Unicode。目前爲止沒有任何工作
編輯:我HexToBytes功能(工作據我所知,它返回我正確的160-B排列):
public static byte[] HexToBytes(string pValue)
{
// FIRST. Use StringBuilder.
StringBuilder builder = new StringBuilder();
// SECOND... USE STRINGBUILDER!... and LINQ.
foreach (char c in pValue.Where(IsHexDigit).Select(Char.ToUpper))
{
builder.Append(c);
}
// THIRD. If you have an odd number of characters, something is very wrong.
string hexString = builder.ToString();
if (hexString.Length % 2 == 1)
{
//throw new InvalidOperationException("There is an odd number of hexadecimal digits in this string.");
// I will just add a zero to the end, who cares (0 padding)
Log.WriteLine(LogLevel.Debug, "Hexstring had an odd number of hexadecimal digits.");
hexString += '0';
}
byte[] bytes = new byte[hexString.Length/2];
// FOURTH. Use the for-loop like a pro :D
for (int i = 0, j = 0; i < bytes.Length; i++, j += 2)
{
string byteString = String.Concat(hexString[j], hexString[j + 1]);
bytes[i] = HexToByte(byteString);
}
return bytes;
}
你的HexToBytes方法是什麼樣的?該代碼中是否有錯誤? –
我很確定它從十六進制中返回一個字節數組,事情是它並不期待它是一個奇怪原因的關鍵。 –
'HexToBytes'對我來說看起來不對。看起來你正在顛倒字節的順序。 「StringBuilder」的整個使用看起來毫無意義且引發錯誤。 –