rsa加签验签C#和js、java、微信小程序互通

js实现rsa加签验签

https://github.com/kjur/jsrsasign
11.1.0版本
解压选择需要的版本,这里选择all版本了
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>JS RSA加签验签</title>
</head>
<body></body>
<script src="jsrsasign-all-min.js"></script>
<script type="text/javascript">// 公钥let pk = "-----BEGIN PUBLIC KEY-----\n" +"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD3XSdz1MnzazBEN5KOfTx0IyVJ\n" +"Z5wb57isrCuHDhnYXwtmdhQalgII0fozeeFpMpAvlnmHC1kpW7XVGvZnLx3bWbCE\n" +"bf+pMSW4kmQuI+5cxRUJbCl7sdaODBrINgERHPICVC18AJLThEVMHyjuR6Jn4zQm\n" +"yYNbReSktY/BrFTvMQIDAQAB\n" +"-----END PUBLIC KEY-----";// 私钥let priK = "-----BEGIN PRIVATE KEY-----\n" +"MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAPddJ3PUyfNrMEQ3\n" +"ko59PHQjJUlnnBvnuKysK4cOGdhfC2Z2FBqWAgjR+jN54WkykC+WeYcLWSlbtdUa\n" +"9mcvHdtZsIRt/6kxJbiSZC4j7lzFFQlsKXux1o4MGsg2AREc8gJULXwAktOERUwf\n" +"KO5HomfjNCbJg1tF5KS1j8GsVO8xAgMBAAECgYEA6eG1JMrj63jEmStmMb1txG1a\n" +"mu4Q5z2QGgtr2HVXsIIlGEq6tWxyHf7TL4qkuz9onuYKn8n2Eqm44fZtVaBx+5ES\n" +"zRpIvlTvaxmVu0HZ1hYAzUw1XyRnXNMKpL5tT4GCjm8+QGPzlGxgXI1sNg8r9Jaw\n" +"9zRUYeA6LQR9RIMkHWUCQQD8QojjVoGjtiunoh/N8iplhUszZIavAEvmDIE+kVy+\n" +"pA7hvlukLw6JMc7cfTcnHyxDo9iHVIzrWlTuKRq9KWVLAkEA+wgJS2sgtldnCVn6\n" +"tJKFVwsHrWhMIU29msPPbNuWUD23BcKE/vehIyFu1ahNA/TiM40PEnzprQ5JfPxU\n" +"16S78wJANTfMLTnYy7Lo7sqTLx2BuD0wqjzw9QZ4/KVytsJv8IAn65P/PVn4FRV+\n" +"8KEx+3zmF7b/PT2nJRe/hycAzxtmlQJBAMrFwQxEqpXfoAEzx4lY2ZBn/nmaR/SW\n" +"4VNEXCbocVC7qT1j1R5HVMgV13uKiTtq8dUGWmhqsi7x3XayNK5ECPUCQQDZaAN6\n" +"tvIHApz9OLsXSw0jZirQ6KEYdharXbIVDy1W1sVE3lzLbqLdFp1bxAHQIvsYS5PM\n" +"A9veSJh372RLJKkj\n" +"-----END PRIVATE KEY-----";// 原文var src = "好厉害";src="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiMTU2MjEzNTc1MDEiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjQ4MDY5NjUyNDQ4NDY3NyIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0";// 创建 Signature 对象let signature = new KJUR.crypto.Signature({alg: "SHA1withRSA", prvkeypem: priK});    //!这里指定 私钥 pem!signature.updateString(src);let a = signature.sign();let sign = hextob64(a);console.log("jsrsasign: \n"+sign);// 验签// !要重新new 一个Signature, 否则, 取摘要和签名时取得摘要不一样, 导致验签误报失败(原因不明)!let signatureVf = new KJUR.crypto.Signature({alg: "SHA1withRSA", prvkeypem: pk});signatureVf.updateString(src);// !接受的参数是16进制字符串!let b = signatureVf.verify(b64tohex(sign));console.log("jsrsasign verify: " + b);
</script>
</html>

在这里插入图片描述
也可以换成SHA256withRSA

vue中使用

npm i jsrsasign

使用

