java RSA

  1. package test;   
  2.   
  3. import java.io.ByteArrayOutputStream;   
  4. import java.io.File;   
  5. import java.io.FileInputStream;   
  6. import java.math.BigInteger;   
  7. import java.security.Key;   
  8. import java.security.KeyFactory;   
  9. import java.security.KeyPair;   
  10. import java.security.PublicKey;   
  11. import java.security.interfaces.RSAPrivateKey;   
  12. import java.security.interfaces.RSAPublicKey;   
  13. import java.security.spec.PKCS8EncodedKeySpec;   
  14. import java.security.spec.RSAPrivateKeySpec;   
  15. import java.security.spec.RSAPublicKeySpec;   
  16. import java.security.spec.X509EncodedKeySpec;   
  17. import java.util.HashMap;   
  18. import common.tools.RSAUtil;   
  19. import javax.crypto.Cipher;   
  20.   
  21. import org.bouncycastle.jce.provider.BouncyCastleProvider;   
  22.   
  23. import com.sun.org.apache.xml.internal.security.utils.Base64;   
  24.   
  25. import mas.Field;   
  26. import mas.MasMain;   
  27. import mas.field.ReturnDataVO;   
  28. import mas.http.TerminalClient;   
  29.   
  30. public class StorageTest {   
  31.   
  32.     public static final String KEY_ALGORITHM = "RSA";         
  33.     public static final String SIGNATURE_ALGORITHM = "MD5withRSA";         
  34.         
  35.     private static final String PUBLIC_KEY = "RSAPublicKey";         
  36.     private static final String PRIVATE_KEY = "RSAPrivateKey";    
  37.        
  38.     //RSA加密后的base64    
  39.     String serc = "AiX8oIzUDi6mHU+C9o7e8Z9gUoZs54+mH6y8/u0kUdy8pYAOkvn4RMoUKKFJn+VlqS9/s4QS7U2jBZ4wGG68mGmIDBXy2KMfXWDC8W9X2Xi9PvqlTMWGqdJ4LxHf1LUBWS81jjcY6MLTcou15rjlFfLLyAL5enEQ3ZpP3MDV19w=";   
  40.     //原串   
  41.     String orgStr = "fDdr/Z253xoWArVPy155QOmXDinjAoos";   
  42.        
  43.            
  44.     private static BouncyCastleProvider bcProvider = new BouncyCastleProvider();   
  45.        
  46.     //其它测试   
  47.     public void test0() throws Exception{   
  48.         String  filePath  =System.getProperty("user.dir") + "/mas.properties" ;   
  49.         MasMain mm = new MasMain();   
  50.         mm.getDataFormater(filePath, "17");   
  51.            
  52.         //ReturnDataVO returnvo  = mm.getDataFormater(filePath, "03");   
  53.         //HashMap<String, Field> hm =  mm.smartAnalysis(returnvo);   
  54.         //得到120数据   
  55.         //byte[] bData = hm.get("120").bValue;   
  56.     }   
  57.        
  58.        
  59.     public void test4() throws Exception{   
  60.         String  filePath  =System.getProperty("user.dir") + "/mas.properties" ;   
  61.         MasMain mm = new MasMain();   
  62.         byte[] bData = common.tools.Base64.getByteFromBASE64(serc);   
  63.         byte[] pubKeyBytes = mm.getPubKey("D://MX090723092600000034.pub.der");   
  64.         byte[] pubRndBytes = mm.getPubKey("D://MX090723092600000034ran.txt");    
  65.            
  66.         RSAPublicKey pubKey =common.tools.RSAUtil.generateRSAPublicKey(pubRndBytes, pubKeyBytes);   
  67.         byte[] decrptBytes = common.tools.RSAUtil.decrypt(pubKey, bData);   
  68.         String base64 = common.tools.Base64.getBASE64FromByte(decrptBytes);   
  69.         System.out.println("解密后:" + base64);   
  70.     }   
  71.        
  72.     //私钥加密 -- 公钥解密 方法   
  73.     public void test1() throws Exception{   
  74.         String  filePath  =System.getProperty("user.dir") + "/mas.properties" ;   
  75.         MasMain mm = new MasMain();   
  76.            
  77.         byte[] bData = common.tools.Base64.getByteFromBASE64(serc);   
  78.         byte[] pubKeyBytes = mm.getPubKey("D://MX090723092600000034.pub.der");   
  79.            
  80.            
  81.         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKeyBytes);   
  82.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);         
  83.         Key publicKey = keyFactory.generatePublic(x509KeySpec);         
  84.         
  85.         // 对数据解密   
  86.         byte[] storKeyByte = common.tools.RSAUtil.decrypt(publicKey, bData);   
  87.         String base64 = common.tools.Base64.getBASE64FromByte(storKeyByte);   
  88.         System.out.println("解密后:" + base64 );   
  89.            
  90.     }   
  91.        
  92.     //RSA ran部分,解密加密串   
  93.     public void test2() throws Exception{   
  94.         MasMain mm = new MasMain();   
  95.         byte[] priRanByte = mm.getPubKey("D://MX090723092600000034ran.txt"); //指数文件   
  96.         byte[] pubExpByte =Base64.decode("AQAB");      
  97.         RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(   
  98.                 priRanByte), new BigInteger(pubExpByte));   
  99.            
  100.         KeyFactory keyFac =  KeyFactory.getInstance("RSA",new BouncyCastleProvider());   
  101.         Key pubKey = keyFac.generatePublic(pubKeySpec);   
  102.            
  103.            
  104.         byte[] storKeyByte = RSAUtil.decrypt(pubKey , common.tools.Base64.getByteFromBASE64(serc));   
  105.         String base64 = common.tools.Base64.getBASE64FromByte(storKeyByte);   
  106.         System.out.println("解密后:" + base64);   
  107.            
  108.     }   
  109.   
  110.     public void test3() throws Exception{   
  111.         KeyPair keyPair=RSAUtil.generateKeyPair();   
  112.         RSAPublicKey pub=(RSAPublicKey)keyPair.getPublic();   
  113.         RSAPrivateKey pri=(RSAPrivateKey)keyPair.getPrivate();   
  114.         byte[] pubByte=pub.getPublicExponent().toByteArray();   
  115.         byte[] priByte=pri.getPrivateExponent().toByteArray();   
  116.         byte[] priRanByte=pri.getModulus().toByteArray();   
  117.         byte[] pubRanByte=pub.getModulus().toByteArray();   
  118.         byte[] pubKey=pub.getEncoded();   
  119.         byte[] priKey=pri.getEncoded();   
  120.            
  121.         System.out.println(common.tools.Base64.getBASE64FromByte(priRanByte));   
  122.         System.out.println(common.tools.Base64.getBASE64FromByte(pubRanByte));   
  123.     }   
  124. }  
