RSA签名加密解密

目录

  • Java 接口
    • RSAUtils.java
    • 示例中的依赖
    • 生成密钥对示例
    • 签名示例
    • 验证签名示例
    • 加密和解密示例
  • Javascript 接口
    • 引入依赖
    • 生成密钥对示例
    • 签名示例
    • 验证签名示例
    • 加密和解密示例
  • 说在最后

Java 接口

  1. 支持的密钥长度包括4种 RSA512、RSA1024、RSA2048、RSA4096
  2. 支持的签名算法包括7种 MD2withRSA、MD5withRSA、SHA1withRSA、SHA224withRSA、SHA256withRSA、SHA384withRSA、SHA512withRSA
  3. 对明文及密文长度没有限制
  4. 其中,java6 不支持签名算法 SHA224withRSA、SHA256withRSA、SHA384withRSA、SHA512withRSA
  5. 其中 java.util.Base64 为 java8 及以上版本支持的 API,低于 java8 的版本需要替换为其他工具类库。

RSAUtils.java

package com.sm;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

/**
 * 
 * @Description: RSA签名,加解密处理核心文件
 */
public final class RSAUtils {

    /**
     * 加密算法RSA
     */
	private static final String KEY_ALGORITHM = "RSA";

    /**
     * 获取公钥的key
     */
	public static final String PUBLIC_KEY = "RSAPublicKey";

    /**
     * 获取私钥的key
     */
	public static final String PRIVATE_KEY = "RSAPrivateKey";
	
	public static RSAEncrypt getRSA512() {
		return RSAEncrypt.RSA512;
	}
	
	public static RSAEncrypt getRSA1024() {
		return RSAEncrypt.RSA1024;
	}
	
	public static RSAEncrypt getRSA2048() {
		return RSAEncrypt.RSA2048;
	}
	
	public static RSAEncrypt getRSA4096() {
		return RSAEncrypt.RSA4096;
	}

    /**
     * 

* 获取私钥 *

* * @param keyMap 密钥对 * @return * @throws Exception */
public static String getPrivateKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get(PRIVATE_KEY); return Base64.getEncoder().encodeToString(key.getEncoded()); } /** *

* 获取公钥 *

* * @param keyMap 密钥对 * @return * @throws Exception */
public static String getPublicKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get(PUBLIC_KEY); return Base64.getEncoder().encodeToString(key.getEncoded()); } /** * @param content * @param charset * @return * @throws SignatureException * @throws UnsupportedEncodingException */ private static byte[] getContentBytes(String content, String charset) { if (charset == null || "".equals(charset)) { return content.getBytes(); } try { return content.getBytes(charset); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UnsupportedEncoding:" + charset, e); } } public static enum RSAEncryptEnum { RSA512(512, 53, 64), RSA1024(1024, 117, 128), RSA2048(2048, 245, 256), RSA4096(4096, 501, 512) ; /** * RSA key的长度 */ private final int keysize; /** * RSA最大加密明文大小 */ private final int maxEncryptBlock; /** * RSA最大解密密文大小 */ private final int maxDecryptBlock; private RSAEncryptEnum(int keysize, int maxEncryptBlock, int maxDecryptBlock) { this.keysize = keysize; this.maxEncryptBlock = maxEncryptBlock; this.maxDecryptBlock = maxDecryptBlock; } public int getKeysize() { return keysize; } public int getMaxEncryptBlock() { return maxEncryptBlock; } public int getMaxDecryptBlock() { return maxDecryptBlock; } } public static final class RSAEncrypt { private final RSAEncryptEnum rsaEncryptEnum; private RSAEncrypt(RSAEncryptEnum rsaEncryptEnum) { this.rsaEncryptEnum = rsaEncryptEnum; } static final RSAEncrypt RSA512 = new RSAEncrypt(RSAEncryptEnum.RSA512); static final RSAEncrypt RSA1024 = new RSAEncrypt(RSAEncryptEnum.RSA1024); static final RSAEncrypt RSA2048 = new RSAEncrypt(RSAEncryptEnum.RSA2048); static final RSAEncrypt RSA4096 = new RSAEncrypt(RSAEncryptEnum.RSA4096); /** *

* 生成密钥对(公钥和私钥) *

* * @return * @throws Exception */
public Map<String, Object> genKeyPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(this.rsaEncryptEnum.getKeysize()); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map<String, Object> keyMap = new HashMap<>(2, 1.0f); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; } /** *

* 私钥解密 *

* * @param encryptedData 已加密数据 * @param privateKey 私钥(BASE64编码) * @return * @throws Exception */
public byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception { byte[] keyBytes = Base64.getDecoder().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; int maxDecryptBlock = this.rsaEncryptEnum.getMaxDecryptBlock(); // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > maxDecryptBlock) { cache = cipher.doFinal(encryptedData, offSet, maxDecryptBlock); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * maxDecryptBlock; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } /** *

* 公钥解密 *

* * @param encryptedData 已加密数据 * @param publicKey 公钥(BASE64编码) * @return * @throws Exception */
public byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception { byte[] keyBytes = Base64.getDecoder().decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; int maxDecryptBlock = this.rsaEncryptEnum.getMaxDecryptBlock(); // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > maxDecryptBlock) { cache = cipher.doFinal(encryptedData, offSet, maxDecryptBlock); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * maxDecryptBlock; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } /** *

* 公钥加密 *

* * @param data 源数据 * @param publicKey 公钥(BASE64编码) * @return * @throws Exception */
public byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception { byte[] keyBytes = Base64.getDecoder().decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); // 对数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; int maxEncryptBlock = this.rsaEncryptEnum.getMaxEncryptBlock(); // 对数据分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > maxEncryptBlock) { cache = cipher.doFinal(data, offSet, maxEncryptBlock); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * maxEncryptBlock; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; } /** *

* 私钥加密 *

* * @param data 源数据 * @param privateKey 私钥(BASE64编码) * @return * @throws Exception */
public byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception { byte[] keyBytes = Base64.getDecoder().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.ENCRYPT_MODE, privateK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; int maxEncryptBlock = this.rsaEncryptEnum.getMaxEncryptBlock(); // 对数据分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > maxEncryptBlock) { cache = cipher.doFinal(data, offSet, maxEncryptBlock); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * maxEncryptBlock; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; } } public static RSASignature getMD2withRSA() { return RSASignature.MD2_WITH_RSA; } public static RSASignature getMD5withRSA() { return RSASignature.MD5_WITH_RSA; } public static RSASignature getSHA1withRSA() { return RSASignature.SHA1_WITH_RSA; } public static RSASignature getSHA224withRSA() { return RSASignature.SHA224_WITH_RSA; } public static RSASignature getSHA256withRSA() { return RSASignature.SHA256_WITH_RSA; } public static RSASignature getSHA384withRSA() { return RSASignature.SHA384_WITH_RSA; } public static RSASignature getSHA512withRSA() { return RSASignature.SHA512_WITH_RSA; } public static final class RSASignature { /** * 签名算法 */ private final String signatureAlgorithm; private RSASignature(String signatureAlgorithm) { this.signatureAlgorithm = signatureAlgorithm; } static final RSASignature MD2_WITH_RSA = new RSASignature("MD2withRSA"); static final RSASignature MD5_WITH_RSA = new RSASignature("MD5withRSA"); static final RSASignature SHA1_WITH_RSA = new RSASignature("SHA1withRSA"); static final RSASignature SHA224_WITH_RSA = new RSASignature("SHA224withRSA"); static final RSASignature SHA256_WITH_RSA = new RSASignature("SHA256withRSA"); static final RSASignature SHA384_WITH_RSA = new RSASignature("SHA384withRSA"); static final RSASignature SHA512_WITH_RSA = new RSASignature("SHA512withRSA"); /** * 签名字符串 * * @param text * 需要签名的字符串 * @param privateKey 私钥(BASE64编码) * * @param charset * 编码格式 * @return 签名结果(BASE64编码) */ public String sign(String text, String privateKey, String charset) throws Exception { byte[] keyBytes = Base64.getDecoder().decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec); Signature signature = Signature.getInstance(this.signatureAlgorithm); signature.initSign(privateK); signature.update(getContentBytes(text, charset)); byte[] result = signature.sign(); return Base64.getEncoder().encodeToString(result); } /** * 签名字符串 * * @param text * 需要签名的字符串 * @param sign * 客户签名结果 * @param publicKey * 公钥(BASE64编码) * @param charset * 编码格式 * @return 验签结果 */ public boolean verify(String text, String sign, String publicKey, String charset) throws Exception { byte[] keyBytes = Base64.getDecoder().decode(publicKey); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PublicKey publicK = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance(this.signatureAlgorithm); signature.initVerify(publicK); signature.update(getContentBytes(text, charset)); return signature.verify(Base64.getDecoder().decode(sign)); } } }

示例中的依赖

import java.util.Base64;
import java.util.Map;

import com.sm.RSAUtils.RSAEncrypt;
import com.sm.RSAUtils.RSASignature;

生成密钥对示例

public static void genKeyPair () throws Exception {
	RSAEncrypt rsaEncrypt = RSAUtils.getRSA1024();
	//生成密钥对
	Map<String, Object> map = rsaEncrypt.genKeyPair();
    String pubKey = RSAUtils.getPublicKey(map);
    String priKey = RSAUtils.getPrivateKey(map);
    System.out.println("pubKey-->"+pubKey);
    System.out.println("priKey-->"+priKey);
}

签名示例

public static void sign() throws Exception {
	String pubKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQE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ef9ncy2oXbZvKlHYu0AykheCLJ7P0/QKBgQDLlxYcPMdSq19QJD9PJJTmD9IO75uNxX2ITsBuiSk81LqiYFm2x9EsKQF7lqZ1xPcoQu/AW1CrO3J9HSSsW4D27yO8dMgL38jT5O5lDiF+Fs+f3c5LDq8vCvXEF5MARo5rgyX7CMJjo1tFoDEX1zEfoBoMmoFfxFuOTlx8/zRHDwKBgQDHpR0nNGnDmW1GtU2uBnrxZo4cTIA3kZPEoQJIrvVkkQ/k1fuZMtzYTsSSEG4b1ZI2tdqm8wItQ50gXyQOCZ6B7kSkU/xelPCEfK7zRObPLS1IOyiayNw7aAwmZI2GERAm9TBlewn2PCJGT9F1vDGTb8M70tkgl8PUXm+XnBSEnwKBgCbKb80Li5Ll0jBL58AloTVAmG5+Gu5lTajWEHY/LhtIERN1NkLMSb+XRJAOwUK5N7p1HodRHsqxdfv+vIkWmjjykaWLvr38cqBlA0M/8QO8Ru0X7wGAF8Ln3LHzJ/AqgWJcx7TQE3G2o2JdxlzbhKGY+L2kBrh/ik5QAfFTEtvjAoGATBWQ1rAS3ohKLPhLclbl47nBzucYthS0y+rQhAKpYnomJH+oMuo/X/Ak2cWJMPJjlpYXjihuW/G4n+2iP/dKgRnc7wNS2njIcLVTt0I69BmzeCOThemmhL1SZA9OIBnAnhgzKXmKglzIcyNYIBZojle5f8MLHHC6IOUcghrpduECgYEAlZgVK0trRmi+Dy2lmkhmBXckq1Xle1cJac3zZYeg9+Cd424WDyqhl2SFNDrvvTGCW9PtONMQBXUxnbImWDb8lw4ClY2tR0XZe0YycGMcV983PsTjJqET+8oGPVLGmnlCLJ4X9raQYKDWpDyGOFfX91QsFOnnSprTrylhjnhC3ko=";
    String text = "id_card=1121321121321321中文2123123&partner_id=TLHS2020001";
    final String charset = "utf-8";
    RSASignature rsaSignature = RSAUtils.getSHA256withRSA();
    String sign = rsaSignature.sign(text, priKey, charset);
   	System.out.println("sign-->"+sign);
}

验证签名示例

public static void verify() throws Exception {
	String pubKey = "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bOoG+wD4/Miptq5+3tmt8Cqktzv8v2Z6kGNejkJl9Mos5lgRI7kdFf9GMiQuy3lvRybOT8S0HFGr2vFrMrUrkYL9W+PzlILS7sQuerLqVm0xKIuj5/thm8L5kcVQFozudxydbYxsBp8pvSqsVRCZ4mPO/S6I1NTeS7ffLGixrmyWsXEVX9/D11WGgN3UYrNlEVna9Y4VOk9o9bB8un/FaJyyMuIHpT0YYLjZxAO2GpxuD9dsJbEL990Lr5k+P66mCeC5mNX/s2jBI49w==";
	final String charset = "utf-8";
    RSASignature rsaSignature = RSAUtils.getSHA256withRSA();
    if(rsaSignature.verify(text, sign, pubKey, charset)) {
		System.out.println("验签成功");
	}else {
		System.out.println("验签失败");
	}
}

加密和解密示例

public static void encryptAndDecrypt() throws Exception {
	RSAEncrypt rsaEncrypt = RSAUtils.getRSA2048();
	String pubKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnsXBwH6me+8+P3BdtnZnsze3nQXCmt8+9+jcLmxK+Q2Oe6qQ3hfElokUpWBLogEgmoj5/dF+xWaQYAzvd1LR7zuKDESQmRnOb9FQD6Pr2RsDOTFBCa5DA0EQ17TmqqaJT9+xrcIVxU/Y2+2tCkRJBJuo7hRoFoM2l37ju9InTGA9P/vQXi9jjSiZ5o6Zbu6svHG1B/1GsnC+wtszYzsMZs7Lo2N5lK2e+q2bBnpvb7PpWOWTGVpeFoivbH+fCIRB6wiFAiQxeZ++KNs2Coi7zoj6cOX49aG4rv4/gnwftOKq4Fb9I+cQW5v7d3Nmp6Jh647DshTEwpLlyxt1J0feUQIDAQAB";
    String priKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCexcHAfqZ77z4/cF22dmezN7edBcKa3z736NwubEr5DY57qpDeF8SWiRSlYEuiASCaiPn90X7FZpBgDO93UtHvO4oMRJCZGc5v0VAPo+vZGwM5MUEJrkMDQRDXtOaqpolP37GtwhXFT9jb7a0KREkEm6juFGg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TEtvjAoGATBWQ1rAS3ohKLPhLclbl47nBzucYthS0y+rQhAKpYnomJH+oMuo/X/Ak2cWJMPJjlpYXjihuW/G4n+2iP/dKgRnc7wNS2njIcLVTt0I69BmzeCOThemmhL1SZA9OIBnAnhgzKXmKglzIcyNYIBZojle5f8MLHHC6IOUcghrpduECgYEAlZgVK0trRmi+Dy2lmkhmBXckq1Xle1cJac3zZYeg9+Cd424WDyqhl2SFNDrvvTGCW9PtONMQBXUxnbImWDb8lw4ClY2tR0XZe0YycGMcV983PsTjJqET+8oGPVLGmnlCLJ4X9raQYKDWpDyGOFfX91QsFOnnSprTrylhjnhC3ko=";
    String text = "id_card=1121321121321321中文2123123&partner_id=TLHS2020001";
	// 加密与解密
	byte[] data = text.getBytes();
	System.out.println("加密前--->" + new String(data));
	
	byte[] encryptedDataPri = rsaEncrypt.encryptByPrivateKey(data, priKey);// 密文
	System.out.println("私钥加密后--->" + Base64.getEncoder().encodeToString(encryptedDataPri));
	byte[] decryptedDataPub = rsaEncrypt.decryptByPublicKey(encryptedDataPri, pubKey);
	System.out.println("公钥解密后--->"+new String(decryptedDataPub));

	byte[] encryptedDataPub = rsaEncrypt.encryptByPublicKey(data, pubKey);// 密文
	System.out.println("公钥加密后--->" + Base64.getEncoder().encodeToString(encryptedDataPub));
	byte[] decryptedDataPri = rsaEncrypt.decryptByPrivateKey(encryptedDataPub, priKey);
	System.out.println("私钥解密后--->"+new String(decryptedDataPri));
}

Javascript 接口

  1. jsencrypt 支持的密钥长度包括4种 RSA512、RSA1024、RSA2048、RSA4096
  2. crypto-js 支持的签名算法包括 MD5、SHA1、SHA224、SHA256、SHA384、SHA512 等多种算法
  3. 对明文及密文长度有限制,超长会报错,可以查看 https://github.com/travist/jsencrypt/issues/110 尝试解决
  4. 经测试,jsencrypt 不支持使用私钥加密,即由私钥加密产生的密文不能被解密。

引入依赖

github链接
https://github.com/travist/jsencrypt
https://github.com/brix/crypto-js/tree/4.1.1

<script type="text/javascript" src="jsencrypt.min.js"></script>
<script type="text/javascript" src="crypto-js.js"></script>

生成密钥对示例

(function () {
	//生成密钥对
	var crypt = new JSEncrypt({default_key_size: 2048});
	crypt.getKey();
	console.log('PrivateKey', crypt.getPrivateKey());
	console.log('PublicKey', crypt.getPublicKey());
})();

签名示例

(function () {
	//RSA2048签名
	var pubKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnsXBwH6me+8+P3BdtnZnsze3nQXCmt8+9+jcLmxK+Q2Oe6qQ3hfElokUpWBLogEgmoj5/dF+xWaQYAzvd1LR7zuKDESQmRnOb9FQD6Pr2RsDOTFBCa5DA0EQ17TmqqaJT9+xrcIVxU/Y2+2tCkRJBJuo7hRoFoM2l37ju9InTGA9P/vQXi9jjSiZ5o6Zbu6svHG1B/1GsnC+wtszYzsMZs7Lo2N5lK2e+q2bBnpvb7PpWOWTGVpeFoivbH+fCIRB6wiFAiQxeZ++KNs2Coi7zoj6cOX49aG4rv4/gnwftOKq4Fb9I+cQW5v7d3Nmp6Jh647DshTEwpLlyxt1J0feUQIDAQAB';
	var priKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCexcHAfqZ77z4/cF22dmezN7edBcKa3z736NwubEr5DY57qpDeF8SWiRSlYEuiASCaiPn90X7FZpBgDO93UtHvO4oMRJCZGc5v0VAPo+vZGwM5MUEJrkMDQRDXtOaqpolP37GtwhXFT9jb7a0KREkEm6juFGgWgzaXfuO70idMYD0/+9BeL2ONKJnmjplu7qy8cbUH/UaycL7C2zNjOwxmzsujY3mUrZ76rZsGem9vs+lY5ZMZWl4WiK9sf58IhEHrCIUCJDF5n74o2zYKiLvOiPpw5fj1obiu/j+CfB+04qrgVv0j5xBbm/t3c2anomHrjsOyFMTCkuXLG3UnR95RAgMBAAECggEAJP8BqcAZPRG/WHrvaz/l5A3cnBsmgH36pzu8apjTU3tEMy7IeOfi6AzjIbHxjbtjhH7cebdiKc8/XxJEjnJe9rbR8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PsTjJqET+8oGPVLGmnlCLJ4X9raQYKDWpDyGOFfX91QsFOnnSprTrylhjnhC3ko=';
	
	//SHA256withRSA
	var plainText = 'id_card=1121321121321321中文2123123&partner_id=TLHS2020001';
	//**加签**
	var sign = new JSEncrypt();
	//设置私钥
       sign.setPrivateKey(priKey);
       //用私钥给明文加签,例子中使用SHA256算法,具体情况具体调整
	var signature = sign.sign(plainText, CryptoJS.SHA256, "sha256");
	console.log('sha256签名', signature);
})();

验证签名示例

(function () {
	//RSA2048验签
	var pubKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnsXBwH6me+8+P3BdtnZnsze3nQXCmt8+9+jcLmxK+Q2Oe6qQ3hfElokUpWBLogEgmoj5/dF+xWaQYAzvd1LR7zuKDESQmRnOb9FQD6Pr2RsDOTFBCa5DA0EQ17TmqqaJT9+xrcIVxU/Y2+2tCkRJBJuo7hRoFoM2l37ju9InTGA9P/vQXi9jjSiZ5o6Zbu6svHG1B/1GsnC+wtszYzsMZs7Lo2N5lK2e+q2bBnpvb7PpWOWTGVpeFoivbH+fCIRB6wiFAiQxeZ++KNs2Coi7zoj6cOX49aG4rv4/gnwftOKq4Fb9I+cQW5v7d3Nmp6Jh647DshTEwpLlyxt1J0feUQIDAQAB';
	var priKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCexcHAfqZ77z4/cF22dmezN7edBcKa3z736NwubEr5DY57qpDeF8SWiRSlYEuiASCaiPn90X7FZpBgDO93UtHvO4oMRJCZGc5v0VAPo+vZGwM5MUEJrkMDQRDXtOaqpolP37GtwhXFT9jb7a0KREkEm6juFGgWgzaXfuO70idMYD0/+9BeL2ONKJnmjplu7qy8cbUH/UaycL7C2zNjOwxmzsujY3mUrZ76rZsGem9vs+lY5ZMZWl4WiK9sf58IhEHrCIUCJDF5n74o2zYKiLvOiPpw5fj1obiu/j+CfB+04qrgVv0j5xBbm/t3c2anomHrjsOyFMTCkuX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ECgYEAlZgVK0trRmi+Dy2lmkhmBXckq1Xle1cJac3zZYeg9+Cd424WDyqhl2SFNDrvvTGCW9PtONMQBXUxnbImWDb8lw4ClY2tR0XZe0YycGMcV983PsTjJqET+8oGPVLGmnlCLJ4X9raQYKDWpDyGOFfX91QsFOnnSprTrylhjnhC3ko=';
	
	//SHA256withRSA
	var plainText = 'id_card=1121321121321321中文2123123&partner_id=TLHS2020001';
	
	var signature = 'GAjmZiUH0hnMOZyOiViCvzZDHoMVXdmwjyyLiAOgBYFhM0/d8GPiPMKZsPIAmIKiDRwX37bOoG+wD4/Miptq5+3tmt8Cqktzv8v2Z6kGNejkJl9Mos5lgRI7kdFf9GMiQuy3lvRybOT8S0HFGr2vFrMrUrkYL9W+PzlILS7sQuerLqVm0xKIuj5/thm8L5kcVQFozudxydbYxsBp8pvSqsVRCZ4mPO/S6I1NTeS7ffLGixrmyWsXEVX9/D11WGgN3UYrNlEVna9Y4VOk9o9bB8un/FaJyyMuIHpT0YYLjZxAO2GpxuD9dsJbEL990Lr5k+P66mCeC5mNX/s2jBI49w==';
	//**验签**
	var verify = new JSEncrypt({
		default_key_size: 2048
	});
	//设置公钥
       verify.setPublicKey(pubKey);
       //验证方法有三个参数明文,用私钥加签后的字符串,加签的算法(跟上文保持一致哈~)
	var verified = verify.verify(plainText, signature, CryptoJS.SHA256);
	
	// 判断验签是否成功
	if (verified) {
	  console.log('验签成功啦~');
	}
	else {
	  console.log('验签失败啦....');
	}
})();

加密和解密示例

(function () {
	//RSA2048加密解密
	var pubKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnsXBwH6me+8+P3BdtnZnsze3nQXCmt8+9+jcLmxK+Q2Oe6qQ3hfElokUpWBLogEgmoj5/dF+xWaQYAzvd1LR7zuKDESQmRnOb9FQD6Pr2RsDOTFBCa5DA0EQ17TmqqaJT9+xrcIVxU/Y2+2tCkRJBJuo7hRoFoM2l37ju9InTGA9P/vQXi9jjSiZ5o6Z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fxFuOTlx8/zRHDwKBgQDHpR0nNGnDmW1GtU2uBnrxZo4cTIA3kZPEoQJIrvVkkQ/k1fuZMtzYTsSSEG4b1ZI2tdqm8wItQ50gXyQOCZ6B7kSkU/xelPCEfK7zRObPLS1IOyiayNw7aAwmZI2GERAm9TBlewn2PCJGT9F1vDGTb8M70tkgl8PUXm+XnBSEnwKBgCbKb80Li5Ll0jBL58AloTVAmG5+Gu5lTajWEHY/LhtIERN1NkLMSb+XRJAOwUK5N7p1HodRHsqxdfv+vIkWmjjykaWLvr38cqBlA0M/8QO8Ru0X7wGAF8Ln3LHzJ/AqgWJcx7TQE3G2o2JdxlzbhKGY+L2kBrh/ik5QAfFTEtvjAoGATBWQ1rAS3ohKLPhLclbl47nBzucYthS0y+rQhAKpYnomJH+oMuo/X/Ak2cWJMPJjlpYXjihuW/G4n+2iP/dKgRnc7wNS2njIcLVTt0I69BmzeCOThemmhL1SZA9OIBnAnhgzKXmKglzIcyNYIBZojle5f8MLHHC6IOUcghrpduECgYEAlZgVK0trRmi+Dy2lmkhmBXckq1Xle1cJac3zZYeg9+Cd424WDyqhl2SFNDrvvTGCW9PtONMQBXUxnbImWDb8lw4ClY2tR0XZe0YycGMcV983PsTjJqET+8oGPVLGmnlCLJ4X9raQYKDWpDyGOFfX91QsFOnnSprTrylhjnhC3ko=';
	
	var plainText = 'id_card=1121321121321321中文2123123&partner_id=TLHS2020001';
	console.log('加密前', plainText);
    
    var encryptPub = new JSEncrypt({
		default_key_size: 2048
	});
	encryptPub.setPublicKey(pubKey);
	var encryptedPub = encryptPub.encrypt(plainText);
	console.log('公钥加密后', encryptedPub);
	
    var decryptPri = new JSEncrypt({
		default_key_size: 2048
	});
    decryptPri.setPrivateKey(priKey);
    var uncryptedPri = decryptPri.decrypt(encryptedPub);
    console.log('私钥解密后', uncryptedPri);
})();

说在最后

Java 和 Javascript 支持的生成密钥对签名加密解密功能可以通用。

你可能感兴趣的:(java,前端,RSA,签名,加密,解密,非对称)