java中RSA加解密的实现

关于加密数据长度和解密数据长度大家可以看一下我前一篇文章内的介绍:

关于RSA算法密钥长度/密文长度/明文长度的介绍

  1. public static void main(String[] args) throws Exception { 
  2.         // TODO Auto-generated method stub 
  3.         HashMap<String, Object> map = RSAUtils.getKeys(); 
  4.         //生成公钥和私钥 
  5.         RSAPublicKey publicKey = (RSAPublicKey) map.get("public"); 
  6.         RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private"); 
  7.          
  8.         //模 
  9.         String modulus = publicKey.getModulus().toString(); 
  10.         //公钥指数 
  11.         String public_exponent = publicKey.getPublicExponent().toString(); 
  12.         //私钥指数 
  13.         String private_exponent = privateKey.getPrivateExponent().toString(); 
  14.         //明文 
  15.         String ming = "123456789"
  16.         //使用模和指数生成公钥和私钥 
  17. RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus, public_exponent);
  18.         RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus, private_exponent); 
  19.         //加密后的密文 
  20.         String mi = RSAUtils.encryptByPublicKey(ming, pubKey); 
  21.         System.err.println(mi); 
  22.         //解密后的明文 
  23.         ming = RSAUtils.decryptByPrivateKey(mi, priKey); 
  24.         System.err.println(ming); 
  25.     } 
public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		HashMap<String, Object> map = RSAUtils.getKeys();
		//生成公钥和私钥
		RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
		RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");
		
		//模
		String modulus = publicKey.getModulus().toString();
		//公钥指数
		String public_exponent = publicKey.getPublicExponent().toString();
		//私钥指数
		String private_exponent = privateKey.getPrivateExponent().toString();
		//明文
		String ming = "123456789";
		//使用模和指数生成公钥和私钥
		RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus, public_exponent);
		RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus, private_exponent);
		//加密后的密文
		String mi = RSAUtils.encryptByPublicKey(ming, pubKey);
		System.err.println(mi);
		//解密后的明文
		ming = RSAUtils.decryptByPrivateKey(mi, priKey);
		System.err.println(ming);
	}