package test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import common.tools.RSAUtil;
import javax.crypto.Cipher;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import com.sun.org.apache.xml.internal.security.utils.Base64;

import mas.Field;
import mas.MasMain;
import mas.field.ReturnDataVO;
import mas.http.TerminalClient;

public class StorageTest {

    public static final String KEY_ALGORITHM = "RSA";      
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";      
     
    private static final String PUBLIC_KEY = "RSAPublicKey";      
    private static final String PRIVATE_KEY = "RSAPrivateKey"; 
    
	//RSA加密后的base64 
	String serc = "AiX8oIzUDi6mHU+C9o7e8Z9gUoZs54+mH6y8/u0kUdy8pYAOkvn4RMoUKKFJn+VlqS9/s4QS7U2jBZ4wGG68mGmIDBXy2KMfXWDC8W9X2Xi9PvqlTMWGqdJ4LxHf1LUBWS81jjcY6MLTcou15rjlFfLLyAL5enEQ3ZpP3MDV19w=";
	//原串
	String orgStr = "fDdr/Z253xoWArVPy155QOmXDinjAoos";
	
		
	private static BouncyCastleProvider bcProvider = new BouncyCastleProvider();
	
	//其它测试
	public void test0() throws Exception{
		String  filePath  =System.getProperty("user.dir") + "/mas.properties" ;
		MasMain mm = new MasMain();
		mm.getDataFormater(filePath, "17");
		
		//ReturnDataVO returnvo  = mm.getDataFormater(filePath, "03");
		//HashMap<String, Field> hm =  mm.smartAnalysis(returnvo);
		//得到120数据
		//byte[] bData = hm.get("120").bValue;
	}
	
	
	public void test4() throws Exception{
		String  filePath  =System.getProperty("user.dir") + "/mas.properties" ;
		MasMain mm = new MasMain();
		byte[] bData = common.tools.Base64.getByteFromBASE64(serc);
		byte[] pubKeyBytes = mm.getPubKey("D://MX090723092600000034.pub.der");
		byte[] pubRndBytes = mm.getPubKey("D://MX090723092600000034ran.txt"); 
		
		RSAPublicKey pubKey =common.tools.RSAUtil.generateRSAPublicKey(pubRndBytes, pubKeyBytes);
		byte[] decrptBytes = common.tools.RSAUtil.decrypt(pubKey, bData);
		String base64 = common.tools.Base64.getBASE64FromByte(decrptBytes);
		System.out.println("解密后:" + base64);
	}
	
	//私钥加密 -- 公钥解密 方法
	public void test1() throws Exception{
		String  filePath  =System.getProperty("user.dir") + "/mas.properties" ;
		MasMain mm = new MasMain();
		
		byte[] bData = common.tools.Base64.getByteFromBASE64(serc);
		byte[] pubKeyBytes = mm.getPubKey("D://MX090723092600000034.pub.der");
		
		
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);      
        Key publicKey = keyFactory.generatePublic(x509KeySpec);      
     
        // 对数据解密
        byte[] storKeyByte = common.tools.RSAUtil.decrypt(publicKey, bData);
        String base64 = common.tools.Base64.getBASE64FromByte(storKeyByte);
		System.out.println("解密后:" + base64 );
		
	}
	
	//RSA ran部分,解密加密串
	public void test2() throws Exception{
		MasMain mm = new MasMain();
		byte[] priRanByte = mm.getPubKey("D://MX090723092600000034ran.txt"); //指数文件
		byte[] pubExpByte =Base64.decode("AQAB");	
		RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(
				priRanByte), new BigInteger(pubExpByte));
		
		KeyFactory keyFac =  KeyFactory.getInstance("RSA",new BouncyCastleProvider());
		Key pubKey = keyFac.generatePublic(pubKeySpec);
		
		
		byte[] storKeyByte = RSAUtil.decrypt(pubKey , common.tools.Base64.getByteFromBASE64(serc));
		String base64 = common.tools.Base64.getBASE64FromByte(storKeyByte);
		System.out.println("解密后:" + base64);
		
	}

	public void test3() throws Exception{
		KeyPair keyPair=RSAUtil.generateKeyPair();
		RSAPublicKey pub=(RSAPublicKey)keyPair.getPublic();
		RSAPrivateKey pri=(RSAPrivateKey)keyPair.getPrivate();
		byte[] pubByte=pub.getPublicExponent().toByteArray();
		byte[] priByte=pri.getPrivateExponent().toByteArray();
		byte[] priRanByte=pri.getModulus().toByteArray();
		byte[] pubRanByte=pub.getModulus().toByteArray();
		byte[] pubKey=pub.getEncoded();
		byte[] priKey=pri.getEncoded();
		
		System.out.println(common.tools.Base64.getBASE64FromByte(priRanByte));
		System.out.println(common.tools.Base64.getBASE64FromByte(pubRanByte));
	}
}

 

 

不要问,自已看代码。

引用: http://www.samwong.cn

 

