兼容JAVA的RSA加密解密类

最近在进行支付系统的开发,其中遇到了一些平台是RSA算法进行加密解密和签名进行通讯、因为2个平台之间的区别采了不少坑,特地记录一下。

一、 算法依赖于 Org.BouncyCastle包,首先选择自己的项目,右键点击管理“NuGet程序包”.

兼容JAVA的RSA加密解密类_第1张图片
image.png

二、搜索“BouncyCastle”,下载最多的就是啦。

兼容JAVA的RSA加密解密类_第2张图片
image.png

三、下面是加密解密类,直接引入系统即可

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto;

namespace My.Common
{
    /// 
    /// 加密工具类
    /// 
    public static class EncryUtils
    {
             
        /// 
        /// RSAJava私钥转换
        /// 
        /// 
        /// 
        public static string RSAPrivateKeyJava2DotNet(string privateKey)
        {
            if (!string.IsNullOrEmpty(privateKey))
            {
                privateKey = privateKey.Trim().Replace(" ", "");
            }

            RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
            return string.Format(
                "{0}{1}

{2}

{3}{4}{5}{6}{7}
", Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()) ); } /// /// RSAJava公钥转换 /// /// /// public static string RSAPublicKeyJava2DotNet(string publicKey) { if (!string.IsNullOrEmpty(publicKey)) { publicKey = publicKey.Trim().Replace(" ", ""); } RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey)); return string.Format( "{0}{1}", Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()), Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()) ); } /// /// 用公钥对数据加密(使用私钥也可以) /// /// 需要加密的字符串 /// 公钥加密 /// public static string RSAEncryptByPublicKey(string message, string pubilcKey) { //保存明文文件的字节数组 Byte[] PlaintextData = Encoding.UTF8.GetBytes(message); RSACryptoServiceProvider RSACryptography = new RSACryptoServiceProvider(); RSACryptography.FromXmlString(pubilcKey); int MaxBlockSize = RSACryptography.KeySize / 8 - 11; //加密块最大长度限制 if (PlaintextData.Length <= MaxBlockSize) return Convert.ToBase64String(RSACryptography.Encrypt(PlaintextData, false)); using (MemoryStream PlaiStream = new MemoryStream(PlaintextData)) using (MemoryStream CrypStream = new MemoryStream()) { Byte[] Buffer = new Byte[MaxBlockSize]; int BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize); while (BlockSize > 0) { Byte[] ToEncrypt = new Byte[BlockSize]; Array.Copy(Buffer, 0, ToEncrypt, 0, BlockSize); Byte[] Cryptograph = RSACryptography.Encrypt(ToEncrypt, false); CrypStream.Write(Cryptograph, 0, Cryptograph.Length); BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize); } return Convert.ToBase64String(CrypStream.ToArray(), Base64FormattingOptions.None); } } /// /// 使用公钥对数据解密(使用私钥也可以) /// /// /// /// /// public static string DecryptPublicKeyJava(string publicKeyJava, string data, string encoding = "UTF-8") { if (string.IsNullOrEmpty(publicKeyJava)) { return string.Empty; } if (string.IsNullOrEmpty(data)) { return string.Empty; } RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKeyJava)); byte[] dataToDecrypt = Convert.FromBase64String(data); IAsymmetricBlockCipher rsaEngine = new RsaEngine(); rsaEngine = new Pkcs1Encoding(rsaEngine); // 这里是指定PCK1算法,如果是其他的算法请自行替换 rsaEngine.Init(false, rsaKeyParameters); string result = ""; for (int j = 0; j < dataToDecrypt.Length / 128; j++) { byte[] buf = new byte[128]; for (int i = 0; i < 128; i++) { buf[i] = dataToDecrypt[i + 128 * j]; } buf = rsaEngine.ProcessBlock(buf, 0, buf.Length); char[] asciiChars = new char[Encoding.GetEncoding(encoding).GetCharCount(buf, 0, buf.Length)]; Encoding.GetEncoding(encoding).GetChars(buf, 0, buf.Length, asciiChars, 0); result += new string(asciiChars); } return result; } /// /// RSA私钥签名算法 /// /// /// /// public static string RSASignByPrivateKey(string content, string privateKey) { RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(); rsaCsp.FromXmlString(privateKey); byte[] dataBytes = Encoding.UTF8.GetBytes(content); byte[] signatureBytes = rsaCsp.SignData(dataBytes, "SHA1"); return Convert.ToBase64String(signatureBytes); } /// /// RSA公钥签名算法 /// /// /// /// /// public static bool RsaVerifyByPublicKey(string content, string publicKey,string sign) { RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(); rsaCsp.FromXmlString(publicKey); //将base64签名数据转码为字节 byte[] orgin = Encoding.UTF8.GetBytes(content); byte[] signedBase64 = Convert.FromBase64String(sign); bool bVerify = rsaCsp.VerifyData(orgin, "SHA1", signedBase64); return bVerify; } } }

使用方法

1、使用EncryUtils.RSAPrivateKeyJava2DotNet 或者 EncryUtils.RSAPublicKeyJava2DotNet 方法。将JAVA的RSA密钥换转换为NET的密钥格式。

2、使用转换后的密钥进行加密,解密,签名等操作。

你可能感兴趣的:(兼容JAVA的RSA加密解密类)