当前位置: 首页 > 工具软件 > Fes.js > 使用案例 >

Node.js使用jsrsasign实现SHA256withRSA加密算法

秦承安
2023-12-01

文档

安装

pnpm i jsrsasign 

代码示例

var rs = require("jsrsasign");

// 秘钥
var privateKeyString = `-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDl3qqZiBYqv9qT
55lohRxVJIbYOYHiGelaN5PaRpecOjOyOl03ZcgNsLLc9HfYrWXo7TyBGg+dYz2L
oauNPOrHxG7mxmBD1V7faTEjiYfwEqyZ4zpWHP+IHOwZaUE26HGVjVm7z1akmnb7
bC9fViXpjqH9Hj3+/s5omTBb992nCUDu9sXzHaQcE2WquTlkOuCvf/YtxhBZCaQE
vmP34GiYzR+Veihgs90KTKEqJyd0Hd72AK2xwJ2JfN3Idz2Z+3RqVlWXm1SgZPf9
8XNHJjq2gLMClpAMMR8sLvEljij+Rv6JZXEx2UuiSslVBYHJGsi6a5mHIGGucv9C
+9y+BGOFAgMBAAECggEBALrVP04oqPO4Gh1LCYpFXqDpXlxSaXnvW5ZDQ/4OkF2f
hLMg8vD63h4ad1ZVsS9AyGsIn7vDBdwDdFuQXNIgKCeURht2M3oO69ykMBdVSlLb
qsQtRxYE3cCw2UlSHnpVdTR7veqDfEWvcnOqG9reN1Rc5NbJhNREIFot4HtvvA1t
UqeWjgUN9Gb6hpBdJKmUfaXlBZvYysHkjsbPgDGtGljnnCHXZepGGKAJjWCh/JKz
JgcVeLEMKCqvd9KvJp1Ny3pdx0dQN1A2xF+CG/TaXmOt/WhrGk6k4YQ4hW60S4Va
PBum0HJapAkaR/LxjbP4DKEF2hHLiX/P/f9b/nHIcWUCgYEA9VRsfZ9xD6gEsPCl
EVwSTrzb8CD8kelt+PM/xdnmRjYwZ07vZO1qHXD/54yXxbx35UXJKzW6+hknWqKH
manLNd22xifbDWwz2gDUlAmHCPbz+ZfHG0wDOOo9EhcrOKXa6z1HBd6ufgnfC7WR
V0w/w3nkaVj3kDXpZAhXaN8nDJ8CgYEA794bPMyXuEIZgxJxXkEVpKB1yGxsknzu
/HrV4nKYMXTrGa+M04/CNfM/XgR3/q1jkBcdfvu0AgQyTR+bU+M/sRlYi0iiAwse
nbm4lpk6HmAHccqyYFwzG7zvNKZKUlEjMgDWn0z7QrCAiTK8P2pNBS37+40/Yr1M
kQno6ip8uVsCgYEA8t7RSMw/sbA0dLbHs5fix/BQDDmb0Re2t26ZA9XkEj4zTRLo
DJK9Kshjj2ewGSGr0F51+UEICfA89Y1RkN53Pqxv9Vwfj/o+muOXj7ae6FES11Va
17s4tW+vZelp8HrBb4EKftUlCcHb/kuRx0rFFU/mwCRDcZDtrQpU/o1sqyECgYEA
4Y9/FYFe+spNq0/gg724WIL7v2kV//qz0YDBOJyCOZ+0pQbL6vY4rvr7D7IsFLV/
9rOF7S9Masj/dD7QleYQsr0e4nt+vlXqiG9pAVU9reqnlX4Cl1KcTO0yE9R790SN
UCwxpsOBU4keleW71/ZiTwia+EYu4O8Z3RnwiKNDfhkCgYAbD04vFYQCijFls+om
WIFvp9CpRlNBDmxc4Ya4QanJoDTVdgr8r/GJv8Zqc/WpMIk5rb5scUyZbtc61JoV
dcyLpezQdAzGvZDIFo4IvcGiglLYEztT9YM7YNUBfmPstepH+CNs8eRdufO5mxLj
MHDrC6b7s1Lr3JcLJfPIUh0jkg==
-----END PRIVATE KEY-----
`;

// 获取签名
function getSHA256withRSA(content) {
  const key = rs.KEYUTIL.getKey(privateKeyString);
  // 创建 Signature 对象,设置签名编码算法
  const signature = new rs.KJUR.crypto.Signature({ alg: "SHA256withRSA" });
  // 初始化
  signature.init(key);

  signature.updateString(content);
  // 生成密文
  const originSign = signature.sign();
  // console.log(originSign)

  return rs.hextob64(originSign);
}

console.log(getSHA256withRSA("Hello Node.js"));

// cWn8W8irbs2WHZ5OXNbdMUcRjHN721KvJ2kL7GfIEcjpA0DdFj8N7nzw4RQRnMc90OxwE6c8YRaCVAfl3ZBBWrXpd+Ahc6uVIEa2YBn381QsFeU/cBfIx2LrEbrJw/w+J/4r7w+JXo8o9fMulVG2+DZVLKEFwyiUmG7OKUMIS6piUt+yIfpWrLX7bZ8bEFIo6BAQk89YqyrpxX32EQ7l9rPV/jDRXXxO5F4NclAy8YOwMla/ek5nPZ1U3u494nX6iNSJlNjfz6emKJiMJBTahFtFkShG6uugoqkPDXnOU8DokkJyFo6Nik81VHgx1oD6TTASne+OPBvFnXuTT47hOw==

在线生成非对称加密公钥私钥对、在线生成公私钥对、RSA Key pair create、生成RSA密钥对
http://web.chacuo.net/netrsakeypair

参考
Node.js 上的 SHA256WithRSA 其实好简单
jsrsasign使用笔记(加密,解密,签名,验签)

 类似资料: