用NODE RSA JS 加密解密正常,用JAVA RSAUtils工具类加密解密正常。但是用node加密玩的java解密不了。原因:node默认的是

DEFAULT_ENCRYPTION_SCHEME = 'pkcs1_oaep'  而java中默认的是pkcs1。

node-rsa源码:https://github.com/rzcoder/node-rsa/blob/ea5c17d9351c857c0594d7921c596ff5636882f1/src/NodeRSA.js

var DEFAULT_ENCRYPTION_SCHEME = 'pkcs1_oaep';

node-rsa官方文档:https://www.npmjs.com/package/node-rsa

Options

You can specify some options by second/third constructor argument, or over key.setOptions()method.

  • environment — working environment (default autodetect):
    • 'browser' — will run pure js implementation of RSA algorithms.
    • 'node' for nodejs >= 0.10.x or io.js >= 1.x — provide some native methods like sign/verify and encrypt/decrypt.
  • encryptionScheme — padding scheme for encrypt/decrypt. Can be 'pkcs1_oaep' or 'pkcs1'. Default 'pkcs1_oaep'.
  • signingScheme — scheme used for signing and verifying. Can be 'pkcs1' or 'pss' or 'scheme-hash' format string (eg 'pss-sha1'). Default 'pkcs1-sha256', or, if chosen pss: 'pss-sha1'.

Notice: This lib supporting next hash algorithms: 'md5''ripemd160''sha1''sha256''sha512' in browser and node environment and additional 'md4''sha''sha224''sha384' in node only.

 

所以要保持一致:

import NodeRSA from 'node-rsa';
const rsa_encrypt = (data) => {
    let key = new NodeRSA('-----BEGIN PUBLIC KEY-----\n' + 'MIGfMA0。。。。。。。AQAB\n' + '-----END PUBLIC KEY-----');
    // key.generateKeyPair(1024);
    key.setOptions({encryptionScheme: 'pkcs1'})
    let encryptKey = key.encrypt(data, 'base64')
    return encryptKey;
}

后台:

    public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
            throws Exception {
        byte[] keyBytes = Base64Utils.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

 参考:https://blog.csdn.net/mshootingstar/article/details/56496719

posted on 2018-04-12 10:34  一天不进步,就是退步  阅读(1852)  评论(0编辑  收藏  举报