.NET RSA解密、签名、验签

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

namespace API.Tools
{
    /// <summary>
    /// 类名:RSAFromPkcs8
    /// 功能:RSA解密、签名、验签
    /// 详细:该类对Java生成的密钥进行解密和签名以及验签专用类,不需要修改
    /// 版本:2.0
    /// 修改日期:2011-05-10
    /// 说明:
    /// 以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
    /// 该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
    /// </summary>
    public sealed class Signatory
    {
        /// <summary>
        /// 签名(C#解释证书导出的,会出现“数据不正确”的错误)
        /// </summary>
        /// <param name="privateKey">私钥</param>
        /// <param name="content">需要签名的内容</param>
        /// <param name="encode">编码格式</param>
        /// <returns></returns>
        public static string sign(string privateKey, string content, Encoding encode)
        {
            byte[] Data = encode.GetBytes(content);
            RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
            MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();

            byte[] signData = rsa.SignData(Data, m5);
            return Convert.ToBase64String(signData);
        }
/// <summary>
        /// 验证签名
        /// </summary>
        /// <param name="publicKey">公钥</param>
        /// <param name="content">需要验证的内容</param>
        /// <param name="signedString">签名结果</param>
        /// <param name="encode">编码格式</param>
        /// <returns></returns>
        public static bool verify(string publicKey, string content, string signedString, Encoding encode)
        {
            bool result = false;
            byte[] Data = encode.GetBytes(content);
            byte[] data = Convert.FromBase64String(signedString);
            RSAParameters paraPub = ConvertFromPublicKey(publicKey);
            RSACryptoServiceProvider rsaPub = new RSACryptoServiceProvider();
            rsaPub.ImportParameters(paraPub);

            MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();
            result = rsaPub.VerifyData(Data, m5, data);
            return result;
        }

        /// <summary>
        /// 解析java生成的pem文件私钥
        /// </summary>
        /// <param name="pemstr"></param>
        /// <returns></returns>
        private static RSACryptoServiceProvider DecodePemPrivateKey(String pemstr)
        {
            byte[] pkcs8privatekey;
            pkcs8privatekey = Convert.FromBase64String(pemstr);
            if (pkcs8privatekey != null)
            {

                RSACryptoServiceProvider rsa = DecodePrivateKeyInfo(pkcs8privatekey);
                return rsa;
            }
            else
                return null;
        }

        private static RSACryptoServiceProvider DecodePrivateKeyInfo(byte[] pkcs8)
        {

            byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] seq = new byte[15];

            MemoryStream mem = new MemoryStream(pkcs8);
            int lenstream = (int)mem.Length;
            BinaryReader binr = new BinaryReader(mem);    //wrap Memory Stream with BinaryReader for easy reading
            byte bt = 0;
            ushort twobytes = 0;

            try
            {

                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130)    //data read as little endian order (actual data order for Sequence is 30 81)
                    binr.ReadByte();    //advance 1 byte
                else if (twobytes == 0x8230)
                    binr.ReadInt16();    //advance 2 bytes
                else
                    return null;

                bt = binr.ReadByte();
                if (bt != 0x02)
                    return null;

                twobytes = binr.ReadUInt16();

                if (twobytes != 0x0001)
                    return null;

                seq = binr.ReadBytes(15);        //read the Sequence OID
                if (!CompareBytearrays(seq, SeqOID))    //make sure Sequence for OID is correct
                    return null;

                bt = binr.ReadByte();
                if (bt != 0x04)    //expect an Octet string
                    return null;

                bt = binr.ReadByte();        //read next byte, or next 2 bytes is  0x81 or 0x82; otherwise bt is the byte count
                if (bt == 0x81)
                    binr.ReadByte();
                else
                    if (bt == 0x82)
                        binr.ReadUInt16();
                //------ at this stage, the remaining sequence should be the RSA private key

                byte[] rsaprivkey = binr.ReadBytes((int)(lenstream - mem.Position));
                RSACryptoServiceProvider rsacsp = DecodeRSAPrivateKey(rsaprivkey);
                return rsacsp;
            }

            catch (Exception)
            {
                return null;
            }