RSAUtils.java

  1. package yyy.test.rsa; 
  2.  
  3. import java.math.BigInteger; 
  4. import java.security.KeyFactory; 
  5. import java.security.KeyPair; 
  6. import java.security.KeyPairGenerator; 
  7. import java.security.NoSuchAlgorithmException; 
  8. import java.security.interfaces.RSAPrivateKey; 
  9. import java.security.interfaces.RSAPublicKey; 
  10. import java.security.spec.RSAPrivateKeySpec; 
  11. import java.security.spec.RSAPublicKeySpec; 
  12. import java.util.HashMap; 
  13.  
  14. import javax.crypto.Cipher; 
  15.  
  16. public class RSAUtils { 
  17.  
  18.     /**
  19.      * 生成公钥和私钥
  20.      * @throws NoSuchAlgorithmException
  21.      *
  22.      */ 
  23.     public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException{ 
  24.         HashMap<String, Object> map = new HashMap<String, Object>(); 
  25.         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); 
  26.         keyPairGen.initialize(1024); 
  27.         KeyPair keyPair = keyPairGen.generateKeyPair(); 
  28.         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); 
  29.         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); 
  30.         map.put("public", publicKey); 
  31.         map.put("private", privateKey); 
  32.         return map; 
  33.     } 
  34.     /**
  35.      * 使用模和指数生成RSA公钥
  36.      * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
  37.      * /None/NoPadding】
  38.      *
  39.      * @param modulus
  40.      *            模
  41.      * @param exponent
  42.      *            指数
  43.      * @return
  44.      */ 
  45.     public static RSAPublicKey getPublicKey(String modulus, String exponent) { 
  46.         try
  47.             BigInteger b1 = new BigInteger(modulus); 
  48.             BigInteger b2 = new BigInteger(exponent); 
  49.             KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
  50.             RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2); 
  51.             return (RSAPublicKey) keyFactory.generatePublic(keySpec); 
  52.         } catch (Exception e) { 
  53.             e.printStackTrace(); 
  54.             return null
  55.         } 
  56.     } 
  57.  
  58.     /**
  59.      * 使用模和指数生成RSA私钥
  60.      * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
  61.      * /None/NoPadding】
  62.      *
  63.      * @param modulus
  64.      *            模
  65.      * @param exponent
  66.      *            指数
  67.      * @return
  68.      */ 
  69.     public static RSAPrivateKey getPrivateKey(String modulus, String exponent) { 
  70.         try
  71.             BigInteger b1 = new BigInteger(modulus); 
  72.             BigInteger b2 = new BigInteger(exponent); 
  73.             KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
  74.             RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2); 
  75.             return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); 
  76.         } catch (Exception e) { 
  77.             e.printStackTrace(); 
  78.             return null
  79.         } 
  80.     } 
  81.  
  82.     /**
  83.      * 公钥加密
  84.      *
  85.      * @param data
  86.      * @param publicKey
  87.      * @return
  88.      * @throws Exception
  89.      */ 
  90.     public static String encryptByPublicKey(String data, RSAPublicKey publicKey) 
  91.             throws Exception { 
  92.         Cipher cipher = Cipher.getInstance("RSA"); 
  93.         cipher.init(Cipher.ENCRYPT_MODE, publicKey); 
  94.         // 模长 
  95.         int key_len = publicKey.getModulus().bitLength() / 8
  96.         // 加密数据长度 <= 模长-11 
  97.         String[] datas = splitString(data, key_len - 11); 
  98.         String mi = ""
  99.         //如果明文长度大于模长-11则要分组加密 
  100.         for (String s : datas) { 
  101.             mi += bcd2Str(cipher.doFinal(s.getBytes())); 
  102.         } 
  103.         return mi; 
  104.     } 
  105.  
  106.     /**
  107.      * 私钥解密
  108.      *
  109.      * @param data
  110.      * @param privateKey
  111.      * @return
  112.      * @throws Exception
  113.      */ 
  114.     public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey) 
  115.             throws Exception { 
  116.         Cipher cipher = Cipher.getInstance("RSA"); 
  117.         cipher.init(Cipher.DECRYPT_MODE, privateKey); 
  118.         //模长 
  119.         int key_len = privateKey.getModulus().bitLength() / 8
  120.         byte[] bytes = data.getBytes(); 
  121.         byte[] bcd = ASCII_To_BCD(bytes, bytes.length); 
  122.         System.err.println(bcd.length); 
  123.         //如果密文长度大于模长则要分组解密 
  124.         String ming = ""
  125.         byte[][] arrays = splitArray(bcd, key_len); 
  126.         for(byte[] arr : arrays){ 
  127.             ming += new String(cipher.doFinal(arr)); 
  128.         } 
  129.         return ming; 
  130.     } 
  131.     /**
  132.      * ASCII码转BCD码
  133.      *
  134.      */ 
  135.     public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) { 
  136.         byte[] bcd = new byte[asc_len / 2]; 
  137.         int j = 0
  138.         for (int i = 0; i < (asc_len + 1) / 2; i++) { 
  139.             bcd[i] = asc_to_bcd(ascii[j++]); 
  140.             bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4)); 
  141.         } 
  142.         return bcd; 
  143.     } 
  144.     public static byte asc_to_bcd(byte asc) { 
  145.         byte bcd; 
  146.  
  147.         if ((asc >= '0') && (asc <= '9')) 
  148.             bcd = (byte) (asc - '0'); 
  149.         else if ((asc >= 'A') && (asc <= 'F')) 
  150.             bcd = (byte) (asc - 'A' + 10); 
  151.         else if ((asc >= 'a') && (asc <= 'f')) 
  152.             bcd = (byte) (asc - 'a' + 10); 
  153.         else 
  154.             bcd = (byte) (asc - 48); 
  155.         return bcd; 
  156.     } 
  157.     /**
  158.      * BCD转字符串
  159.      */ 
  160.     public static String bcd2Str(byte[] bytes) { 
  161.         char temp[] = new char[bytes.length * 2], val; 
  162.  
  163.         for (int i = 0; i < bytes.length; i++) { 
  164.             val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f); 
  165.             temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0'); 
  166.  
  167.             val = (char) (bytes[i] & 0x0f); 
  168.             temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0'); 
  169.         } 
  170.         return new String(temp); 
  171.     } 
  172.     /**
  173.      * 拆分字符串
  174.      */ 
  175.     public static String[] splitString(String string, int len) { 
  176.         int x = string.length() / len; 
  177.         int y = string.length() % len; 
  178.         int z = 0
  179.         if (y != 0) { 
  180.             z = 1
  181.         } 
  182.         String[] strings = new String[x + z]; 
  183.         String str = ""
  184.         for (int i=0; i<x+z; i++) { 
  185.             if (i==x+z-1 && y!=0) { 
  186.                 str = string.substring(i*len, i*len+y); 
  187.             }else
  188.                 str = string.substring(i*len, i*len+len); 
  189.             } 
  190.             strings[i] = str; 
  191.         } 
  192.         return strings; 
  193.     } 
  194.     /**
  195.      *拆分数组
  196.      */ 
  197.     public static byte[][] splitArray(byte[] data,int len){ 
  198.         int x = data.length / len; 
  199.         int y = data.length % len; 
  200.         int z = 0
  201.         if(y!=0){ 
  202.             z = 1
  203.         } 
  204.         byte[][] arrays = new byte[x+z][]; 
  205.         byte[] arr; 
  206.         for(int i=0; i<x+z; i++){ 
  207.             arr = new byte[len]; 
  208.             if(i==x+z-1 && y!=0){ 
  209.                 System.arraycopy(data, i*len, arr, 0, y); 
  210.             }else
  211.                 System.arraycopy(data, i*len, arr, 0, len); 
  212.             } 
  213.             arrays[i] = arr; 
  214.         } 
  215.         return arrays; 
  216.     } 
package yyy.test.rsa;

import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.HashMap;

import javax.crypto.Cipher;

