码迷,mamicode.com
首页 > Web开发 > 详细

netcore2.x下 RSA加解密错误:Operation is not supported on this platform.

时间:2021-01-21 10:39:41      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:ace   sam   dem   new   car   mit   oid   provider   utf8   

代码如下:经过测试,在netcore3.x正常,在netframework下也正常,就是netcore2.x报错。

       /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="publickey"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RSAEncrypt(string publickey, string content)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(publickey);
            cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
            return Convert.ToBase64String(cipherbytes);
        }
        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="privatekey"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RSADecrypt(string privatekey, string content)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(privatekey);
            cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);
            return Encoding.UTF8.GetString(cipherbytes);
        }

改为:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Xml;

namespace RSADemoNetCore2._1
{
    public static class RSAHelper
    {
        private const string privateKey = "<RSAKeyValue><Modulus>ulFAqzRA8HCGbw2rg1kPHmcI5dWC6Ive2HTzzq9kocAREBfZLEC7dcnTPjA6ChnfBg6MphSBwBonEIwntOAOyY5FoZSoFN+KyDrllWqKLmqZOg8Tvtf55UsTOs9h8atgzEIE5t+mp3FYMJRxv0w+pWyMs5bmELeGAoafUGlMLOU=</Modulus><Exponent>AQAB</Exponent><P>5O8P2EogWjcxJJiNfv6u8i71cjsFhfP6h9O/hlXhOW87OljjeuXGa0wJnLdk63WnMcjk0i9z0Xl5GJ+5eni/Dw==</P><Q>0FhbREKVOQTFfTpHIAhwu0/V6CJadCksEkrxyQJmgSGVygpbPqdCk/c9cMVOniPwKu+9qpUa0IZ2NORBMWiUyw==</Q><DP>ZhwW1iLh4TtCyQ7d9anFADJfuY6HvSKAOPsCLvm5FjP9l92zwMohwRPOKb9G3RrB8xumq/UMVH84uvnq8axPkw==</DP><DQ>b/z+WcucYECzUuOvdYVz6ws3xIYqrsOuv8pu+ogCxyhhVm+Iqj3HqLc93E8COjjBEKM7BOUOu8V65mVGsaMwTw==</DQ><InverseQ>XMlElo7aJZrQu5YmA666ZvO9j98AxLeT9Abkc6xDHhJS5g90h1rEBoFfNEC+2Js7In7wmbcK/7KLqq5SURM/cA==</InverseQ><D>sYYxw+6p4W6V6MJxpVj6GtG5nKPvc3ux/TSSCWD81VGX8GmIt62F8Bk5eYuiAXXdFnxObwAjENLaXd3tB15lNu3+ag/OpOKkRvk+8Qv399celFUDXyit59PbbBffHVkiEhULLpf+2QWB/3Bjk60Gb3uNaC4ptzSi5zYGYY91exE=</D></RSAKeyValue>";
        private const string publicKey = "<RSAKeyValue><Modulus>ulFAqzRA8HCGbw2rg1kPHmcI5dWC6Ive2HTzzq9kocAREBfZLEC7dcnTPjA6ChnfBg6MphSBwBonEIwntOAOyY5FoZSoFN+KyDrllWqKLmqZOg8Tvtf55UsTOs9h8atgzEIE5t+mp3FYMJRxv0w+pWyMs5bmELeGAoafUGlMLOU=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

        public static byte[] Encrypt(byte[] encryptBytes, RSAEncryptionPadding padding)
        {
            using (var rsa = RSA.Create())
            {

                FromXmlString(rsa, publicKey);

                var maxBlockSize = GetMaxBlockSize(rsa, padding);

                if (encryptBytes.Length <= maxBlockSize)
                {
                    var @bytes = rsa.Encrypt(encryptBytes, padding);
                    return @bytes;
                }

                using (var memoryStream = new MemoryStream(encryptBytes))
                {
                    using (var readStream = new MemoryStream())
                    {
                        byte[] buffer = new byte[maxBlockSize];

                        int blockSize = memoryStream.Read(buffer, 0, maxBlockSize);

                        while (blockSize > 0)
                        {
                            var blockByte = new byte[blockSize];

                            Array.Copy(buffer, 0, blockByte, 0, blockSize);

                            var encrypts = rsa.Encrypt(blockByte, padding);

                            readStream.Write(encrypts, 0, encrypts.Length);

                            blockSize = memoryStream.Read(buffer, 0, maxBlockSize);
                        }

                        return readStream.ToArray();
                    }
                }
            }
        }