import jsrsasign from 'jsrsasign';
let signData="";//原始数据
let sign="";//base64格式签名
let publicKey="";//公钥
let signatureVf = new jsrsasign.Signature({alg: "SHA256withRSA", prvkeypem: publicKey});
signatureVf.updateString(signData);
// !接受的参数是16进制字符串!
let b = signatureVf.verify(jsrsasign.b64tohex(sign));

微信小程序使用

找到npm/lib下jsrsasign.js,底部有export的js就是
在这里插入图片描述

import jsrsasign from './jsrsasign'
/*** 验签*/
function veritify(data,sign,publickKey){let signatureVf = new jsrsasign.Signature({alg: "SHA256withRSA", prvkeypem: publickKey});signatureVf.updateString(data);let b = signatureVf.verify(jsrsasign.b64tohex(sign));return b;
}

C# 实现rsa加签验签

新建.net core3.1项目
安装BouncyCastle.Cryptography 2.4.0

RSAHelper

using System;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;namespace RSACSharpJsStu01
{public class RSAHelper{/// <summary>/// 重写FromXmlString方法/// </summary>/// <param name="xmlString"></param>/// <returns></returns>public static RSACryptoServiceProvider FromXmlString(string xmlString){var rsa = new RSACryptoServiceProvider();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 = Convert.FromBase64String(node.InnerText);break;case "Exponent":parameters.Exponent = Convert.FromBase64String(node.InnerText);break;case "P":parameters.P = Convert.FromBase64String(node.InnerText);break;case "Q":parameters.Q = Convert.FromBase64String(node.InnerText);break;case "DP":parameters.DP = Convert.FromBase64String(node.InnerText);break;case "DQ":parameters.DQ = Convert.FromBase64String(node.InnerText);break;case "InverseQ":parameters.InverseQ = Convert.FromBase64String(node.InnerText);break;case "D":parameters.D = Convert.FromBase64String(node.InnerText);break;}}}else{throw new Exception("Invalid XML RSA key.");}rsa.ImportParameters(parameters);return rsa;}/// <summary>/// RSA公钥,从Java格式转.net格式(不依赖第三方包)/// </summary>/// <param name="publikKey"></param>/// <returns></returns>public static string RSAPublicKeyJava2DotNet(string publicKey){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>        /// RSA签名验证/// </summary> /// <param name="encryptSource">签名</param>/// <param name="c">验证的字符串</param>/// <param name="publicKey">公钥</param>/// <returns>是否相同,true验证成功,false验证失败。</returns>public static bool VerifySignature(string encryptSource, string compareString, string publicKey){try{//.net core2.2及其以下版本使用,重写FromXmlString(string)方法//using RSACryptoServiceProvider rsa = FromXmlString(RSAPublicKeyJava2DotNet(publicKey));var rsa = new RSACryptoServiceProvider();rsa.FromXmlString(RSAPublicKeyJava2DotNet(publicKey)); //.net core3.0直接使用,不需要重写byte[] signature = Convert.FromBase64String(encryptSource);//SHA1Managed sha1 = new SHA1Managed();SHA256Managed sha256 = new SHA256Managed();RSAPKCS1SignatureDeformatter df = new RSAPKCS1SignatureDeformatter(rsa);df.SetHashAlgorithm("SHA256");byte[] compareByte = sha256.ComputeHash(Encoding.UTF8.GetBytes(compareString));return df.VerifySignature(compareByte, signature);}catch (Exception){return false;}}/// <summary>/// RSA私钥,从Java格式转.net格式(不依赖第三方包)/// </summary>/// <param name="privateKey">私钥</param>/// <returns></returns>public static string RSAPrivateKeyJava2DotNet(string privateKey){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>/// 私钥签名/// </summary>/// <param name="contentForSign"></param>/// <param name="privateKey"></param>/// <returns></returns>public static string Sign(string contentForSign, string privateKey){var netKey = RSAPrivateKeyJava2DotNet(privateKey); //转换成适用于.net的私钥//var rsa = FromXmlString(netKey); //.net core2.2及其以下版本使用,重写FromXmlString(string)方法var rsa = new RSACryptoServiceProvider();rsa.FromXmlString(netKey); //.net core3.0直接使用,不需要重写var rsaClear = new RSACryptoServiceProvider();var paras = rsa.ExportParameters(true);rsaClear.ImportParameters(paras); //签名返回//var sha1 = new SHA1CryptoServiceProvider();using (var sha256 = new SHA256CryptoServiceProvider()){var signData = rsa.SignData(Encoding.UTF8.GetBytes(contentForSign), sha256);return Convert.ToBase64String(signData);}}}
}

接口如下

using System.Text;
using Microsoft.AspNetCore.Mvc;namespace RSACSharpJsStu01.Controllers
{[ApiController]public class IndexController : ControllerBase{// 公钥private string pk = //"-----BEGIN PUBLIC KEY-----\n" +"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD3XSdz1MnzazBEN5KOfTx0IyVJ\n" +"Z5wb57isrCuHDhnYXwtmdhQalgII0fozeeFpMpAvlnmHC1kpW7XVGvZnLx3bWbCE\n" +"bf+pMSW4kmQuI+5cxRUJbCl7sdaODBrINgERHPICVC18AJLThEVMHyjuR6Jn4zQm\n" +"yYNbReSktY/BrFTvMQIDAQAB\n"//+"-----END PUBLIC KEY-----";// 私钥private string priK = //"-----BEGIN PRIVATE KEY-----\n" +"MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAPddJ3PUyfNrMEQ3\n" +"ko59PHQjJUlnnBvnuKysK4cOGdhfC2Z2FBqWAgjR+jN54WkykC+WeYcLWSlbtdUa\n" +"9mcvHdtZsIRt/6kxJbiSZC4j7lzFFQlsKXux1o4MGsg2AREc8gJULXwAktOERUwf\n" +"KO5HomfjNCbJg1tF5KS1j8GsVO8xAgMBAAECgYEA6eG1JMrj63jEmStmMb1txG1a\n" +"mu4Q5z2QGgtr2HVXsIIlGEq6tWxyHf7TL4qkuz9onuYKn8n2Eqm44fZtVaBx+5ES\n" +"zRpIvlTvaxmVu0HZ1hYAzUw1XyRnXNMKpL5tT4GCjm8+QGPzlGxgXI1sNg8r9Jaw\n" +"9zRUYeA6LQR9RIMkHWUCQQD8QojjVoGjtiunoh/N8iplhUszZIavAEvmDIE+kVy+\n" +"pA7hvlukLw6JMc7cfTcnHyxDo9iHVIzrWlTuKRq9KWVLAkEA+wgJS2sgtldnCVn6\n" +"tJKFVwsHrWhMIU29msPPbNuWUD23BcKE/vehIyFu1ahNA/TiM40PEnzprQ5JfPxU\n" +"16S78wJANTfMLTnYy7Lo7sqTLx2BuD0wqjzw9QZ4/KVytsJv8IAn65P/PVn4FRV+\n" +"8KEx+3zmF7b/PT2nJRe/hycAzxtmlQJBAMrFwQxEqpXfoAEzx4lY2ZBn/nmaR/SW\n" +"4VNEXCbocVC7qT1j1R5HVMgV13uKiTtq8dUGWmhqsi7x3XayNK5ECPUCQQDZaAN6\n" +"tvIHApz9OLsXSw0jZirQ6KEYdharXbIVDy1W1sVE3lzLbqLdFp1bxAHQIvsYS5PM\n" +"A9veSJh372RLJKkj\n"//+"-----END PRIVATE KEY-----";[HttpGet("/rsa")]public string Get(){var src = "好厉害";src ="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiMTU2MjEzNTc1MDEiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjQ4MDY5NjUyNDQ4NDY3NyIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0";var sign = RSAHelper.Sign(src, priK);StringBuilder result = new StringBuilder();result.Append("加签结果:");result.Append(sign);var isSuccess = RSAHelper.VerifySignature(sign,src, pk);result.Append("验签结果:");result.Append(isSuccess + "");return result.ToString();}}
}

在这里插入图片描述
转化为RsaPemHelper

 public class PemHelper{static private Regex _PEMCode = new Regex(@"--+.+?--+|\s+");static private byte[] _SeqOID = new byte[] { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };static private byte[] _Ver = new byte[] { 0x02, 0x01, 0x00 };/// <summary>/// 用PEM格式密钥对创建RSA,支持PKCS#1、PKCS#8格式的PEM/// </summary>public static RSACryptoServiceProvider FromPEM(string pem){var rsaParams = new CspParameters();rsaParams.Flags = CspProviderFlags.UseMachineKeyStore;var rsa = new RSACryptoServiceProvider(rsaParams);var param = new RSAParameters();var base64 = _PEMCode.Replace(pem, "");var data = RSAUnitHelper.Base64DecodeBytes(base64);if (data == null){throw new Exception("PEM内容无效");}var idx = 0;//读取长度Func<byte, int> readLen = (first) => {if (data[idx] == first){idx++;if (data[idx] == 0x81){idx++;return data[idx++];}else if (data[idx] == 0x82){idx++;return (((int)data[idx++]) << 8) + data[idx++];}else if (data[idx] < 0x80){return data[idx++];}}throw new Exception("PEM未能提取到数据");};//读取块数据Func<byte[]> readBlock = () => {var len = readLen(0x02);if (data[idx] == 0x00){idx++;len--;}var val = data.sub(idx, len);idx += len;return val;};//比较data从idx位置开始是否是byts内容Func<byte[], bool> eq = (byts) => {for (var i = 0; i < byts.Length; i++, idx++){if (idx >= data.Length){return false;}if (byts[i] != data[idx]){return false;}}return true;};if (pem.Contains("PUBLIC KEY")){/****使用公钥****///读取数据总长度readLen(0x30);if (!eq(_SeqOID)){throw new Exception("PEM未知格式");}//读取1长度readLen(0x03);idx++;//跳过0x00//读取2长度readLen(0x30);//Modulusparam.Modulus = readBlock();//Exponentparam.Exponent = readBlock();}else if (pem.Contains("PRIVATE KEY")){/****使用私钥****///读取数据总长度readLen(0x30);//读取版本号if (!eq(_Ver)){throw new Exception("PEM未知版本");}//检测PKCS8var idx2 = idx;if (eq(_SeqOID)){//读取1长度readLen(0x04);//读取2长度readLen(0x30);//读取版本号if (!eq(_Ver)){throw new Exception("PEM版本无效");}}else{idx = idx2;}//读取数据param.Modulus = readBlock();param.Exponent = readBlock();param.D = readBlock();param.P = readBlock();param.Q = readBlock();param.DP = readBlock();param.DQ = readBlock();param.InverseQ = readBlock();}else{throw new Exception("pem需要BEGIN END标头");}rsa.ImportParameters(param);return rsa;}/// <summary>/// 将RSA中的密钥对转换成PEM格式,usePKCS8=false时返回PKCS#1格式,否则返回PKCS#8格式,如果convertToPublic含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响/// </summary>public static string ToPEM(RSACryptoServiceProvider rsa, bool convertToPublic, bool usePKCS8){var ms = new MemoryStream();//写入一个长度字节码Action<int> writeLenByte = (len) => {if (len < 0x80){ms.WriteByte((byte)len);}else if (len <= 0xff){ms.WriteByte(0x81);ms.WriteByte((byte)len);}else{ms.WriteByte(0x82);ms.WriteByte((byte)(len >> 8 & 0xff));ms.WriteByte((byte)(len & 0xff));}};//写入一块数据Action<byte[]> writeBlock = (byts) => {var addZero = (byts[0] >> 4) >= 0x8;ms.WriteByte(0x02);var len = byts.Length + (addZero ? 1 : 0);writeLenByte(len);if (addZero){ms.WriteByte(0x00);}ms.Write(byts, 0, byts.Length);};//根据后续内容长度写入长度数据Func<int, byte[], byte[]> writeLen = (index, byts) => {var len = byts.Length - index;ms.SetLength(0);ms.Write(byts, 0, index);writeLenByte(len);ms.Write(byts, index, len);return ms.ToArray();};if (rsa.PublicOnly || convertToPublic){/****生成公钥****/var param = rsa.ExportParameters(false);//写入总字节数,不含本段长度,额外需要24字节的头,后续计算好填入ms.WriteByte(0x30);var index1 = (int)ms.Length;//固定内容// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"ms.writeAll(_SeqOID);//从0x00开始的后续长度ms.WriteByte(0x03);var index2 = (int)ms.Length;ms.WriteByte(0x00);//后续内容长度ms.WriteByte(0x30);var index3 = (int)ms.Length;//写入ModuluswriteBlock(param.Modulus);//写入ExponentwriteBlock(param.Exponent);//计算空缺的长度var byts = ms.ToArray();byts = writeLen(index3, byts);byts = writeLen(index2, byts);byts = writeLen(index1, byts);return "-----BEGIN PUBLIC KEY-----\n" + RSAUnitHelper.TextBreak(RSAUnitHelper.Base64EncodeBytes(byts), 64) + "\n-----END PUBLIC KEY-----";}else{/****生成私钥****/var param = rsa.ExportParameters(true);//写入总字节数,后续写入ms.WriteByte(0x30);int index1 = (int)ms.Length;//写入版本号ms.writeAll(_Ver);//PKCS8 多一段数据int index2 = -1, index3 = -1;if (usePKCS8){//固定内容ms.writeAll(_SeqOID);//后续内容长度ms.WriteByte(0x04);index2 = (int)ms.Length;//后续内容长度ms.WriteByte(0x30);index3 = (int)ms.Length;//写入版本号ms.writeAll(_Ver);}//写入数据writeBlock(param.Modulus);writeBlock(param.Exponent);writeBlock(param.D);writeBlock(param.P);writeBlock(param.Q);writeBlock(param.DP);writeBlock(param.DQ);writeBlock(param.InverseQ);//计算空缺的长度var byts = ms.ToArray();if (index2 != -1){byts = writeLen(index3, byts);byts = writeLen(index2, byts);}byts = writeLen(index1, byts);var flag = " PRIVATE KEY";if (!usePKCS8){flag = " RSA" + flag;}return "-----BEGIN" + flag + "-----\n" + RSAUnitHelper.TextBreak(RSAUnitHelper.Base64EncodeBytes(byts), 64) + "\n-----END" + flag + "-----";}}}

如果有部分密钥加密解密报错可以使用PemHelper.FromPEM替代FromXmlString
可以看到js加签和C#加签结果一样,所以验签也是通过的

java代码实现

SHA256withRSAUtil.java

package com.wujialiang;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;public class SHA256withRSAUtil {private static final String RSA = "RSA";private static final String SHA256WITHRSA = "SHA256withRSA";/*** 生成RSA密钥* @return* @throws NoSuchAlgorithmException*/public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);keyPairGenerator.initialize(2048, new SecureRandom());return keyPairGenerator.genKeyPair();}/*** 获取私钥* @param base64* @return*/public static PrivateKey getPrivateKey(String base64) throws Exception {// 解码Base64字符串回字节数组byte[] encodedPrivateKey = Base64.getDecoder().decode(base64);// 使用PKCS8EncodedKeySpec和KeyFactory来加载私钥PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);KeyFactory kf = KeyFactory.getInstance(RSA);PrivateKey privateKey = kf.generatePrivate(keySpec);return privateKey;}/*** 获取私钥* @param base64* @return*/public static PublicKey getPublicKey(String base64) throws Exception {// 解码Base64字符串回字节数组byte[] encodedPrivateKey = Base64.getDecoder().decode(base64);// 使用PKCS8EncodedKeySpec和KeyFactory来加载私钥//PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedPrivateKey);KeyFactory kf = KeyFactory.getInstance(RSA);PublicKey publicKey = kf.generatePublic(keySpec);return publicKey;}/*** 使用私钥对明文进行签名** @param plainText  明文* @param privateKey 私钥* @return 签名结果* @throws Exception 签名异常*/public static String sign(String plainText, PrivateKey privateKey) throws Exception {Signature signature = Signature.getInstance(SHA256WITHRSA);signature.initSign(privateKey);signature.update(plainText.getBytes());return Base64.getEncoder().encodeToString(signature.sign());}/*** 使用公钥对签名进行验证** @param plainText 明文* @param signature 签名结果* @param publicKey 公钥* @return 验证结果,true表示验证通过,false表示验证失败* @throws Exception 验证异常*/public static boolean verify(String plainText, String signature, PublicKey publicKey) throws Exception {Signature signatureInstance = Signature.getInstance(SHA256WITHRSA);signatureInstance.initVerify(publicKey);signatureInstance.update(plainText.getBytes());byte[] decodedSignature = Base64.getDecoder().decode(signature);return signatureInstance.verify(decodedSignature);}
}

使用

package com.wujialiang;/*** Hello world!*/
public class App {public static void main(String[] args) {// 生成RSA密钥对
//        KeyPair keyPair = generateKeyPair();
//        PrivateKey privateKey = keyPair.getPrivate();
//        PublicKey publicKey = keyPair.getPublic();// 公钥String pk = //"-----BEGIN PUBLIC KEY-----\n" +"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD3XSdz1MnzazBEN5KOfTx0IyVJ\n" +"Z5wb57isrCuHDhnYXwtmdhQalgII0fozeeFpMpAvlnmHC1kpW7XVGvZnLx3bWbCE\n" +"bf+pMSW4kmQuI+5cxRUJbCl7sdaODBrINgERHPICVC18AJLThEVMHyjuR6Jn4zQm\n" +"yYNbReSktY/BrFTvMQIDAQAB\n"//+"-----END PUBLIC KEY-----";// 私钥String priK = //"-----BEGIN PRIVATE KEY-----\n" +"MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAPddJ3PUyfNrMEQ3\n" +"ko59PHQjJUlnnBvnuKysK4cOGdhfC2Z2FBqWAgjR+jN54WkykC+WeYcLWSlbtdUa\n" +"9mcvHdtZsIRt/6kxJbiSZC4j7lzFFQlsKXux1o4MGsg2AREc8gJULXwAktOERUwf\n" +"KO5HomfjNCbJg1tF5KS1j8GsVO8xAgMBAAECgYEA6eG1JMrj63jEmStmMb1txG1a\n" +"mu4Q5z2QGgtr2HVXsIIlGEq6tWxyHf7TL4qkuz9onuYKn8n2Eqm44fZtVaBx+5ES\n" +"zRpIvlTvaxmVu0HZ1hYAzUw1XyRnXNMKpL5tT4GCjm8+QGPzlGxgXI1sNg8r9Jaw\n" +"9zRUYeA6LQR9RIMkHWUCQQD8QojjVoGjtiunoh/N8iplhUszZIavAEvmDIE+kVy+\n" +"pA7hvlukLw6JMc7cfTcnHyxDo9iHVIzrWlTuKRq9KWVLAkEA+wgJS2sgtldnCVn6\n" +"tJKFVwsHrWhMIU29msPPbNuWUD23BcKE/vehIyFu1ahNA/TiM40PEnzprQ5JfPxU\n" +"16S78wJANTfMLTnYy7Lo7sqTLx2BuD0wqjzw9QZ4/KVytsJv8IAn65P/PVn4FRV+\n" +"8KEx+3zmF7b/PT2nJRe/hycAzxtmlQJBAMrFwQxEqpXfoAEzx4lY2ZBn/nmaR/SW\n" +"4VNEXCbocVC7qT1j1R5HVMgV13uKiTtq8dUGWmhqsi7x3XayNK5ECPUCQQDZaAN6\n" +"tvIHApz9OLsXSw0jZirQ6KEYdharXbIVDy1W1sVE3lzLbqLdFp1bxAHQIvsYS5PM\n" +"A9veSJh372RLJKkj\n"//+"-----END PRIVATE KEY-----";// 明文String src = "好厉害";src ="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiMTU2MjEzNTc1MDEiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjQ4MDY5NjUyNDQ4NDY3NyIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0";//私钥签名String c = null;try {c = SHA256withRSAUtil.sign(src, SHA256withRSAUtil.getPrivateKey(priK.replace("\n","")));System.out.println(c);//公钥验签(true表示验证通过,false表示验证失败)System.out.println("验证结果:" + SHA256withRSAUtil.verify(src, c, SHA256withRSAUtil.getPublicKey(pk.replace("\n",""))));} catch (Exception e) {throw new RuntimeException(e);}}
}

在这里插入图片描述

可以看到java加签和C#、js加签结果一样,所以验签也是通过的

参考

rsa js和java互通
C# rsa加签验签

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/30707.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

有趣网站分享 - 生成 O‘Reilly 类型封面

文章目录 网站介绍效果 网站介绍 –> O’RLY 封面工厂 https://orly.nanmu.me 你可以… 设置文本内容 选择图片 选择颜色 效果 2024-06-20&#xff08;四&#xff09;

前端网页开发学习(HTML+CSS+JS)有这一篇就够!

目录 HTML教程 ▐ 概述 ▐ 基础语法 ▐ 文本标签 ▐ 列表标签 ▐ 表格标签 ▐ 表单标签 CSS教程 ▐ 概述 ▐ 基础语法 ▐ 选择器 ▐ 修饰文本 ▐ 修饰背景 ▐ 透明度 ▐ 伪类 ▐ 盒子模型 ▐ 浮动 ▐ 定位 JavaScript教程 ▐ 概述 ▐ 基础语法 ▐ 函数 …

契约锁电子签章平台 add 远程命令执行漏洞复现(XVE-2023-23720)

0x01 产品简介 契约锁电子签章平台是上海亘岩网络科技有限公司推出的一套数字签章解决方案。契约锁为中大型组织提供“数字身份、电子签章、印章管控以及数据存证服务”于一体的数字可信基础解决方案,可无缝集成各类系统,让其具有电子化签署的能力,实现组织全程数字化办公。通…

还在为Android开发找不到图片测试资源发愁吗? DummyImage来助你加速开发

使用 DummyImage 模拟电影应用数据 在开发和测试过程中&#xff0c;模拟数据是不可或缺的工具。它可以帮助我们在没有真实数据的情况下测试应用程序的功能和性能。本文将介绍如何使用 [DummyImage]https://dummyimage.com生成占位符图像来模拟电影应用的数据&#xff0c;并深入…

专家观点∣企企通采购供应链数字化总监于海生:如何利用数字化技术重构采购流程,推动企业降本增效?

摘要 数字化转型现已成为企业提升竞争力、实现降本增效的必由之路。企业应主动参与到数字经济的建设中&#xff0c;以数据资源为关键要素&#xff0c;以现代信息网络为主要载体&#xff0c;以信息通信技术的有效使用作为效率提升和经济结构优化的重要推动力的一系列经济活动&a…

80W大功率钓鱼灯调光调色方案 | 非同步降压 LED 驱动芯片FP7195,将PWM信号转为模拟信号进行调光,深度可达0.1%

夜钓作为一种受欢迎的休闲娱乐方式&#xff0c;随着LED照明技术的不断发展&#xff0c;钓鱼爱好者们对于钓鱼灯的光照效果和调光调色功能提出了更高的要求。传统的调光方案往往无法满足钓鱼爱好者对于光线亮度和色温的精准控制需求。 对此&#xff0c;我司推出一个80W大功率夜钓…

部署RAC到单实例ADG(11G)

服务器信息 主库RAC环境信息 主库RAC基本环境 节点1 节点2 OS centos 7.9 centos 7.9 数据库版本 11.2.0.4 11.2.0.4 规格 1C4G 1C4G 主机名 racdb01 racdb02 public ip 192.168.40.135 192.168.40.145 vip 192.168.40.13 192.168.40.14 private ip 192…

【开关电源】Buck 降压电路

文章目录 前言基本组成工作原理电路特点工作模式设计与实现 前言 Buck降压电路&#xff0c;也称为降-降&#xff08;step-down&#xff09;转换器&#xff0c;是一种直流-直流&#xff08;DC-DC&#xff09;电源转换器&#xff0c;用于将输入电压转换为较低的输出电压。这种电…

小林图解系统-二.硬件结构 2.7为什么0.1+0.2不等于0.3?

为什么负数要用补码表示&#xff1f; 十进制转二进制&#xff1a;除2取余法 [整数类型]的数字在计算机的存储方式&#xff1a;int类型&#xff0c;32位&#xff0c;最高位[符号标志位]&#xff0c;正数符号位0&#xff0c;负数的符号位1&#xff0c;剩余的31位则表示2进制数据…

计算机网络 —— 应用层(电子邮件)

计算机网络 —— 应用层&#xff08;电子邮件&#xff09; 电子邮件发送电子邮件的过程SMTP特性工作流程 电子邮件格式MIME关键组件工作方式 POP/IMAPPOP&#xff08;邮局协议&#xff09;IMAP&#xff08;因特网邮件访问协议&#xff09; 基于万维网的电子邮箱特点优势常见的基…

gorm 一对多

type Author struct {AID int gorm:"primary_key;AUTO_INCREMENT"Name stringAge stringSex string//关联关系Article []Article gorm:"ForeignKey:Auid;AssociationForeignKey:AID" } type Article struct {ArId int gorm:"primary_key;AUTO_I…

TF-IDF在现代搜索引擎优化策略中的作用

TF-IDF&#xff08;Term Frequency-Inverse Document Frequency&#xff09;是一种用于文本挖掘和信息检索的统计方法&#xff0c;用来评估一个词语对于一个文档或一个语料库的重要程度。TF-IDF算法结合了词频&#xff08;TF&#xff09;和逆文档频率&#xff08;IDF&#xff0…

软考高级资格是否等于高级工程师或者是否拥有职称?

软考采用"考试取代评审"的方式&#xff0c;一旦通过考试&#xff0c;就不再需要进行相应的职称认定和评审工作。取得考试通过证书意味着具备了相应工作岗位的水平和职称资格。软考的初级、中级、高级分别对应着技术员/助理工程师、工程师和高级工程师这些职称。 大多…

osi七层参考模型和tcp/ip模型的区别与相似之处

osi七层参考模型&#xff1a; 2.tcp/ip四层参考模型&#xff1a; osi七层参考模型与tcp/ip四层参考模型的相似与区别&#xff1a; 相同点&#xff1a; 2者都是模型化层次化 下层对上层提供服务支持 每层协议彼此相互独立 不同点&#xff1a;OSI先有模型才有协议 TCP/IP先有…

MK米客方德 SD NAND 功耗对比

在这个数据驱动的时代&#xff0c;MK米客方德在工业存储领域不断突破&#xff0c;凭借卓越的产品和服务赢得了广泛的客户认可。我们自主研发的嵌入式存储芯片已实现规模化量产&#xff0c;而我们最新一代的工业级SD NAND—AST系列也已正式推出。 该产品采用LGA-8(6*8mm)封装&am…

为什么选择飞速(FS)25G SFP28光模块?

25G SFP28光模块是一种传输速率为25Gbps的光模块。与传统的10G光模块相比&#xff0c;它具有更高的端口密度&#xff0c;可以通过减少TOR交换机和线缆的数量来节省运营成本。同时&#xff0c;25G光模块为中小型数据中心提供更节能高效的选择&#xff0c;非常适合连接中小型数据…

.NET C# 使用GDAL读取FileGDB要素类

.NET C# 使用GDAL读取FileGDB要素类 目录 .NET C# 使用GDAL读取FileGDB要素类1 环境2 Nuget3 Code 1 环境 VisualStudio2022 .NET6 GDAL 3.7.5 2 Nuget 3 Code using OSGeo.OGR; using OSGeo.OSR;namespace TestGDAL {internal class Program{static void Main(string[] a…

浅谈配置元件之Java默认请求

浅谈配置元件之Java默认请求 1.简介 “Java默认请求”&#xff08;虽然直接名为"Java Request"更常见&#xff09;是一个高级配置元件&#xff0c;它允许用户通过Java代码自定义请求逻辑&#xff0c;为测试提供了极高的灵活性和扩展性。 2.Java请求组件概述 在JM…

Ubuntu/Linux系统安装JDK1.8(带jdk1.8资源和操作教程)

文章目录 前言一、JDK1.8下载二、上传三、安装四、配置环境变量五、查看总结 前言 &#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;Ubuntu/Linux jdk1.8安装包&#xff…

【机器学习】【深度学习】MXnet神经网络图像风格迁移学习简介

使用部分 一、编程环境 编程环境使用Windows11上的Anaconda环境&#xff0c;Python版本为3.6. 关于Conda环境的建立和管理&#xff0c;可以参考我的博客&#xff1a;【Anaconda】【Windows编程技术】【Python】Anaconda的常用命令及实操 二、项目结构&#xff08;代码非原创…