android作为前端,使用node生成的rsa公钥进行加密密码,然后通过接口到node后端中rsa解密密码,但是明明公钥和私钥都是正确的,但node就是无法解密android加密的密文,代码如下:
1、node生成公钥和私钥的方法:
const { publicEncrypt, privateDecrypt } = require('crypto')
const fs = require('fs')
const { generateKeyPairSync } = require('crypto')
// 配置
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
modulusLength: 1024,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
})
// 生成密钥
const pub = publicKey.toString()
const pri = privateKey.toString()
console.log('---------------公钥--------------\n' + pub)
console.log('---------------私钥--------------\n' + pri)
// 生成pem密钥文件
fs.writeFileSync('./pem/RsaPri.pem', privateKey)
fs.writeFileSync('./pem/RsaPub.pem', publicKey)
2、node解密的方法:
// 解密
function decryption (data) {
try {
const priKey = fs.readFileSync('./pem/RsaPri.pem', 'utf8')
const dataDecry = privateDecrypt(priKey, Buffer.from(data.toString('base64'), 'base64'))
// 返回结果
return JSON.stringify({
code: 200,
data: dataDecry
})
} catch (e) {
// 返回错误
return JSON.stringify({
code: 500,
data: e
})
}
}
module.exports = {
decryption
}
3、android加密的方法
package com.example.test4.utils;
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
public class RsaUtil {
private static String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUdql3ySffmXK62MdQcZnLjIL5n2vcavNEt/v1U//caLzyy+olyhvdKUk/sBYNApKzEIOCy5mbm3xmGEB0HplZWCAWs/lxB+827MeSWCjEwg5/kxtMFGkqiw64gp5Bx7IqwdA3qhsFlmyxIGMm/66Ea3GCjL7PTPlDoDU5ZL803wIDAQAB";
/**
* 使用公钥加密
* @param content 需要加密的密文(String类型)
* @return base64数据
* @throws Exception
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public static String encryptByPublicKey(String content) throws Exception {
byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyStr.getBytes("utf-8"));
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
byte[] plainTextBytes = content.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(plainTextBytes);
String encryptedBase64Str = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println(encryptedBase64Str);
return encryptedBase64Str;
}
}