使用RSA-1280十六进制密钥加密字符串

本文关键字:加密 字符串 密钥 十六进制 RSA-1280 使用 | 更新日期: 2023-09-27 18:08:10

我一直在尝试用服务器发送给我的公共RSA密钥加密密码。

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;
        }

使用RSA-1280十六进制密钥加密字符串

您的公钥格式不正确。它不是一个CSP斑点。它是一个DER编码的SubjectPublicKeyInfo结构。您可以找到源代码来解析它,也可以自己编写。下面是此类代码的一个示例: