如何在JS/Node中使用RSA x509 2048公钥加密数据,js?

kq0g1dla  于 2023-04-29  发布在  Node.js
关注(0)|答案(1)|浏览(146)

提示模块使用This encryption
密码出错了

const encrypted = crypto.publicEncrypt( { key: `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAW3P7gObqvIjJA3L7ZMVDdJ5lLis4jpShq14xWtS3AvnStWV4xY2BQ74bE08PvomByQc585vM7/HQNj2JNwQXwbjhyL5noC5Da3YGt5RiPMARa61LVeBcN8pipJNZoaFSrpMeG1CE45NMNhAnphv0WXzdX+9sr2uateIOi3Ab5QIDAQAB`, padding: crypto.constants.RSA_PKCS1_PADDING, }, Buffer.from(cardData), );

误差

Error: error:1E08010C:DECODER routines::unsupported at Object.publicEncrypt (node:internal/crypto/cipher:79:12)

我也这样试过,但还是一样的错误

const publicKey = Buffer.from(    'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAW3P7gObqvIjJA3L7ZMVDdJ5lLis4jpShq14xWtS3AvnStWV4xY2BQ74bE08PvomByQc585vM7/HQNj2JNwQXwbjhyL5noC5Da3YGt5RiPMARa61LVeBcN8pipJNZoaFSrpMeG1CE45NMNhAnphv0WXzdX+9sr2uateIOi3Ab5QIDAQAB',
      'base64',
    );
    const encrypted = crypto.publicEncrypt(
      {
        key: publicKey,
        padding: crypto.constants.RSA_PKCS1_PADDING,
      },
      Buffer.from(cardData, 'base64'),
    );
flseospp

flseospp1#

很奇怪,但是当我把钥匙放进一个文件里的时候,它就起作用了,但是我不明白为什么

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFdAOCAQ8AMIIBCgKCAQEAv5yse9ka3ZQE0feuGtem
Yv3IqOlLck8zHUM7lTrdza6lXTszRSXfdO7jMb+L5C7e2QNFs+7sIX2OQJ6a+HG8
kr+jwJ4tS3c1sWtd9NXpsU40PE4MeNE5RqiNXjcDxA+L4OsEm/BlyFOEOh2epGyY
Ud5/iO3OiQFRNicomT2saQYAeqIwuELPs1XpLk9HLx5qPbm8fRrQhjeUD5TLO8b+
4yCnObe8vy/BMUwBfq+ieWADIjwWCMp2KTpMGLz48qnaD9kdrYJ0iyHqzb2mkDhd
Izkim24A3lWoYitJCBrrB2xM05sm9+OdCI1f7nPNJbl5URHobSwR94IRGT7CJcUj
vwIDAQAB
-----END PUBLIC KEY-----

然后读出来

const publicKey = fs.readFileSync('./rsaprivkey_public.key');
    const encryptedData = crypto.publicEncrypt(
      {
        key: Buffer.from(publicKey),
        padding: crypto.constants.RSA_PKCS1_PADDING,
      },
      Buffer.from(cardData),
    );

相关问题