java与nodejs的rsa加解密

自己用 支付宝开放平台助手生成 公私钥 rsa 那种
java版本


package my_demo;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

// spring-core-4.1.6.RELEASE 版本随意
import org.springframework.util.Base64Utils;

// fastjson2-2.0.8 版本随意
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

public class Psbc_fjapp2 {

	public static void main(String[] args) throws Exception {
		String rsa_publicKey = "xxxxxxxxxxxxxx";
		String rsa_privateKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";

		String paramStr = "JSON(JavaScript Object Notation, JS对象简谱)是一种轻量级的数据交换格式。它基于 ECMAScript(European Computer Manufacturers Association, 欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。";
		JSONObject paramJson = JSONObject.parseObject("{\"total\":0,\"list\":[{\"a\":\"1\",\"b\":\"2\",\"c\":\"xxxxxxxxxxxxxx\",\"d\":\"d\",\"e\":\"e\",\"cancelTime\":\"2022-11-08 15:55:55\"}]}");
		String plain = JSON.toJSONString(paramJson);
		plain = paramStr;// json与字符串
		System.out.println("plain = " + plain);
		String sign = encryptByPublicKey(plain, rsa_privateKey);
		System.out.println("sign = " + sign);
		System.out.println("plain = " + decryptByPrivateKey(sign, rsa_publicKey));
	}

	/**
	 * 私钥加密
	 *
	 * @param input, prik
	 * @return Bsae64加密好的字符串
	 */
	public static String encryptByPublicKey(String input, String key) throws Exception {
		return Base64Utils.encodeToString(encryptRSA(key, input.getBytes(), 117));
//		return Base64Utils.encodeToString(encryptRSA(key, input.getBytes(), 117)).replaceAll("[+]", "@");
	}

	/**
	 * 公钥解密
	 *
	 * @param input, pubk
	 * @return 解密好的字符串
	 */
	public static String decryptByPrivateKey(String input, String key) throws Exception {
		return new String(decryptRSA(key, Base64Utils.decodeFromString(input), 128));
//		return new String(decryptRSA(key, Base64Utils.decodeFromString(input.replaceAll("@", "+")), 128));
	}

	/**
	 * 私钥加密
	 */
	public static byte[] encryptRSA(String key, byte[] input, int length) throws Exception {
		byte[] encodedKey = Base64Utils.decodeFromString(key);
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		Key prik = keyFactory.generatePrivate(keySpec);
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, prik);
		int inputLen = input.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > length) {
				cache = cipher.doFinal(input, offSet, length);
			} else {
				cache = cipher.doFinal(input, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * length;
		}
		byte[] result = out.toByteArray();
		out.close();
		return result;
	}

	/**
	 * 公钥解密
	 */
	public static byte[] decryptRSA(String key, byte[] input, int length) throws Exception {
		byte[] encodedKey = Base64Utils.decodeFromString(key);
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		Key pubk = keyFactory.generatePublic(keySpec);
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, pubk);
		int inputLen = input.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > length) {
				cache = cipher.doFinal(input, offSet, length);
			} else {
				cache = cipher.doFinal(input, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * length;
		}
		byte[] result = out.toByteArray();
		out.close();
		return result;
	}

}


 node.js版本 

let os = require('os')
let crypto = require('crypto')
let rsa_public_key =
    '-----BEGIN PUBLIC KEY-----'
    + os.EOL + 'xxxxxxxxxxxxxx'
    + os.EOL + '-----END PUBLIC KEY-----'
let rsa_private_key =
    '-----BEGIN RSA PRIVATE KEY-----'
    + os.EOL + 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    + os.EOL + '-----END RSA PRIVATE KEY-----'
// 转PKCS1(非JAVA适用)私钥 公私钥由支付宝开放平台助手生成
let rsa_private_key_f =
    '-----BEGIN RSA PRIVATE KEY-----'
    + os.EOL + 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    + os.EOL + '-----END RSA PRIVATE KEY-----'


let paramsStr = 'JSON(JavaScript Object Notation, JS对象简谱)是一种轻量级的数据交换格式。它基于 ECMAScript(European Computer Manufacturers Association, 欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。'
let plain = '{"total":0,"list":[{"a":"1","b":"2","c":"xxxxxxxxxxxxxx","d":"d","e":"e","cancelTime":"2022-11-08 15:55:55"}]}'
// plain = paramsStr
console.log(plain);
sign = encryptRSABL(rsa_private_key_f, plain)
console.log(sign)
// sign = 'OMbKwbF5Jz7pqNOsO9yJND4Vwv8ERrsIn+4tG7QsvDAb1rmrBLWn+K7H8ZCHVPLPfXAo47MRRVAmCM+SxOy9gpuj1vxGGrSeNeFEBxkfrwWvVPJGCWjgVwWK74bxZMQGP3tBpyBf+lHrUuSyC3cZm0LdSP99d44gv1YSySjDjw96KdCSGanYCu22XKbd2GDltlIzhyLpZDTUCVMUx46kViYmnES/Jwt432LKhUcgrfwhFtMG94tZQQshs1sQ4uFR2Tz5EUKjkASn8H5zRUOjmn6JEVGcSFVxFR+bPZL7AcUo46YjbnllZxbzzqQZ7KeCVEP3CXS0H5cQee+97aEi3CHrPb4wprZWGdBlPE08oUYh8rrm7d2/RdIkMpG0X5Vt3PxvGsWgO5IWC2bKY3zV5vgS3UfsSzcsILV/G6/EkzHCz1dgmPZPBrsZBzgxvyi4mh1GZWnrhqPf7yTdTO4jBzMazcKk7P6kI/dB4bmgdWFTm2kAeW817U/0Ov+TeVIvD6YqvlON68zDOfHCAdwYDSJhVv/gK/w1obk+y0aoCqavmKl+KsAIcRfJEy0GucFrUPBjgOX33ROCqgLbQ4w7FLNn9e1sKrDJ50j2EONX6YO4AjJHNqKC/RaEnxHs8l6syC2T1dKa89OKgBR+sogjs21LNC0m3EzcVostmHpnMxcgbJt/Vny0405SsyuXPxZTATTKdTtTMxxbU48qf8Bmk4tIhnLD15W3t6sksVPQcBNw01BjwG18mCwYez8jXZ8H2zG8iFK9IFckac4iIK/BVVIsq8JjS/FCRQseRmiyGjI27OPg7jzJtGlRL7gFyig4pEWIhtG72f3VvME+LJXOXw=='
console.log(decryptRSABL(rsa_public_key, sign))

/**
 * 私钥加密
 * @param {*} prik 
 * @param {*} str 
 * @returns 
 */
function encryptRSABL (prik, str) {
    let encryptString = Buffer.from(str)
    let result = []
    let inputLen = encryptString.length
    let offSet = 0
    let length = 117
    let i = 0
    while (inputLen - offSet > 0) {
        let cache = ''
        if (inputLen - offSet > length) {
            cache = crypto.privateEncrypt(prik, encryptString.slice(offSet, (offSet + length)))
        } else {
            cache = crypto.privateEncrypt(prik, encryptString.slice(offSet, (offSet + (inputLen - offSet))))
        }
        cache.forEach(o => {
            result.push(o)
        })
        i++
        offSet = i * length
    }
    return new Buffer.from(result).toString('base64')
}

/**
 * 公钥解密
 * @param {*} pubk 
 * @param {*} str 
 * @returns 
 */
function decryptRSABL (pubk, str) {
    let encryptString = Buffer.from(str, 'base64')
    let result = []
    let inputLen = encryptString.length
    let offSet = 0
    let length = 128
    let i = 0
    while (inputLen - offSet > 0) {
        let cache = ''
        if (inputLen - offSet > length) {
            cache = crypto.publicDecrypt(pubk, encryptString.slice(offSet, (offSet + length)))
        } else {
            cache = crypto.publicDecrypt(pubk, encryptString.slice(offSet, (offSet + (inputLen - offSet))))
        }
        cache.forEach(o => {
            result.push(o)
        })
        i++
        offSet = i * length
    }
    return new Buffer.from(result).toString('utf-8')
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RSA(Rivest-Shamir-Adleman)是一种非对称加密算法,它使用公钥和私钥来加密和解密数据。在Node.js中,我们可以使用`crypto`模块来实现RSA加密和解密。 首先,我们需要生成RSA密钥对。可以使用以下代码生成一个新的RSA密钥对: ```javascript const crypto = require('crypto'); const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: 'pkcs1', format: 'pem' }, privateKeyEncoding: { type: 'pkcs1', format: 'pem' } }); console.log('公钥:'); console.log(publicKey); console.log('私钥:'); console.log(privateKey); ``` 生成的公钥和私钥将以PEM格式显示。 接下来,我们可以使用生成的公钥进行加密,私钥进行解密。以下是一个示例: ```javascript const crypto = require('crypto'); // 加密 function encrypt(data, publicKey) { const buffer = Buffer.from(data, 'utf8'); const encrypted = crypto.publicEncrypt(publicKey, buffer); return encrypted.toString('base64'); } // 解密 function decrypt(encryptedData, privateKey) { const buffer = Buffer.from(encryptedData, 'base64'); const decrypted = crypto.privateDecrypt(privateKey, buffer); return decrypted.toString('utf8'); } // 使用示例 const plaintext = 'Hello, RSA!'; const encrypted = encrypt(plaintext, publicKey); console.log('加密后的数据:', encrypted); const decrypted = decrypt(encrypted, privateKey); console.log('解密后的数据:', decrypted); ``` 请注意,这只是一个基本示例,实际使用时可能需要处理更复杂的数据和错误处理。 希望这可以帮助到你!如有任何问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值