public class RSAUtils {

	/**
	 * 生成公钥和私钥
	 * @throws NoSuchAlgorithmException 
	 *
	 */
	public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException{
		HashMap<String, Object> map = new HashMap<String, Object>();
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        map.put("public", publicKey);
        map.put("private", privateKey);
        return map;
	}
	/**
	 * 使用模和指数生成RSA公钥
	 * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
	 * /None/NoPadding】
	 * 
	 * @param modulus
	 *            模
	 * @param exponent
	 *            指数
	 * @return
	 */
	public static RSAPublicKey getPublicKey(String modulus, String exponent) {
		try {
			BigInteger b1 = new BigInteger(modulus);
			BigInteger b2 = new BigInteger(exponent);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
			return (RSAPublicKey) keyFactory.generatePublic(keySpec);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 使用模和指数生成RSA私钥
	 * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
	 * /None/NoPadding】
	 * 
	 * @param modulus
	 *            模
	 * @param exponent
	 *            指数
	 * @return
	 */
	public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
		try {
			BigInteger b1 = new BigInteger(modulus);
			BigInteger b2 = new BigInteger(exponent);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
			return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 公钥加密
	 * 
	 * @param data
	 * @param publicKey
	 * @return
	 * @throws Exception
	 */
	public static String encryptByPublicKey(String data, RSAPublicKey publicKey)
			throws Exception {
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		// 模长
		int key_len = publicKey.getModulus().bitLength() / 8;
		// 加密数据长度 <= 模长-11
		String[] datas = splitString(data, key_len - 11);
		String mi = "";
		//如果明文长度大于模长-11则要分组加密
		for (String s : datas) {
			mi += bcd2Str(cipher.doFinal(s.getBytes()));
		}
		return mi;
	}

	/**
	 * 私钥解密
	 * 
	 * @param data
	 * @param privateKey
	 * @return
	 * @throws Exception
	 */
	public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)
			throws Exception {
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		//模长
		int key_len = privateKey.getModulus().bitLength() / 8;
		byte[] bytes = data.getBytes();
		byte[] bcd = ASCII_To_BCD(bytes, bytes.length);
		System.err.println(bcd.length);
		//如果密文长度大于模长则要分组解密
		String ming = "";
		byte[][] arrays = splitArray(bcd, key_len);
		for(byte[] arr : arrays){
			ming += new String(cipher.doFinal(arr));
		}
		return ming;
	}
	/**
	 * ASCII码转BCD码
	 * 
	 */
	public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {
		byte[] bcd = new byte[asc_len / 2];
		int j = 0;
		for (int i = 0; i < (asc_len + 1) / 2; i++) {
			bcd[i] = asc_to_bcd(ascii[j++]);
			bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));
		}
		return bcd;
	}
	public static byte asc_to_bcd(byte asc) {
		byte bcd;

		if ((asc >= '0') && (asc <= '9'))
			bcd = (byte) (asc - '0');
		else if ((asc >= 'A') && (asc <= 'F'))
			bcd = (byte) (asc - 'A' + 10);
		else if ((asc >= 'a') && (asc <= 'f'))
			bcd = (byte) (asc - 'a' + 10);
		else
			bcd = (byte) (asc - 48);
		return bcd;
	}
	/**
	 * BCD转字符串
	 */
	public static String bcd2Str(byte[] bytes) {
		char temp[] = new char[bytes.length * 2], val;

		for (int i = 0; i < bytes.length; i++) {
			val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
			temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');

			val = (char) (bytes[i] & 0x0f);
			temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
		}
		return new String(temp);
	}
	/**
	 * 拆分字符串
	 */
	public static String[] splitString(String string, int len) {
		int x = string.length() / len;
		int y = string.length() % len;
		int z = 0;
		if (y != 0) {
			z = 1;
		}
		String[] strings = new String[x + z];
		String str = "";
		for (int i=0; i<x+z; i++) {
			if (i==x+z-1 && y!=0) {
				str = string.substring(i*len, i*len+y);
			}else{
				str = string.substring(i*len, i*len+len);
			}
			strings[i] = str;
		}
		return strings;
	}
	/**
	 *拆分数组 
	 */
	public static byte[][] splitArray(byte[] data,int len){
		int x = data.length / len;
		int y = data.length % len;
		int z = 0;
		if(y!=0){
			z = 1;
		}
		byte[][] arrays = new byte[x+z][];
		byte[] arr;
		for(int i=0; i<x+z; i++){
			arr = new byte[len];
			if(i==x+z-1 && y!=0){
				System.arraycopy(data, i*len, arr, 0, y);
			}else{
				System.arraycopy(data, i*len, arr, 0, len);
			}
			arrays[i] = arr;
		}
		return arrays;
	}
}
  1. java 
  2. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 
  3. android 
  4. Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding"); 
  5.  
  6. 参考: 
  7. http://stackoverflow.com/questions/6069369/rsa-encryption-difference-between-java-and-android 
  8. http://stackoverflow.com/questions/2956647/rsa-encrypt-with-base64-encoded-public-key-in-android 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值