RSA生成、加密、解密、签名。

首先,要会生成RSA密码对。

https://app.alipay.com/market/document.htm?name=saomazhifu#page-23    (事例中的密钥对好像有问题,最好用自己生成的。)

虽然说公钥和私钥都可以进行加密和解密,如果你是用公钥加密,就需要用私钥解密,如果你用的是私钥加密,就需要用公钥解密。

实际应用中,一般是自己保管私钥,别人都用公钥

import javax.crypto.Cipher;
import sun.security.rsa.RSAPublicKeyImpl;
import com.sun.org.apache.xml.internal.security.utils.Base64;


public class Main {

	public static String encrypt(String data, String publicKey){
		try{
			 byte[] keyBytes = Base64.decode(publicKey);
			 RSAPublicKeyImpl key = new RSAPublicKeyImpl(keyBytes);
			 Cipher cipher = Cipher.getInstance("RSA");
			 cipher.init(Cipher.ENCRYPT_MODE, key);   
			 byte[] encryptdata = cipher.doFinal(data.getBytes());   
			 return Base64.encode(encryptdata);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDO2DT8szWj8TpQfwiaflBhZ6cBRRFm/vhkYm6mSpk5kMSU3RNvjQx+I0xoTz+r4y9JUMsbHYy9Undwq94Z9lgYHlJQMVDb4kkiyaAn1Veu9fiQ3wPwgwQC84V0ymuPnfhBt8KcaNtS0CAEtHvFwnBwx2vlMoaG+uGdxrJ3Pho4PwIDAQAB";
		System.out.println(encrypt("abc", publicKey));
		//其实这里隐藏了一个bug,加密出来的东西为了好看,它自动加了\n这样的换行字符,
		//有些boss如果没有把回车或是空白字符过滤掉的话,就会出错。所以建议用 replayce一下。
		System.out.println(encrypt("abc", publicKey).replace("\n", ""));
		//细心的人就会发现,用同一个公钥,加密同一个字符串的加密密文是不同的,说明这种加密算法比较强大,它会在里面自动的padding一些随机信息。也就更安全。
		//当然了,用密钥解出来就是一样的了。
	}
}

我用的类基本上jdk都已集成,不用引用第三方包什么的,还是蛮方便的。

有时候会提示找不到RSAPublicKeyImpl类,这是jdk没设置好的原因,右击项目,选中properties,找到Java Build Path,然后在Libraries中

双击JRE System Library 然后选中Alternate JRE:定位到你安装jdk的地方就ok了。

import java.security.Key;
import java.security.KeyFactory;
import javax.crypto.Cipher;
import java.security.spec.PKCS8EncodedKeySpec;
import com.sun.org.apache.xml.internal.security.utils.Base64;


public class Main2 {
	
	public static String decrypt(String data, String privateKey){
		try{
			 byte[] keyBytes = Base64.decode(privateKey);
			 PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
			 KeyFactory keyFactory = KeyFactory.getInstance("RSA");   
			 Key privateKey2 = keyFactory.generatePrivate(pkcs8KeySpec);  
		
			 Cipher cipher = Cipher.getInstance("RSA");
			 cipher.init(Cipher.DECRYPT_MODE, privateKey2);   
			 byte[] encryptdata = cipher.doFinal(Base64.decode(data));   
			 return new String(encryptdata);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		String data = "EEzWXpVZ6FPJOzQASGDfZuCg7nLsyT2fwF85qwD5OXoCwtxCPkej+PkRDOispR0m327cEc7clm6Wqg4bXMxfehc7bkILtSsTIeNkAQMzoB7/xpMeGi6oQFQJJ1PvLqMTb4s+lhKvoBhER8XM/PXIGanL+trDeLcPG7NR72qu4TI=";
		String privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAM7YNPyzNaPxOlB/CJp+UGFnpwFFEWb++GRibqZKmTmQxJTdE2+NDH4jTGhPP6vjL0lQyxsdjL1Sd3Cr3hn2WBgeUlAxUNviSSLJoCfVV671+JDfA/CDBALzhXTKa4+d+EG3wpxo21LQIAS0e8XCcHDHa+Uyhob64Z3Gsnc+Gjg/AgMBAAECgYAb/exlykbXEd0naZmbdr6f/+v84wDw5E5vH1cEEBJeVPYVgzmPHhJzu4kqkJb4Rv1uOY3S9JPIRzG8wLWE4+6VzpF89/oR4O7rb8FV5Ma1I0oXNWyTy5wxqSt39bZZK/12vA58iomt7/+D3k1Z1V55XBNKI0s3SoXkD3pfECAQkQJBAPXV3uh4VOt3kX5GYxs0amF/DxWGFhLvsQWNKNXHK/47r4owVLCw/JDhelfMnWP/AmmANTgO1jnE/GW/RayPN3cCQQDXZZ++PKmhYqFaOPWmO5MItKo9iI5CPiMSZK3yF9nQjqBkquJnbL2XcP/nZqy//xs4lHs52A1qzS2e/xH58Ud5AkEAsUyYQY1XoaNQmYPmQl6hQsPCe0GDdhDM2TYfd174SZl+VunYir56yXr1I5F9CfuHH9PJji6VLoD1j+RNOdDorQJBAMxIEk9u4wYvL44M1VUZzSIFjiubtie3HLYWDC69VhOJIS84Lk8ef1UAk4MYCqBwxpVLpO7ALEFtZGYVzSu6HCkCQQDADWjpnSTo2l5yqYaA8nz4puKAbETC9F3RwMbwHlCY/HZ1QN077E2/3vAI4m0C1ssjN+reszqHUZihBwA5Eg/w";
		System.out.println(decrypt(data, privateKey));
	}
}

签名与验证

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import com.sun.org.apache.xml.internal.security.utils.Base64;


public class Main3 {
	