        public static byte[] Decrypt(byte[] decryptBytes, RSAEncryptionPadding padding)
        {
            using (var rsa = RSA.Create())
            {
                FromXmlString(rsa, privateKey);

                var maxBlockSize = rsa.KeySize / 8;

                if (decryptBytes.Length <= maxBlockSize)
                {
                    var @bytes = rsa.Decrypt(decryptBytes, padding);
                    return @bytes;
                }

                using (var memoryStream = new MemoryStream(decryptBytes))
                {
                    using (var readStream = new MemoryStream())
                    {
                        var buffer = new byte[maxBlockSize];

                        var blockSize = memoryStream.Read(buffer, 0, maxBlockSize);

                        while (blockSize > 0)
                        {
                            var blockByte = new byte[blockSize];

                            Array.Copy(buffer, 0, blockByte, 0, blockSize);

                            var decrypts = rsa.Decrypt(blockByte, padding);

                            readStream.Write(decrypts, 0, decrypts.Length);

                            blockSize = memoryStream.Read(buffer, 0, maxBlockSize);
                        }

                        return readStream.ToArray();
                    }
                }
            }
        }

        public static void FromXmlString(RSA rsa, string xmlString)
        {
            RSAParameters parameters = new RSAParameters();

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xmlString);

            if (xmlDoc.DocumentElement.Name.Equals("RSAKeyValue"))
            {
                foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
                {
                    switch (node.Name)
                    {
                        case "Modulus": parameters.Modulus = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break;
                        case "Exponent": parameters.Exponent = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break;
                        case "P": parameters.P = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break;
                        case "Q": parameters.Q = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break;
                        case "DP": parameters.DP = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break;
                        case "DQ": parameters.DQ = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break;
                        case "InverseQ": parameters.InverseQ = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break;
                        case "D": parameters.D = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break;
                    }
                }
            }
            else
            {
                throw new Exception("Invalid XML RSA key.");
            }

            rsa.ImportParameters(parameters);
        }

        static int GetMaxBlockSize(RSA rsa, RSAEncryptionPadding padding)
        {
            var offset = 0;
            if (padding.Mode == RSAEncryptionPaddingMode.Pkcs1)
            {
                offset = 11;
            }
            else
            {
                if (padding.Equals(RSAEncryptionPadding.OaepSHA1))
                {
                    offset = 42;
                }

                if (padding.Equals(RSAEncryptionPadding.OaepSHA256))
                {
                    offset = 66;
                }

                if (padding.Equals(RSAEncryptionPadding.OaepSHA384))
                {
                    offset = 98;
                }

                if (padding.Equals(RSAEncryptionPadding.OaepSHA512))
                {
                    offset = 130;
                }
            }
            return rsa.KeySize / 8 - offset;
        }
    }
}

使用:

  public static void Main(string[] args)
        {
            string encryptString = "需要加密的字符";
            var encryptBytes = Encoding.UTF8.GetBytes(encryptString);

            //加密后字节数组
            var resultBytes = RSAHelper.Encrypt(encryptBytes, RSAEncryptionPadding.Pkcs1);
            Console.WriteLine();

            //解密后字节数组
            var decryptBytes = RSAHelper.Decrypt(resultBytes, RSAEncryptionPadding.Pkcs1);

            //解密结果
            var result = Encoding.UTF8.GetString(decryptBytes);

            //比较加密字符串和解密结果是否相等
            Console.WriteLine(encryptString == result);
            Console.ReadKey();
        }

 

netcore2.x下 RSA加解密错误:Operation is not supported on this platform.

标签:ace   sam   dem   new   car   mit   oid   provider   utf8   

原文地址:https://www.cnblogs.com/25miao/p/14303701.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!