Java代码 复制代码
  1. package common.tools;   
  2.   
  3. import javax.crypto.BadPaddingException;   
  4. import javax.crypto.Cipher;ng   
  5. import javax.crypto.IllegalBlockSizeException;   
  6. import javax.crypto.NoSuchPaddingException;   
  7. import javax.crypto.ShortBufferException;   
  8.   
  9. import java.security.InvalidKeyException;   
  10. import java.security.Key;   
  11. import java.security.KeyFactory;   
  12. import java.security.KeyPair;   
  13. import java.security.KeyPairGenerator;   
  14. import java.security.NoSuchAlgorithmException;   
  15. import java.security.SecureRandom;   
  16. import java.security.spec.RSAPublicKeySpec;   
  17. import java.security.spec.RSAPrivateKeySpec;   
  18. import java.security.spec.InvalidKeySpecException;   
  19. import java.security.interfaces.RSAPrivateKey;   
  20. import java.security.interfaces.RSAPublicKey;   
  21.   
  22. import java.io.ByteArrayOutputStream;   
  23. import java.io.IOException;   
  24.   
  25. import java.math.BigInteger;   
  26.   
  27. import org.bouncycastle.jce.provider.BouncyCastleProvider;   
  28.   
  29. public class RSAUtil {   
  30.        
  31.     private static BouncyCastleProvider bcProvider = new BouncyCastleProvider();   
  32.        
  33.     /**  
  34.      *   
  35.      * 生成密钥对  
  36.      *   
  37.      * @return KeyPair  
  38.      *   
  39.      * @throws EncryptException  
  40.      *   
  41.      */  
  42.   
  43.     public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {   
  44.   
  45.         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",bcProvider);   
  46.         final int KEY_SIZE = 1024;   
  47.         keyPairGen.initialize(KEY_SIZE, new SecureRandom());   
  48.         KeyPair keyPair = keyPairGen.genKeyPair();   
  49.         return keyPair;   
  50.     }   
  51.   
  52.     /**  
  53.      *   
  54.      * 生成公钥  
  55.      *   
  56.      * @param modulus  
  57.      *   
  58.      * @param publicExponent  
  59.      *   
  60.      * @return RSAPublicKey  
  61.      *   
  62.      * @throws EncryptException  
  63.      *   
  64.      */  
  65.   
  66.     public static RSAPublicKey generateRSAPublicKey(byte[] modulus,   
  67.             byte[] publicExponent) throws NoSuchAlgorithmException,   
  68.             InvalidKeySpecException {   
  69.   
  70.         KeyFactory keyFac = null;   
  71.         keyFac = KeyFactory.getInstance("RSA",bcProvider);   
  72.         RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(   
  73.                 modulus), new BigInteger(publicExponent));   
  74.         return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);   
  75.   
  76.     }   
  77.   
  78.     /**  
  79.      *   
  80.      * 生成私钥  
  81.      *   
  82.      * @param modulus  
  83.      *   
  84.      * @param privateExponent  
  85.      *   
  86.      * @return RSAPrivateKey  
  87.      *   
  88.      * @throws EncryptException  
  89.      *   
  90.      */  
  91.   
  92.     public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus,   
  93.             byte[] privateExponent) throws NoSuchAlgorithmException,   
  94.             InvalidKeySpecException {   
  95.   
  96.         KeyFactory keyFac = null;   
  97.   
  98.         keyFac = KeyFactory.getInstance("RSA",bcProvider);   
  99.   
  100.         RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(   
  101.                 modulus), new BigInteger(privateExponent));   
  102.   
  103.         return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);   
  104.   
  105.     }   
  106.   
  107.     /**  
  108.      *   
  109.      * 加密  
  110.      *   
  111.      * @param key  
  112.      *            加密的密钥  
  113.      *   
  114.      * @param data  
  115.      *            待加密的明文数据  
  116.      *   
  117.      * @return 加密后的数据  
  118.      *   
  119.      * @throws EncryptException  
  120.      *   
  121.      */  
  122.   
  123.     public static byte[] encrypt(Key key, byte[] data)   
  124.             throws NoSuchPaddingException, NoSuchAlgorithmException,   
  125.             InvalidKeyException, ShortBufferException, IllegalBlockSizeException,BadPaddingException {   
  126.   
  127.         Cipher cipher = Cipher.getInstance("RSA",bcProvider);   
  128.         cipher.init(Cipher.ENCRYPT_MODE, key);   
  129.   
  130.         int blockSize = cipher.getBlockSize();   
  131.         //System.out.println(blockSize);   
  132.         // 获得加密块大小,如:加密前数据为128个byte,而key_size=1024   
  133.         // 加密块大小为127   
  134.         // byte,加密后为128个byte;因此共有2个加密块,第一个127   
  135.         // byte第二个为1个byte   
  136.   
  137.         int outputSize = cipher.getOutputSize(data.length);// 获得加密块加密后块大小   
  138.   
  139.         int leavedSize = data.length % blockSize;   
  140.   
  141.         int blocksSize = leavedSize != 0 ? data.length / blockSize + 1  
  142.                 : data.length / blockSize;   
  143.   
  144.         byte[] raw = new byte[outputSize * blocksSize];   
  145.   
  146.         int i = 0;   
  147.   
  148.         while (data.length - i * blockSize > 0) {   
  149.   
  150.             if (data.length - i * blockSize > blockSize)   
  151.   
  152.                 cipher.doFinal(data, i * blockSize, blockSize, raw, i   
  153.                         * outputSize);   
  154.   
  155.             else  
  156.   
  157.                 cipher.doFinal(data, i * blockSize,   
  158.                         data.length - i * blockSize, raw, i * outputSize);   
  159.   
  160.             i++;   
  161.   
  162.         }   
  163.   
  164.         return raw;   
  165.   
  166.     }   
  167.   
  168.     /**  
  169.      *   
  170.      * 解密  
  171.      *   
  172.      * @param key  
  173.      *            解密的密钥  
  174.      *   
  175.      * @param raw  
  176.      *            已经加密的数据  
  177.      *   
  178.      * @return 解密后的明文  
  179.      *   
  180.      * @throws EncryptException  
  181.      *   
  182.      */  
  183.   
  184.     public static byte[] decrypt(Key key, byte[] raw)   
  185.             throws NoSuchPaddingException, NoSuchAlgorithmException,   
  186.             InvalidKeyException, ShortBufferException,BadPaddingException,IllegalBlockSizeException,IOException {   
  187.   
  188.         Cipher cipher = Cipher.getInstance("RSA",bcProvider);   
  189.   
  190.         cipher.init(cipher.DECRYPT_MODE, key);   
  191.   
  192.         int blockSize = cipher.getBlockSize();   
  193.   
  194.         ByteArrayOutputStream bout = new ByteArrayOutputStream(64);   
  195.   
  196.         int j = 0;   
  197.   
  198.         while (raw.length - j * blockSize > 0) {   
  199.   
  200.             bout.write(cipher.doFinal(raw, j * blockSize, blockSize));   
  201.   
  202.             j++;   
  203.   
  204.         }   
  205.   
  206.         return bout.toByteArray();   
  207.   
  208.     }   
  209.   
  210.   
  211. }  
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值