	public static String sign(String data, String privateKey){
		try{
	        byte[] keyBytes = Base64.decode(privateKey);
	        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
	        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
	        
	        Signature signature = Signature.getInstance("MD5withRSA");
	        signature.initSign(privateK);
	        signature.update(data.getBytes());
	        return Base64.encode(signature.sign());
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
    public static boolean verify(String data, String publicKey, String sign){
    	try{
            byte[] keyBytes = Base64.decode(publicKey);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicK = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initVerify(publicK);
            signature.update(data.getBytes());
            return signature.verify(Base64.decode(sign));
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return false;
    }
	
	public static void main(String[] args) {
		String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDO2DT8szWj8TpQfwiaflBhZ6cBRRFm/vhkYm6mSpk5kMSU3RNvjQx+I0xoTz+r4y9JUMsbHYy9Undwq94Z9lgYHlJQMVDb4kkiyaAn1Veu9fiQ3wPwgwQC84V0ymuPnfhBt8KcaNtS0CAEtHvFwnBwx2vlMoaG+uGdxrJ3Pho4PwIDAQAB";
		String privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAM7YNPyzNaPxOlB/CJp+UGFnpwFFEWb++GRibqZKmTmQxJTdE2+NDH4jTGhPP6vjL0lQyxsdjL1Sd3Cr3hn2WBgeUlAxUNviSSLJoCfVV671+JDfA/CDBALzhXTKa4+d+EG3wpxo21LQIAS0e8XCcHDHa+Uyhob64Z3Gsnc+Gjg/AgMBAAECgYAb/exlykbXEd0naZmbdr6f/+v84wDw5E5vH1cEEBJeVPYVgzmPHhJzu4kqkJb4Rv1uOY3S9JPIRzG8wLWE4+6VzpF89/oR4O7rb8FV5Ma1I0oXNWyTy5wxqSt39bZZK/12vA58iomt7/+D3k1Z1V55XBNKI0s3SoXkD3pfECAQkQJBAPXV3uh4VOt3kX5GYxs0amF/DxWGFhLvsQWNKNXHK/47r4owVLCw/JDhelfMnWP/AmmANTgO1jnE/GW/RayPN3cCQQDXZZ++PKmhYqFaOPWmO5MItKo9iI5CPiMSZK3yF9nQjqBkquJnbL2XcP/nZqy//xs4lHs52A1qzS2e/xH58Ud5AkEAsUyYQY1XoaNQmYPmQl6hQsPCe0GDdhDM2TYfd174SZl+VunYir56yXr1I5F9CfuHH9PJji6VLoD1j+RNOdDorQJBAMxIEk9u4wYvL44M1VUZzSIFjiubtie3HLYWDC69VhOJIS84Lk8ef1UAk4MYCqBwxpVLpO7ALEFtZGYVzSu6HCkCQQDADWjpnSTo2l5yqYaA8nz4puKAbETC9F3RwMbwHlCY/HZ1QN077E2/3vAI4m0C1ssjN+reszqHUZihBwA5Eg/w";
		String sign = sign("abc", privateKey);
		System.out.println(verify("abc", publicKey , sign));
	}
}

最近补充一下js版的RSA加解密和签名:加密解最好用的是jsencrypt.js ,签名最好用的是jsrsasign.js 。曾经我也用痛苦地用过RSA.js ,但是它很难用,首先是它的参数对我是一种考验,一开始都不知道那些参数怎么填,才来才慢慢明白,还有就是RSA.js加密是没有padding的,它每次加密出来的东西只要公钥和数据一样,加密出来就是一样的密文,这个还必须得用  bcprov-jdk15-143.jar

			 Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());  
			 final Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC");  

这个来解,但是一般的boss系统都不这么干,所以RSA.js并不好用,果断放弃吧。

代码如下:

function encrypt(data){  //加密
    var _encrypt = new JSEncrypt();
    _encrypt.setPublicKey(boss_public_key);
    var encrypted = _encrypt.encrypt(data);
    return encrypted;
}

function decrypt(data){
    var _decrypt = new JSEncrypt();
    _decrypt.setPrivateKey(Merchant_private_key);
    var uncrypted = _decrypt.decrypt(data);
    return uncrypted;
}

function sign(data){  //签名
  var rsa = KEYUTIL.getRSAKeyFromPlainPKCS8PEM("-----BEGIN PRIVATE KEY-----" + Merchant_private_key + "-----END PRIVATE KEY-----");
  var result = rsa.signString(data, "md5");
  return base64_encode(code_conversion(result));
}

 这里是用到的几个js  【JS-RSA加密签名-纯净版.zip】

链接:https://pan.baidu.com/s/14eGYh0ZTa_kTVJ3Fkqq-vA
提取码:8v3e

 

 

 

posted on 2015-09-27 20:49  angelshelter  阅读(4454)  评论(1编辑  收藏  举报

导航