字符串格式的RSA公钥和私钥

时间:2018-09-01 13:35:01

标签: c#

如何使用提供为字符串的公共和私有RSA密钥进行加密和解密。因为我使用RSACryptoServiceProvider,所以它需要XML格式,因此有可能使用所提供的字符串。谢谢。

2 个答案:

答案 0 :(得分:0)

您必须解析初始字符串才能分别获取所有向量,公钥和指数。然后将此字符串转换为字节并使用以下代码作为示例:

RSAParameters parameters = new RSAParameters();

//here you have to set all provided exponents, vectors
parameters.Exponent = myExponent; //...and other properties

//then - create new RSA cryptoservise provider and import parameters
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.ImportParameters(parameters);

要将字符串转换为字节,请使用以下表达式-它已经过测试:

public static byte[] String2ByteArray(string Hex, int j = -2) =>
(Hex.StartsWith("0x") ? Hex = Hex.Substring(2) : Hex).Where((x, i) => i % 2 == 0)
.Select(x => byte.Parse(Hex.Substring(j += 2, 2), NumberStyles.HexNumber)).ToArray();
public static Action<string> writeOutput = (x) => Debug.WriteLine(x);

如果您得到这样的XML:

<RSAKeyValue>
   <Modulus>…</Modulus>
   <Exponent>…</Exponent>
   <P>…</P>
   <Q>…</Q>
   <DP>…</DP>
   <DQ>…</DQ>
   <InverseQ>…</InverseQ>
   <D>…</D>
</RSAKeyValue>

您可以解析此XML以检索所有参数。因此,将它们分配给

parameters.Modulus
parameters.Exponent
parameters.P
parameters.D
parameters.DP
parameters.DQ
parameters.InverseQ

答案 1 :(得分:0)

使用了Bouncy castle dll,将关键信息粘贴到文本文件中并使用以下代码解决了问题:

public string RSABouncyEncrypt(string content)
        {
            var bytesToEncrypt = Encoding.UTF8.GetBytes(content);
            AsymmetricKeyParameter keyPair;
            using (var reader = File.OpenText(@"E:\......\public.pem"))
            {
                keyPair = (AsymmetricKeyParameter)new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
            }   

            var engine = new RsaEngine();
            engine.Init(true, keyPair);

            var encrypted = engine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length);

            var cryptMessage = Convert.ToBase64String(encrypted);
            //Logs.Log.LogMessage("encrypted: " + cryptMessage);
            //Console.WriteLine(cryptMessage);

            //Decrypt before return statement to check that it has been encrypted correctly
            //RSADecrypt(cryptMessage);
            return cryptMessage;
        }

        public string RSADecrypt(string string64)
        {
            var bytesToDecrypt = Convert.FromBase64String(string64); // string to decrypt, base64 encoded

            AsymmetricCipherKeyPair keyPair;

            using (var reader = File.OpenText(@"E:\.....\private.pem"))
                keyPair = (AsymmetricCipherKeyPair)new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();

            var decryptEngine = new RsaEngine();
            decryptEngine.Init(false, keyPair.Private);

            var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));
            //Logs.Log.LogMessage("decrypted: " + decrypted);
            //Console.WriteLine(decrypted);
            return decrypted;
        }