用nodejs接第三方java服务加密问题
发布于 8 年前 作者 weizhigang 3482 次浏览 来自 问答

我这边现在那个公钥(key)是一个纯的字符串,然后加密的java代码如下: /**

  • 用公钥加密

  • @param data 加密数据

  • @param key 公钥

  • @return 加密后的字节数组

  • @throws Exception 异常 */ public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception { byte[] encryptedData = null;

    //对公钥解密 byte[] keyBytes = decryptBASE64(key); //取公钥 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

    //对数据解密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    // 加密时超过maxEncryptBlockSize字节就报错。为此采用分段加密的办法来加密 int maxEncryptBlockSize = getMaxEncryptBlockSize(keyFactory, publicKey);

    ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { int dataLength = data.length; for (int i = 0; i < data.length; i += maxEncryptBlockSize) { int encryptLength = dataLength - i < maxEncryptBlockSize ? dataLength - i : maxEncryptBlockSize; byte[] doFinal = cipher.doFinal(data, i, encryptLength); bout.write(doFinal); } encryptedData = bout.toByteArray(); } finally { if (bout != null) { bout.close(); } } return encryptedData; } 我想要用node实现同样的加密方式,要怎么做呢,对加密这个不太熟悉,尝试了很多种写法,都不行,请大家指导一下

1 回复

建议使用aes加密方式加密

var crypto = require('crypto');
var Buffer = require('buffer').Buffer;
var key = "3755c118e8639eb0"; /这个key长度是固定的
var key  = new Buffer(key,'utf-8');
var Aes = {
  //加密
  encypt: function(data){
    var iv = '';
    var clearEncoding = 'utf8';
    var cipherEncoding = 'base64';
    var cipherChunks = [];
    var cipher = crypto.createCipheriv('aes-128-ecb', key, iv);
    cipher.setAutoPadding(true);

    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(cipherEncoding));

    return cipherChunks.join('');
  },
  //解密
  decrypt: function(data){
    var iv = "";
    var clearEncoding = 'utf8';
    var cipherEncoding = 'base64';
    var cipherChunks = [];
    var decipher = crypto.createDecipheriv('aes-128-ecb', key, iv);
    decipher.setAutoPadding(true);

    cipherChunks.push(decipher.update(data, cipherEncoding, clearEncoding));
    cipherChunks.push(decipher.final(clearEncoding));

    return cipherChunks.join('');
  },
  base64_encode: function(data){
    var b = new Buffer(data);
    var s = b.toString('base64');
    return s;
  },
  base64_decode: function(data){
    var b = new Buffer(data,'base64');
    var s = b.toString();
    return s;
  }
};
module.exports = Aes;
回到顶部