用NODE RSA JS 加密解密正常,用JAVA RSAUtils工具類加密解密正常。可是用node加密玩的java解密不了。緣由:node默認的是java
DEFAULT_ENCRYPTION_SCHEME = 'pkcs1_oaep' 而java中默認的是pkcs1。node
node-rsa源碼:https://github.com/rzcoder/node-rsa/blob/ea5c17d9351c857c0594d7921c596ff5636882f1/src/NodeRSA.jsgit
var DEFAULT_ENCRYPTION_SCHEME = 'pkcs1_oaep';github
node-rsa官方文檔:https://www.npmjs.com/package/node-rsanpm
You can specify some options by second/third constructor argument, or over key.setOptions()
method.ide
'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.'pkcs1_oaep'
or 'pkcs1'
. Default 'pkcs1_oaep'
.'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; }
後臺:spa
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.net