RSA加密,解密,加签,验签

RSA加密解密

RSA加密,解密我使用的是jsencypt,具体的使用参考:"https://github.com/travist/jsencrypt"

加密、签名 简介

数据加密:用公钥加密,只有用私钥解开,因为私钥只有你自己有,所以他保证了数据不能被别人看到

数据签名:用私钥加密,只能用公钥解密,任何人都可以用公钥验证。因为私钥只有你自己有,所以它可以保证数据只能是你发出的,不可能有别人发出,除非你得私钥丢失或被第三方破解出来。

rsa找的插件,直接上代码



RSA加签验签

需要注意的是:区分RSA私钥的类型,有pkcs1和pkcs8。pkcs8格式的私钥主要用于Java中。

  • pkcs1格式:
    • -----BEGIN RSA PRIVATE KEY-----

    • -----END RSA PRIVATE KEY------

  • pkcs8格式:
    • -----BEGIN PRIVATE KEY-----
    • -----END PRIVATE KEY----

加签验签必须要有前缀后缀否则会报错

let privateKey = '-----BEGIN PRIVATE KEY-----MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANG/4GW4WIt+vkRpMR + u6aXfH1mMvxFila4C0jMUyfvCZdWIDj4rsNM80EKOHoZYnS1w0kBzIZXeqCAFdLLOX0D4NGpiCtcn / shlI2 / cUUFgLyVDbLdace2y9WKVCH8ohOrw + 3wOFMoBZk2CWKHOYu + 0akkz7NCl0g0MZy9prpNJAgMBAAECgYBa7Bsg3QV9Cqb9zr + dpVvhLFRRpEJbDeomcVCfFf7spHsyUfUinBvdpbn9b8 / pmtYfkY2CpKXFaqxknRjWPcFqBce2jpgh5hJEfPXA1bqfYaSuGJVVER2t1TfbqvBNYdE56KjpZXkQx3dRg / V8M0JYpEz8uymxWDYWmPERk5 + DdQJBAPykfg + mu1NJdqnq5wNE8mAx0uBVg4gUCmSCATrICxvc8aDHQAT7FKNzphVaoaC299nWAuI0QkqhdZ96siHPVKcCQQDUiXWD2PPvtFT9yNw5cjKTfmj3gr7etuRsvX + ovWZusV21W1DSLD4GyAfzl8ju0EHdwSZ7L9Crs4Ryk6uHdqaPAkBgKnTZnEudrk7 + 6q04b1wbBZwRTDue5pH2JA43w8GGv5kx6 + YQf0oh1XmYk0EGnd7GClJarC23nrHZHKkFeZftAkAUz3TLOSYBdYXQ56bwlQbwvDLo8UthIUVShGeIjSsHcaR8SnmqapyUK2fj6RvKjme0n + H1s + PZvBUe5uinte1vAkEAm7FdzA5NrFw7hT7NNozsTjFdpaeIyWp1A2pc9X + Gh8Ynq3syZQj7Xi704l / 4yB5dInzQ6a + fH9BDvJOJ1B8Uxg ==-----END PRIVATE KEY-----';
    let publicKey = '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRv+BluFiLfr5EaTEfruml3x9ZjL8RYpWuAtIzFMn7wmXViA4 + K7DTPNBCjh6GWJ0tcNJAcyGV3qggBXSyzl9A + DRqYgrXJ / 7IZSNv3FFBYC8lQ2y3WnHtsvVilQh / KITq8Pt8DhTKAWZNglihzmLvtGpJM + zQpdINDGcvaa6TSQIDAQAB-----END PUBLIC KEY-----';
    // 加签
    let verify_rsa = new RSA.RSAKey()
    verify_rsa = RSA.KEYUTIL.getKey(privateKey);
    let str  = '123'
    let Sig = verify_rsa.signStringWithSHA1('signData', str);
    Sig = RSA.hex2b64(Sig)

    // 验签
    verify_rsa = RSA.KEYUTIL.getKey(publicKey)
    Sig = RSA.b64tohex(Sig)
    let flag = verify_rsa.verifyString("signData", Sig)
    console.log(flag) // true

转载于:https://www.cnblogs.com/mengxiangji/p/10827238.html

你可能感兴趣的:(RSA加密,解密,加签,验签)