            finally { binr.Close(); }

        }

        private static bool CompareBytearrays(byte[] a, byte[] b)
        {
            if (a.Length != b.Length)
                return false;
            int i = 0;
            foreach (byte c in a)
            {
                if (c != b[i])
                    return false;
                i++;
            }
            return true;
        }

        private static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
        {
            byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

            // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
            MemoryStream mem = new MemoryStream(privkey);
            BinaryReader binr = new BinaryReader(mem);    //wrap Memory Stream with BinaryReader for easy reading
            byte bt = 0;
            ushort twobytes = 0;
            int elems = 0;
            try
            {
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130)    //data read as little endian order (actual data order for Sequence is 30 81)
                    binr.ReadByte();    //advance 1 byte
                else if (twobytes == 0x8230)
                    binr.ReadInt16();    //advance 2 bytes
                else
                    return null;

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102)    //version number
                    return null;
                bt = binr.ReadByte();
                if (bt != 0x00)
                    return null;

                //------  all private key components are Integer sequences ----
                elems = GetIntegerSize(binr);
                MODULUS = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                E = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                D = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                P = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                Q = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DP = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DQ = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                IQ = binr.ReadBytes(elems);

                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSAParameters RSAparams = new RSAParameters();
                RSAparams.Modulus = MODULUS;
                RSAparams.Exponent = E;
                RSAparams.D = D;
                RSAparams.P = P;
                RSAparams.Q = Q;
                RSAparams.DP = DP;
                RSAparams.DQ = DQ;
                RSAparams.InverseQ = IQ;
                RSA.ImportParameters(RSAparams);
                return RSA;
            }
            catch (Exception)
            {
                return null;
            }
            finally { binr.Close(); }
        }

        private static int GetIntegerSize(BinaryReader binr)
        {
            byte bt = 0;
            byte lowbyte = 0x00;
            byte highbyte = 0x00;
            int count = 0;
            bt = binr.ReadByte();
            if (bt != 0x02)        //expect integer
                return 0;
            bt = binr.ReadByte();

            if (bt == 0x81)
                count = binr.ReadByte();    // data size in next byte
            else
                if (bt == 0x82)
                {
                    highbyte = binr.ReadByte();    // data size in next 2 bytes
                    lowbyte = binr.ReadByte();
                    byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                    count = BitConverter.ToInt32(modint, 0);
                }
                else
                {
                    count = bt;        // we already have the data size
                }

            while (binr.ReadByte() == 0x00)
            {    //remove high order zeros in data
                count -= 1;
            }
            binr.BaseStream.Seek(-1, SeekOrigin.Current);        //last ReadByte wasn‘t a removed zero, so back up a byte
            return count;
        }

        private static RSAParameters ConvertFromPublicKey(string pemFileConent)
        {

            byte[] keyData = Convert.FromBase64String(pemFileConent);
            if (keyData.Length < 162)
            {
                throw new ArgumentException("pem file content is incorrect.");
            }
            byte[] pemModulus = new byte[128];
            byte[] pemPublicExponent = new byte[3];
            Array.Copy(keyData, 29, pemModulus, 0, 128);
            Array.Copy(keyData, 159, pemPublicExponent, 0, 3);
            RSAParameters para = new RSAParameters();
            para.Modulus = pemModulus;
            para.Exponent = pemPublicExponent;
            return para;
        }
    }
}

上面的类在平常使用的时候,是没有问题的,但,我们在对接第三方支付(易联支付)时,遇到一个非常刺手的,签名不通过。

  • 签名证书,是从北京数字认证拿到,里面有一个文件xxxxx-Signature.pfx 和证书密码,我们需要从该文件中,使用openssl.exe工具,导出RSA公钥和私钥
  • 导出的公钥,发给合作平台配上,私钥用于数据签名
  • 签名时,使用导出的私钥进行。

问题来了,调用上面程序的sign()方法,解释私钥时,总报“数据不正解”或者“无效的私钥”之类的。更奇怪的是,该私钥在java下使用没有问题。联系了对方,对方试了好多几证书,只有我们的这个有问题。好吧,算倒霉吧。

解决方法:

.net里可以直接使用证书进行RSA签名:

        /// <summary>
        /// 签名,直接使用证书签名
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="password"></param>
        /// <param name="content"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string sign(string filePath,string password, string content, Encoding encode)
        {
            byte[] Data = encode.GetBytes(content);

            X509Certificate2 myX509 = new X509Certificate2(filePath, password, X509KeyStorageFlags.Exportable);
            var rsa = (RSACryptoServiceProvider)myX509.PrivateKey;
            MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();

            byte[] signData = rsa.SignData(Data, m5);
            return Convert.ToBase64String(signData);
        }

问题解决!

时间: 2024-08-27 16:28:41

.NET RSA解密、签名、验签的相关文章

RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密

原文:RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密 C#在using System.Security.Cryptography下有 DESCryptoServiceProvider RSACryptoServiceProvider  DESCryptoServiceProvider 是用于对称加密 RSACryptoServiceProvider是用于非对称加密  对称加密的意思:有一个密钥 相当于加密算法,加密用它来加

加解密/签名验签

一.我加密.签名的过程 1,生成18位随机密钥:rand 067870-544583-448433: 2,使用对方的公钥证书(cer文件),并使用“RSA”算法,对随机密钥的字节数组加密,得到一个字节数组,将其转化为小写的十六进制字符串:secretKey 07ed7542951980385e32c149039255aabf8009e1e98a9432db19755e45e07361d318b98393d431cad4f656df7bc254548bacc92c53aa9566fd9ca1105

openresty中使用私钥/公钥进行加密/解密/签名/验签。

对于公钥私钥的提取,详细请看http://www.cnblogs.com/dreamer-One/p/5621134.html另外付在线加解密工具链接:http://tool.chacuo.net/cryptrsaprikey--公钥local RSA_PUBLIC_KEY = [[ -----BEGIN RSA PUBLIC KEY----- MIGJAoGBAJ9YqFCTlhnmTYNCezMfy7yb7xwAzRinXup1Zl51517rhJq8W0wVwNt+ mcKwRzisA1S

.net core RSA 分段加密解密,签名验签(对接java)

参考地址: https://www.cnblogs.com/stulzq/p/7757915.html https://www.cnblogs.com/stulzq/p/8260873.html https://github.com/stulzq/RSAExtensions(XC.RSAUtil) https://www.cnblogs.com/stulzq/p/12053976.html https://github.com/stulzq/RSAExtensions (RSAExtension

JAVA 实现 基于RSA算法的签名验签

基本步骤 签名方: 1用sha1算出原文的摘要 2用私钥对摘要进行加密 3对密文进行BASE64编码 验证方: 1对密文进行BASE64解码 2用公钥对解码后的密文解密 3用sha1对原文计算摘要并和解密后的明文比对 上干货 //参数字符串         String userId="2312sd";         String orderId="232djfj";         String price="12312";         

eos中签名验签流程和eosjs中的加解密原理

关键词:eos 签名 验签 ecc dsa 加密 解密 eosjs aes 本文主要探讨两方面 1.eosjs中用密钥对进行加解密功能 2.eos中密钥对生成,签名和验签过程(私钥签名 公钥验签) 常用的加密算法 对称性加密算法 对称式加密就是加密和解密使用同一个密钥,信息接收双方都需事先知道密匙和加解密算法,之后便是对数据进行加解密了.对称加密算法用来对敏感数据等信息进行加密. 对称性加密算法有:AES.DES.3DES DES(Data EncryptionStandard):数据加密标准,

非对称加密解密与签名验签的关系

首先看一下各自的定义: 加密:发送方利用接收方的公钥对要发送的明文进行加密. 解密:接受方利用自己的私钥进行解密. 签名:发送方用一个哈希函数从报文文本中生成报文摘要,然后用自己的私人密钥对这个摘要进行加密,得到的就是这个报文对应的数字签名.通常来说,发送方会把数字签名和报文原文一并发送给接受者. 验签:接收方得到原始报文和数字签名后,用同一个哈希函数从报文中生成摘要A,另外,用发送方提供的公钥对数字签名进行解密,得到摘要B,对比A和B是否相同,就可以得知报文有没有被篡改过. 两者的目的不同,加

RSA签名验签

import android.util.Base64; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; /** * Author:JsonLu * DateTime:

RSA签名验签学习笔记

RSA私钥签名时要基于某个HASH算法,比如MD5或者SHA1等.之前我一直认为签名的过程是:先对明文做HASH计算,然后用私钥直接对HASH值加密.最近才发现不是那么简单,需要对HASH后的数据进行BER编码再加密. 先看一个例子. 公钥模:89 54 E6 61 C1 52 DB ED 07 57 50 04 AD B3 D2 A7 A9 8F E8 D8 20 5B 01 B2 E5 E4 7A 7B EE 80 E3 C0 13 11 D2 F9 AD C3 CC 5F 1D 96 AC

Java使用RSA加密解密签名及校验

由于项目要用到非对称加密解密签名校验什么的,于是参考<Java加密解密的艺术>写一个RSA进行加密解密签名及校验的Demo,代码很简单,特此分享! RSA加密解密类: package com.ihep; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; imp