公司最近对接的第三方API需要将发到那边的数据进行加密,加密使用的算法是MD5withRSA,已经提供了Java的MD5withRSA算法,但公司使用的是.Net开发的,在此做个记录.
需要添加一个名为BouncyCastle的NuGet程序包,公司内部使用的是itextsharp.dll组件,其实itextsharp.dll中已经包含了BouncyCastle,实现效果是一样的
.NET代码
/// <summary>
/// 数据加密(通过私钥进行加密)
/// </summary>
/// <param name="content">待加密字符串</param>
/// <param name="privateKey">私钥</param>
/// <returns>加密后字符串</returns>
public string Sign(string content, string privateKey)
{
byte[] pkcs8EncodedBytes = Convert.FromBase64String(privateKey.Replace("\r", "").Replace("\n", "").Replace(" ", ""));
AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(pkcs8EncodedBytes);
ISigner normalSig = SignerUtilities.GetSigner("MD5withRSA");
normalSig.Init(true, priKey);
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(content);
normalSig.BlockUpdate(byteData, 0, byteData.Length);
byte[] normalResult = normalSig.GenerateSignature();
return Convert.ToBase64String(normalResult);
}
/// <summary>
/// 验证签名
/// </summary>
/// <param name="content">待签名的字符串</param>
/// <param name="sign">加密后的文本</param>
/// <param name="publicKey">公钥文本</param>
/// <returns>是否一致</returns>
public static bool Verify(string content, string sign, string publicKey)
{
byte[] pubKeyBytes = Convert.FromBase64String(publicKey.Replace("\r", "").Replace("\n", "").Replace(" ", ""));
AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(pubKeyBytes);
ISigner signer = SignerUtilities.GetSigner("MD5withRSA");
signer.Init(false, pubKey);
var contentBytes = Encoding.GetEncoding("UTF-8").GetBytes(content);
signer.BlockUpdate(contentBytes, 0, contentBytes.Length);
return signer.VerifySignature(Convert.FromBase64String(sign));
}
Java代码
/**
* 签名
*
* @param data 组装好的字符串
* @param privateKey pcks8私钥去掉换行符与首尾
* @return 签名结果
* @throws Exception
*/
public String sign(String data, String privateKey) throws Exception {
String concatedString = data;
byte[] pkcs8EncodedBytes = Base64.getDecoder().decode(privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
Signature md5withrsa = Signature.getInstance("MD5withRSA");
md5withrsa.initSign(privKey);
md5withrsa.update(concatedString.getBytes());
byte[] res = md5withrsa.sign();
return Base64.getEncoder().encodeToString(res);
}
/**
* 验签
*
* @param content
* 组装好的字符串
* @param sign
* 验签串
* @param publicKey
* 公钥去掉换行符与首尾
* @return boolean
*/
public static boolean check(String content, String sign, String publicKey) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.getDecoder().decode(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
java.security.Signature signature = java.security.Signature.getInstance("MD5withRSA");
signature.initVerify(pubKey);
signature.update(content.getBytes());
return signature.verify(Base64.getDecoder().decode(sign));
} catch (Exception e) {
e.printStackTrace();
}
return false;
}