最近在進行支付系統(tǒng)的開發(fā)栏饮,其中遇到了一些平臺是RSA算法進行加密解密和簽名進行通訊荐糜、因為2個平臺之間的區(qū)別采了不少坑鳖链,特地記錄一下。
一媳友、 算法依賴于 Org.BouncyCastle包斯议,首先選擇自己的項目,右鍵點擊管理“NuGet程序包”.
二醇锚、搜索“BouncyCastle”哼御,下載最多的就是啦。
三焊唬、下面是加密解密類恋昼,直接引入系統(tǒng)即可
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
{
/// <summary>
/// 加密工具類
/// </summary>
public static class EncryUtils
{
/// <summary>
/// RSAJava私鑰轉(zhuǎn)換
/// </summary>
/// <param name="privateKey"></param>
/// <returns></returns>
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(
"<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
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())
);
}
/// <summary>
/// RSAJava公鑰轉(zhuǎn)換
/// </summary>
/// <param name="publicKey"></param>
/// <returns></returns>
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(
"<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned())
);
}
/// <summary>
/// 用公鑰對數(shù)據(jù)加密(使用私鑰也可以)
/// </summary>
/// <param name="message">需要加密的字符串</param>
/// <param name="pubilcKey">公鑰加密</param>
/// <returns></returns>
public static string RSAEncryptByPublicKey(string message, string pubilcKey)
{
//保存明文文件的字節(jié)數(shù)組
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);
}
}
/// <summary>
/// 使用公鑰對數(shù)據(jù)解密(使用私鑰也可以)
/// </summary>
/// <param name="publicKeyJava"></param>
/// <param name="data"></param>
/// <param name="encoding"></param>
/// <returns></returns>
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;
}
/// <summary>
/// RSA私鑰簽名算法
/// </summary>
/// <param name="content"></param>
/// <param name="privateKey"></param>
/// <returns></returns>
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);
}
/// <summary>
/// RSA公鑰簽名算法
/// </summary>
/// <param name="content"></param>
/// <param name="publicKey"></param>
/// <param name="sign"></param>
/// <returns></returns>
public static bool RsaVerifyByPublicKey(string content, string publicKey,string sign)
{
RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider();
rsaCsp.FromXmlString(publicKey);
//將base64簽名數(shù)據(jù)轉(zhuǎn)碼為字節(jié)
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密鑰換轉(zhuǎn)換為NET的密鑰格式。
2鸥滨、使用轉(zhuǎn)換后的密鑰進行加密嗦哆,解密,簽名等操作婿滓。