IT序号网

RSA对称加密算法知识解答

lxf 2021年06月13日 编程语言 140 0
import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.security.InvalidKeyException; 
import java.security.KeyFactory; 
import java.security.KeyPair; 
import java.security.KeyPairGenerator; 
import java.security.NoSuchAlgorithmException; 
import java.security.SecureRandom; 
import java.security.interfaces.RSAPrivateKey; 
import java.security.interfaces.RSAPublicKey; 
import java.security.spec.InvalidKeySpecException; 
import java.security.spec.PKCS8EncodedKeySpec; 
import java.security.spec.X509EncodedKeySpec; 
 
import javax.crypto.BadPaddingException; 
import javax.crypto.Cipher; 
import javax.crypto.IllegalBlockSizeException; 
import javax.crypto.NoSuchPaddingException; 
 
import org.bouncycastle.jce.provider.BouncyCastleProvider; 
 
import sun.misc.BASE64Decoder; 
 
public class RSAEncrypt { 
	 
	private static final String DEFAULT_PUBLIC_KEY1="" 
			+"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGaeXY1/bTQ/exo57QGqZ30FNV" 
			+"saPKyz1SJtjVj+5gYs0ml9YGqzXm2Y3xtR9q2xkdO5TKMkDeL95Lidp49RAOMC8/" 
			+"105LkyESwZVVAWB8GKS5RbCi7chbct0alYT2eSJkI9ihEc8aouQ2/P5+sGUUqzVP" 
			+"e/n+bs7fTlL4OJV/bQIDAQAB"; 
	 
	private static final String DEFAULT_PRIVATE_KEY="" 
			+"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAMZp5djX9tND97Gj" 
			+"ntAapnfQU1Wxo8rLPVIm2NWP7mBizSaX1garNebZjfG1H2rbGR07lMoyQN4v3kuJ" 
			+"2nj1EA4wLz/XTkuTIRLBlVUBYHwYpLlFsKLtyFty3RqVhPZ5ImQj2KERzxqi5Db8" 
			+"/n6wZRSrNU97+f5uzt9OUvg4lX9tAgMBAAECgYA6ijQObmmcm4kRGD1bGQHUh9qO" 
			+"hgLVanGFM4D2QakLNxtgL5wuC4WzvqxqjA3g8RPP1CxqG7mX1He5wcp7tZIumHa3" 
			+"iE7jok0y8behrf3/esw3RGiPia2q7ue1kQeC6CoRd1kByhaBs/z6W0g7/YdEpwI+" 
			+"T7rWVwI03p2Z8XrgAQJBAOUIqhTRKscLnaBRHBk1zG3UjFmJKgrp9gHGyYJfax5d" 
			+"SZDl25e8WT9sdIBQfHysH1bvQIsdfMJPXvfwr2pPXQECQQDdxk6Yx1LGJDdlH/Qy" 
			+"15NFZvke/xDYvN2YqjkFoMdp2aFH7T+p1nBUVtd0fWcQaMAulQBnePh81BPDIJvb" 
			+"POZtAkBwvWcbgCrSeAFLXSG7tyO+HJZJrJ8paClUjom6x0VvWPRRgxQpCOnVsolW" 
			+"cEgXBpMWtAbNc+Jps7BH1A5FAnQBAkArFoVcv5VAc/bjSeMLIcE2QbxzHkFqqr8v" 
			+"ExuDEWrNEQB51gmBeO1YJYs00cx9bqywIDj04Zb9wcKZLbO6U8m9AkAEIOaCFC9A" 
			+"3I4kC+n3PI2RiyKm2Y4pIc8hvLF7fdKRJLhE6CU54HfnWfp60cafLQbArfQPaJeq" 
			+"fRwmeXX3YHU1"; 
 
	/** 
	 * 私钥 
	 */ 
	private RSAPrivateKey privateKey; 
 
	/** 
	 * 公钥 
	 */ 
	private RSAPublicKey publicKey; 
	 
	/** 
	 * 字节数据转字符串专用集合 
	 */ 
	private static final char[] HEX_CHAR= {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 
	 
 
	/** 
	 * 获取私钥 
	 * @return 当前的私钥对象 
	 */ 
	public RSAPrivateKey getPrivateKey() { 
		return privateKey; 
	} 
 
	/** 
	 * 获取公钥 
	 * @return 当前的公钥对象 
	 */ 
	public RSAPublicKey getPublicKey() { 
		return publicKey; 
	} 
 
	/** 
	 * 随机生成密钥对 
	 */ 
	public void genKeyPair(){ 
		KeyPairGenerator keyPairGen= null; 
		try { 
			keyPairGen= KeyPairGenerator.getInstance("RSA"); 
		} catch (NoSuchAlgorithmException e) { 
			e.printStackTrace(); 
		} 
		keyPairGen.initialize(1024, new SecureRandom()); 
		KeyPair keyPair= keyPairGen.generateKeyPair(); 
		this.privateKey= (RSAPrivateKey) keyPair.getPrivate(); 
		this.publicKey= (RSAPublicKey) keyPair.getPublic(); 
	} 
 
	/** 
	 * 从文件中输入流中加载公钥 
	 * @param in 公钥输入流 
	 * @throws Exception 加载公钥时产生的异常 
	 */ 
	public void loadPublicKey(InputStream in) throws Exception{ 
		try { 
			BufferedReader br= new BufferedReader(new InputStreamReader(in)); 
			String readLine= null; 
			StringBuilder sb= new StringBuilder(); 
			while((readLine= br.readLine())!=null){ 
				if(readLine.charAt(0)=='-'){ 
					continue; 
				}else{ 
					sb.append(readLine); 
					sb.append('\r'); 
				} 
			} 
			loadPublicKey(sb.toString()); 
		} catch (IOException e) { 
			throw new Exception("公钥数据流读取错误"); 
		} catch (NullPointerException e) { 
			throw new Exception("公钥输入流为空"); 
		} 
	} 
 
 
	/** 
	 * 从字符串中加载公钥 
	 * @param publicKeyStr 公钥数据字符串 
	 * @throws Exception 加载公钥时产生的异常 
	 */ 
	public void loadPublicKey(String publicKeyStr) throws Exception{ 
		try { 
			BASE64Decoder base64Decoder= new BASE64Decoder(); 
			byte[] buffer= base64Decoder.decodeBuffer(publicKeyStr); 
			KeyFactory keyFactory= KeyFactory.getInstance("RSA"); 
			X509EncodedKeySpec keySpec= new X509EncodedKeySpec(buffer); 
			this.publicKey= (RSAPublicKey) keyFactory.generatePublic(keySpec); 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此算法"); 
		} catch (InvalidKeySpecException e) { 
			throw new Exception("公钥非法"); 
		} catch (IOException e) { 
			throw new Exception("公钥数据内容读取错误"); 
		} catch (NullPointerException e) { 
			throw new Exception("公钥数据为空"); 
		} 
	} 
 
	/** 
	 * 从文件中加载私钥 
	 * @param keyFileName 私钥文件名 
	 * @return 是否成功 
	 * @throws Exception  
	 */ 
	public void loadPrivateKey(InputStream in) throws Exception{ 
		try { 
			BufferedReader br= new BufferedReader(new InputStreamReader(in)); 
			String readLine= null; 
			StringBuilder sb= new StringBuilder(); 
			while((readLine= br.readLine())!=null){ 
				if(readLine.charAt(0)=='-'){ 
					continue; 
				}else{ 
					sb.append(readLine); 
					sb.append('\r'); 
				} 
			} 
			loadPrivateKey(sb.toString()); 
		} catch (IOException e) { 
			throw new Exception("私钥数据读取错误"); 
		} catch (NullPointerException e) { 
			throw new Exception("私钥输入流为空"); 
		} 
	} 
 
	public void loadPrivateKey(String privateKeyStr) throws Exception{ 
		try { 
			BASE64Decoder base64Decoder= new BASE64Decoder(); 
			byte[] buffer= base64Decoder.decodeBuffer(privateKeyStr); 
			PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(buffer); 
			KeyFactory keyFactory= KeyFactory.getInstance("RSA"); 
			this.privateKey= (RSAPrivateKey) keyFactory.generatePrivate(keySpec); 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此算法"); 
		} catch (InvalidKeySpecException e) { 
			throw new Exception("私钥非法"); 
		} catch (IOException e) { 
			throw new Exception("私钥数据内容读取错误"); 
		} catch (NullPointerException e) { 
			throw new Exception("私钥数据为空"); 
		} 
	} 
 
	/** 
	 * 加密过程 
	 * @param publicKey 公钥 
	 * @param plainTextData 明文数据 
	 * @return 
	 * @throws Exception 加密过程中的异常信息 
	 */ 
	public byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception{ 
		if(publicKey== null){ 
			throw new Exception("加密公钥为空, 请设置"); 
		} 
		Cipher cipher= null; 
		try { 
			cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 
			cipher.init(Cipher.ENCRYPT_MODE, publicKey); 
			byte[] output= cipher.doFinal(plainTextData); 
			return output; 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此加密算法"); 
		} catch (NoSuchPaddingException e) { 
			e.printStackTrace(); 
			return null; 
		}catch (InvalidKeyException e) { 
			throw new Exception("加密公钥非法,请检查"); 
		} catch (IllegalBlockSizeException e) { 
			throw new Exception("明文长度非法"); 
		} catch (BadPaddingException e) { 
			throw new Exception("明文数据已损坏"); 
		} 
	} 
	 
	 
 
	/** 
	 * 解密过程 
	 * @param privateKey 私钥 
	 * @param cipherData 密文数据 
	 * @return 明文 
	 * @throws Exception 解密过程中的异常信息 
	 */ 
	public byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception{ 
		if (privateKey== null){ 
			throw new Exception("解密私钥为空, 请设置"); 
		} 
		Cipher cipher= null; 
		try { 
			cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 
			cipher.init(Cipher.DECRYPT_MODE, privateKey); 
			byte[] output= cipher.doFinal(cipherData); 
			return output; 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此解密算法"); 
		} catch (NoSuchPaddingException e) { 
			e.printStackTrace(); 
			return null; 
		}catch (InvalidKeyException e) { 
			throw new Exception("解密私钥非法,请检查"); 
		} catch (IllegalBlockSizeException e) { 
			throw new Exception("密文长度非法"); 
		} catch (BadPaddingException e) { 
			throw new Exception("密文数据已损坏"); 
		}		 
	} 
 
	 
	/** 
	 * 字节数据转十六进制字符串 
	 * @param data 输入数据 
	 * @return 十六进制内容 
	 */ 
	public static String byteArrayToString(byte[] data){ 
		StringBuilder stringBuilder= new StringBuilder(); 
		for (int i=0; i<data.length; i++){ 
			//取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移 
			stringBuilder.append(HEX_CHAR[(data[i] & 0xf0)>>> 4]); 
			//取出字节的低四位 作为索引得到相应的十六进制标识符 
			stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]); 
			if (i<data.length-1){ 
				stringBuilder.append(' '); 
			} 
		} 
		return stringBuilder.toString(); 
	} 
	 
	/** 
	 *  
	 * @param path 
	 * @return 
	 */ 
	  public static InputStream getPathStream(String path) { 
	         FileInputStream inputStream = null; 
	         File file = new File(path); 
	         try { 
	             inputStream = new FileInputStream(file); 
	         } catch (FileNotFoundException e) { 
	             e.printStackTrace(); 
	         } 
	         return inputStream; 
	 } 
	   
	public static void main(String[] args){ 
		RSAEncrypt rsaEncrypt= new RSAEncrypt(); 
		//rsaEncrypt.genKeyPair(); 
		//加载公钥 
		try { 
			rsaEncrypt.loadPublicKey(getPathStream("E:\\Key\\sg_public_key.pem")); 
			System.out.println("加载公钥成功"); 
		} catch (Exception e) { 
			System.err.println(e.getMessage()); 
			System.err.println("加载公钥失败"); 
		} 
 
		//加载私钥 
		try { 
			rsaEncrypt.loadPrivateKey(getPathStream("E:\\Key\\sg_private_key.pem")); 
			System.out.println("加载私钥成功"); 
		} catch (Exception e) { 
			System.err.println(e.getMessage()); 
			System.err.println("加载私钥失败"); 
		} 
 
		//测试字符串 
		String encryptStr= "车难用土"; 
 
		try { 
			//加密 
			byte[] cipher = rsaEncrypt.encrypt(rsaEncrypt.getPublicKey(), encryptStr.getBytes()); 
			//解密 
			byte[] plainText = rsaEncrypt.decrypt(rsaEncrypt.getPrivateKey(), cipher); 
			System.out.println("密文长度:"+ cipher.length); 
			System.out.println(RSAEncrypt.byteArrayToString(cipher)); 
			System.out.println("明文长度:"+ plainText.length); 
			System.out.println(RSAEncrypt.byteArrayToString(plainText)); 
			System.out.println(new String(plainText)); 
		} catch (Exception e) { 
			System.err.println(e.getMessage()); 
		} 
	} 
}



RSA在线生成地址:

IT虾米网


版本2 


import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.security.InvalidKeyException; 
import java.security.KeyFactory; 
import java.security.KeyPair; 
import java.security.KeyPairGenerator; 
import java.security.NoSuchAlgorithmException; 
import java.security.SecureRandom; 
import java.security.interfaces.RSAPrivateKey; 
import java.security.interfaces.RSAPublicKey; 
import java.security.spec.InvalidKeySpecException; 
import java.security.spec.PKCS8EncodedKeySpec; 
import java.security.spec.X509EncodedKeySpec; 
 
import javax.crypto.BadPaddingException; 
import javax.crypto.Cipher; 
import javax.crypto.IllegalBlockSizeException; 
import javax.crypto.NoSuchPaddingException; 
 
import org.bouncycastle.jce.provider.BouncyCastleProvider; 
 
 
 
 
 
import sun.misc.BASE64Decoder; 
import sun.misc.BASE64Encoder; 
 
 
public class RSAUtil { 
	/** 
	 * 私钥 
	 */ 
	private static  RSAPrivateKey privateKey; 
 
	/** 
	 * 公钥 
	 */ 
	private static  RSAPublicKey publicKey; 
	 
	/** 
	 * 字节数据转字符串专用集合 
	 */ 
	private static final char[] HEX_CHAR= {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 
	 
 
	static  
	{ 
		loadPublicKey(getPathStream("config//sg_public_key.pem")); 
		loadPrivateKey(getPathStream("config//sg_private_key.pem")); 
	} 
	private static final String DEFAULT_PUBLIC_KEY1="" 
			+"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGaeXY1/bTQ/exo57QGqZ30FNV" 
			+"saPKyz1SJtjVj+5gYs0ml9YGqzXm2Y3xtR9q2xkdO5TKMkDeL95Lidp49RAOMC8/" 
			+"105LkyESwZVVAWB8GKS5RbCi7chbct0alYT2eSJkI9ihEc8aouQ2/P5+sGUUqzVP" 
			+"e/n+bs7fTlL4OJV/bQIDAQAB"; 
	 
	private static final String DEFAULT_PRIVATE_KEY="" 
			+"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAMZp5djX9tND97Gj" 
			+"ntAapnfQU1Wxo8rLPVIm2NWP7mBizSaX1garNebZjfG1H2rbGR07lMoyQN4v3kuJ" 
			+"2nj1EA4wLz/XTkuTIRLBlVUBYHwYpLlFsKLtyFty3RqVhPZ5ImQj2KERzxqi5Db8" 
			+"/n6wZRSrNU97+f5uzt9OUvg4lX9tAgMBAAECgYA6ijQObmmcm4kRGD1bGQHUh9qO" 
			+"hgLVanGFM4D2QakLNxtgL5wuC4WzvqxqjA3g8RPP1CxqG7mX1He5wcp7tZIumHa3" 
			+"iE7jok0y8behrf3/esw3RGiPia2q7ue1kQeC6CoRd1kByhaBs/z6W0g7/YdEpwI+" 
			+"T7rWVwI03p2Z8XrgAQJBAOUIqhTRKscLnaBRHBk1zG3UjFmJKgrp9gHGyYJfax5d" 
			+"SZDl25e8WT9sdIBQfHysH1bvQIsdfMJPXvfwr2pPXQECQQDdxk6Yx1LGJDdlH/Qy" 
			+"15NFZvke/xDYvN2YqjkFoMdp2aFH7T+p1nBUVtd0fWcQaMAulQBnePh81BPDIJvb" 
			+"POZtAkBwvWcbgCrSeAFLXSG7tyO+HJZJrJ8paClUjom6x0VvWPRRgxQpCOnVsolW" 
			+"cEgXBpMWtAbNc+Jps7BH1A5FAnQBAkArFoVcv5VAc/bjSeMLIcE2QbxzHkFqqr8v" 
			+"ExuDEWrNEQB51gmBeO1YJYs00cx9bqywIDj04Zb9wcKZLbO6U8m9AkAEIOaCFC9A" 
			+"3I4kC+n3PI2RiyKm2Y4pIc8hvLF7fdKRJLhE6CU54HfnWfp60cafLQbArfQPaJeq" 
			+"fRwmeXX3YHU1"; 
 
	public static String base64Encoder(String str){ 
		 
		 BASE64Encoder encode = new BASE64Encoder(); 
		 return encode.encode(str.getBytes()); 
		  
	} 
 
	public static String base64Decoder(String str){ 
		 
		 BASE64Decoder decode=new BASE64Decoder(); 
		 String result=""; 
		  
		 byte[] b; 
			try { 
				b = decode.decodeBuffer(str); 
				result=new String(b); 
				 
			} catch (IOException e) { 
				e.printStackTrace(); 
			} 
		 
			return result; 
		  
	} 
 
	/** 
	 * 随机生成密钥对 
	 */ 
	public void genKeyPair(){ 
		KeyPairGenerator keyPairGen= null; 
		try { 
			keyPairGen= KeyPairGenerator.getInstance("RSA"); 
		} catch (NoSuchAlgorithmException e) { 
			e.printStackTrace(); 
		} 
		keyPairGen.initialize(1024, new SecureRandom()); 
		KeyPair keyPair= keyPairGen.generateKeyPair(); 
		this.privateKey= (RSAPrivateKey) keyPair.getPrivate(); 
		this.publicKey= (RSAPublicKey) keyPair.getPublic(); 
	} 
 
	/** 
	 * 从文件中输入流中加载公钥 
	 * @param in 公钥输入流 
	 * @throws Exception 加载公钥时产生的异常 
	 */ 
	public static void loadPublicKey(InputStream in) { 
		try { 
			BufferedReader br= new BufferedReader(new InputStreamReader(in)); 
			String readLine= null; 
			StringBuilder sb= new StringBuilder(); 
			while((readLine= br.readLine())!=null){ 
				if(readLine.charAt(0)=='-'){ 
					continue; 
				}else{ 
					sb.append(readLine); 
					sb.append('\r'); 
				} 
			} 
			loadPublicKey(sb.toString()); 
		} catch (Exception e) { 
			System.err.println("加载公钥失败"); 
			 
		}  
	} 
 
 
	/** 
	 * 从字符串中加载公钥 
	 * @param publicKeyStr 公钥数据字符串 
	 * @throws Exception 加载公钥时产生的异常 
	 */ 
	public static void loadPublicKey(String publicKeyStr) throws Exception{ 
		try { 
			BASE64Decoder base64Decoder= new BASE64Decoder(); 
			byte[] buffer= base64Decoder.decodeBuffer(publicKeyStr); 
			KeyFactory keyFactory= KeyFactory.getInstance("RSA"); 
			X509EncodedKeySpec keySpec= new X509EncodedKeySpec(buffer); 
			publicKey= (RSAPublicKey) keyFactory.generatePublic(keySpec); 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此算法"); 
		} catch (InvalidKeySpecException e) { 
			throw new Exception("公钥非法"); 
		} catch (IOException e) { 
			throw new Exception("公钥数据内容读取错误"); 
		} catch (NullPointerException e) { 
			throw new Exception("公钥数据为空"); 
		} 
	} 
 
	/** 
	 * 从文件中加载私钥 
	 * @param keyFileName 私钥文件名 
	 * @return 是否成功 
	 * @throws Exception  
	 */ 
	public static void loadPrivateKey(InputStream in){ 
		try { 
			BufferedReader br= new BufferedReader(new InputStreamReader(in)); 
			String readLine= null; 
			StringBuilder sb= new StringBuilder(); 
			while((readLine= br.readLine())!=null){ 
				if(readLine.charAt(0)=='-'){ 
					continue; 
				}else{ 
					sb.append(readLine); 
					sb.append('\r'); 
				} 
			} 
			loadPrivateKey(sb.toString()); 
		} catch (Exception e) { 
			System.err.println("加载私钥失败"); 
			 
		}  
	} 
 
	public static void loadPrivateKey(String privateKeyStr) throws Exception{ 
		try { 
			BASE64Decoder base64Decoder= new BASE64Decoder(); 
			byte[] buffer= base64Decoder.decodeBuffer(privateKeyStr); 
			PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(buffer); 
			KeyFactory keyFactory= KeyFactory.getInstance("RSA"); 
			privateKey= (RSAPrivateKey) keyFactory.generatePrivate(keySpec); 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此算法"); 
		} catch (InvalidKeySpecException e) { 
			throw new Exception("私钥非法"); 
		} catch (IOException e) { 
			throw new Exception("私钥数据内容读取错误"); 
		} catch (NullPointerException e) { 
			throw new Exception("私钥数据为空"); 
		} 
	} 
 
	/** 
	 * 加密过程 
	 * @param publicKey 公钥 
	 * @param plainTextData 明文数据 
	 * @return 
	 * @throws Exception 加密过程中的异常信息 
	 */ 
	public byte[] encrypt(byte[] plainTextData) throws Exception{ 
		 
		if(publicKey== null){ 
			throw new Exception("加密公钥为空, 请设置"); 
		} 
		Cipher cipher= null; 
		try { 
			cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 
			cipher.init(Cipher.ENCRYPT_MODE, publicKey); 
			byte[] output= cipher.doFinal(plainTextData); 
			return output; 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此加密算法"); 
		} catch (NoSuchPaddingException e) { 
			e.printStackTrace(); 
			return null; 
		}catch (InvalidKeyException e) { 
			throw new Exception("加密公钥非法,请检查"); 
		} catch (IllegalBlockSizeException e) { 
			throw new Exception("明文长度非法"); 
		} catch (BadPaddingException e) { 
			throw new Exception("明文数据已损坏"); 
		} 
	} 
	 
	/** 
	 * 加密过程 
	 * @param publicKey 公钥 
	 * @param plainTextData 明文数据 
	 * @return 
	 * @throws Exception 加密过程中的异常信息 
	 */ 
	public String encrypt(String ENSTR) throws Exception{ 
		 
		byte[]  plainTextData=ENSTR.getBytes(); 
		if(publicKey== null){ 
			throw new Exception("加密公钥为空, 请设置"); 
		} 
		Cipher cipher= null; 
		try { 
			cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 
			cipher.init(Cipher.ENCRYPT_MODE, publicKey); 
			byte[] output= cipher.doFinal(plainTextData); 
			BASE64Encoder encoder = new BASE64Encoder(); 
			return encoder.encode(output); 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此加密算法"); 
		} catch (NoSuchPaddingException e) { 
			e.printStackTrace(); 
			return null; 
		}catch (InvalidKeyException e) { 
			throw new Exception("加密公钥非法,请检查"); 
		} catch (IllegalBlockSizeException e) { 
			throw new Exception("明文长度非法"); 
		} catch (BadPaddingException e) { 
			throw new Exception("明文数据已损坏"); 
		} 
	} 
	 
	 
	 
 
	/** 
	 * 解密过程 
	 * @param privateKey 私钥 
	 * @param cipherData 密文数据 
	 * @return 明文 
	 * @throws Exception 解密过程中的异常信息 
	 */ 
	public byte[]  decrypt(byte[] cipherData) throws Exception{ 
		if (privateKey== null){ 
			throw new Exception("解密私钥为空, 请设置"); 
		} 
		Cipher cipher= null; 
		try { 
			cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 
			cipher.init(Cipher.DECRYPT_MODE, privateKey); 
			byte[] output= cipher.doFinal(cipherData); 
			return output; 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此解密算法"); 
		} catch (NoSuchPaddingException e) { 
			e.printStackTrace(); 
			return null; 
		}catch (InvalidKeyException e) { 
			throw new Exception("解密私钥非法,请检查"); 
		} catch (IllegalBlockSizeException e) { 
			throw new Exception("密文长度非法"); 
		} catch (BadPaddingException e) { 
			throw new Exception("密文数据已损坏"); 
		}		 
	} 
	 
 
	/** 
	 * 解密过程 
	 * @param privateKey 私钥 
	 * @param cipherData 密文数据 
	 * @return 明文 
	 * @throws Exception 解密过程中的异常信息 
	 */ 
	public String decrypt(String DEStr) throws Exception{ 
		BASE64Decoder decoder = new BASE64Decoder(); 
		byte[] cipherData=decoder.decodeBuffer(DEStr); 
		if (privateKey== null){ 
			throw new Exception("解密私钥为空, 请设置"); 
		} 
		Cipher cipher= null; 
		try { 
			cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 
			cipher.init(Cipher.DECRYPT_MODE, privateKey); 
			byte[] output= cipher.doFinal(cipherData); 
			return new String (output); 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此解密算法"); 
		} catch (NoSuchPaddingException e) { 
			e.printStackTrace(); 
			return null; 
		}catch (InvalidKeyException e) { 
			throw new Exception("解密私钥非法,请检查"); 
		} catch (IllegalBlockSizeException e) { 
			throw new Exception("密文长度非法"); 
		} catch (BadPaddingException e) { 
			throw new Exception("密文数据已损坏"); 
		}		 
	} 
 
	 
	/** 
	 * 字节数据转十六进制字符串 
	 * @param data 输入数据 
	 * @return 十六进制内容 
	 */ 
	public static String byteArrayToString(byte[] data){ 
		StringBuilder stringBuilder= new StringBuilder(); 
		for (int i=0; i<data.length; i++){ 
			//取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移 
			stringBuilder.append(HEX_CHAR[(data[i] & 0xf0)>>> 4]); 
			//取出字节的低四位 作为索引得到相应的十六进制标识符 
			stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]); 
			if (i<data.length-1){ 
				stringBuilder.append(' '); 
			} 
		} 
		return stringBuilder.toString(); 
	} 
	 
	/** 
	 *  
	 * @param path 
	 * @return 
	 */ 
	  public static InputStream getPathStream(String path) { 
		  	InputStream inputStream = null; 
	         try { 
	             inputStream = RSAUtil.class.getClassLoader().getResourceAsStream(path); 
	         } catch (Exception e) { 
	             e.printStackTrace(); 
	         } 
	         return inputStream; 
	 } 
	   
	public static void main(String[] args){ 
		RSAUtil rsaEncrypt= new RSAUtil(); 
		 
 
		//测试字符串 
		String encryptStr= "我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我"; 
		 
		 
		System.out.println(DEFAULT_PUBLIC_KEY1.length()); 
		System.out.println(encryptStr.getBytes().length); 
 
		try { 
			//加密 
			String cipher = rsaEncrypt.encrypt(encryptStr); 
			 
			String plainText = rsaEncrypt.decrypt(cipher); 
			System.out.println("密文长度:"+ cipher.getBytes().length); 
			System.out.println((cipher)); 
			System.out.println("明文长度:"+ plainText.getBytes().length); 
			 
			System.out.println(plainText); 
			 
		} catch (Exception e) { 
			System.err.println(e.getMessage()); 
		} 
	} 
}


版本3  分段加密 117  分段解密 128 


http://zhuyuehua.iteye.com/blog/1112722

import java.io.BufferedReader; 
import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.security.InvalidKeyException; 
import java.security.KeyFactory; 
import java.security.KeyPair; 
import java.security.KeyPairGenerator; 
import java.security.NoSuchAlgorithmException; 
import java.security.SecureRandom; 
import java.security.interfaces.RSAPrivateKey; 
import java.security.interfaces.RSAPublicKey; 
import java.security.spec.InvalidKeySpecException; 
import java.security.spec.PKCS8EncodedKeySpec; 
import java.security.spec.X509EncodedKeySpec; 
 
import javax.crypto.BadPaddingException; 
import javax.crypto.Cipher; 
import javax.crypto.IllegalBlockSizeException; 
import javax.crypto.NoSuchPaddingException; 
 
import org.bouncycastle.jce.provider.BouncyCastleProvider; 
 
import sun.misc.BASE64Decoder; 
import sun.misc.BASE64Encoder; 
 
 
public class RSAUtil { 
	/** 
	 * 私钥 
	 */ 
	private static  RSAPrivateKey privateKey; 
 
	/** 
	 * 公钥 
	 */ 
	private static  RSAPublicKey publicKey; 
	 
	/** 
	 * 字节数据转字符串专用集合 
	 */ 
	private static final char[] HEX_CHAR= {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 
	 
 
	static  
	{ 
		loadPublicKey(getPathStream("config//public_key.pem")); 
		loadPrivateKey(getPathStream("config//private_key.pem")); 
	} 
 
 
	public static String base64Encoder(String str){ 
		 
		 BASE64Encoder encode = new BASE64Encoder(); 
		 return encode.encode(str.getBytes()); 
		  
	} 
 
	public static String base64Decoder(String str){ 
		 
		 BASE64Decoder decode=new BASE64Decoder(); 
		 String result=""; 
		  
		 byte[] b; 
			try { 
				b = decode.decodeBuffer(str); 
				result=new String(b); 
				 
			} catch (IOException e) { 
				e.printStackTrace(); 
			} 
		 
			return result; 
		  
	} 
 
	/** 
	 * 随机生成密钥对 
	 */ 
	public void genKeyPair(){ 
		KeyPairGenerator keyPairGen= null; 
		try { 
			keyPairGen= KeyPairGenerator.getInstance("RSA"); 
		} catch (NoSuchAlgorithmException e) { 
			e.printStackTrace(); 
		} 
		keyPairGen.initialize(1024, new SecureRandom()); 
		KeyPair keyPair= keyPairGen.generateKeyPair(); 
		this.privateKey= (RSAPrivateKey) keyPair.getPrivate(); 
		this.publicKey= (RSAPublicKey) keyPair.getPublic(); 
	} 
 
	/** 
	 * 从文件中输入流中加载公钥 
	 * @param in 公钥输入流 
	 * @throws Exception 加载公钥时产生的异常 
	 */ 
	public static void loadPublicKey(InputStream in) { 
		try { 
			BufferedReader br= new BufferedReader(new InputStreamReader(in)); 
			String readLine= null; 
			StringBuilder sb= new StringBuilder(); 
			while((readLine= br.readLine())!=null){ 
				if(readLine.charAt(0)=='-'){ 
					continue; 
				}else{ 
					sb.append(readLine); 
					sb.append('\r'); 
				} 
			} 
			loadPublicKey(sb.toString()); 
		} catch (Exception e) { 
			System.err.println("加载公钥失败"); 
			 
		}  
	} 
 
 
	/** 
	 * 从字符串中加载公钥 
	 * @param publicKeyStr 公钥数据字符串 
	 * @throws Exception 加载公钥时产生的异常 
	 */ 
	public static void loadPublicKey(String publicKeyStr) throws Exception{ 
		try { 
			BASE64Decoder base64Decoder= new BASE64Decoder(); 
			byte[] buffer= base64Decoder.decodeBuffer(publicKeyStr); 
			KeyFactory keyFactory= KeyFactory.getInstance("RSA"); 
			X509EncodedKeySpec keySpec= new X509EncodedKeySpec(buffer); 
			publicKey= (RSAPublicKey) keyFactory.generatePublic(keySpec); 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此算法"); 
		} catch (InvalidKeySpecException e) { 
			throw new Exception("公钥非法"); 
		} catch (IOException e) { 
			throw new Exception("公钥数据内容读取错误"); 
		} catch (NullPointerException e) { 
			throw new Exception("公钥数据为空"); 
		} 
	} 
 
	/** 
	 * 从文件中加载私钥 
	 * @param keyFileName 私钥文件名 
	 * @return 是否成功 
	 * @throws Exception  
	 */ 
	public static void loadPrivateKey(InputStream in){ 
		try { 
			BufferedReader br= new BufferedReader(new InputStreamReader(in)); 
			String readLine= null; 
			StringBuilder sb= new StringBuilder(); 
			while((readLine= br.readLine())!=null){ 
				if(readLine.charAt(0)=='-'){ 
					continue; 
				}else{ 
					sb.append(readLine); 
					sb.append('\r'); 
				} 
			} 
			loadPrivateKey(sb.toString()); 
		} catch (Exception e) { 
			System.err.println("加载私钥失败"); 
			 
		}  
	} 
 
	public static void loadPrivateKey(String privateKeyStr) throws Exception{ 
		try { 
			BASE64Decoder base64Decoder= new BASE64Decoder(); 
			byte[] buffer= base64Decoder.decodeBuffer(privateKeyStr); 
			PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(buffer); 
			KeyFactory keyFactory= KeyFactory.getInstance("RSA"); 
			privateKey= (RSAPrivateKey) keyFactory.generatePrivate(keySpec); 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此算法"); 
		} catch (InvalidKeySpecException e) { 
			throw new Exception("私钥非法"); 
		} catch (IOException e) { 
			throw new Exception("私钥数据内容读取错误"); 
		} catch (NullPointerException e) { 
			throw new Exception("私钥数据为空"); 
		} 
	} 
 
	/** 
	 * 加密过程 
	 * @param publicKey 公钥 
	 * @param plainTextData 明文数据 
	 * @return 
	 * @throws Exception 加密过程中的异常信息 
	 */ 
	public byte[] encrypt(byte[] plainTextData) throws Exception{ 
		 
		if(publicKey== null){ 
			throw new Exception("加密公钥为空, 请设置"); 
		} 
		Cipher cipher= null; 
		try { 
			cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 
			cipher.init(Cipher.ENCRYPT_MODE, publicKey); 
			byte[] output= cipher.doFinal(plainTextData); 
			return output; 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此加密算法"); 
		} catch (NoSuchPaddingException e) { 
			e.printStackTrace(); 
			return null; 
		}catch (InvalidKeyException e) { 
			throw new Exception("加密公钥非法,请检查"); 
		} catch (IllegalBlockSizeException e) { 
			throw new Exception("明文长度非法"); 
		} catch (BadPaddingException e) { 
			throw new Exception("明文数据已损坏"); 
		} 
	} 
	 
	 
	 
	/** 
	 * 加密过程 
	 * @param publicKey 公钥 
	 * @param plainTextData 明文数据 
	 * @return 
	 * @throws Exception 加密过程中的异常信息 
	 */ 
	public String encrypt(String ENSTR) throws Exception{ 
		 
		byte[]  data=ENSTR.getBytes(); 
      
		if(publicKey== null){ 
			throw new Exception("加密公钥为空, 请设置"); 
		} 
		Cipher cipher= null; 
		try { 
			 
			cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 
			cipher.init(Cipher.ENCRYPT_MODE, publicKey); 
	        int inputLen = data.length; 
	        int offSet=0; 
	        ByteArrayOutputStream out = new ByteArrayOutputStream();     
			int i = 0; 
			byte[] cache; 
	        while (inputLen - offSet > 0)  
	        { 
	            if (inputLen - offSet > 117) 
	                cache = cipher.doFinal(data, offSet, 117); 
	            else  
	            { 
	                cache = cipher.doFinal(data, offSet, inputLen - offSet); 
	            } 
	            out.write(cache, 0, cache.length); 
	            i++; 
	            offSet = i * 117; 
	         } 
	         
	        byte[] encryptedData = out.toByteArray(); 
	        out.close(); 
		         
			BASE64Encoder encoder = new BASE64Encoder(); 
			return encoder.encode(encryptedData); 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此加密算法"); 
		} catch (NoSuchPaddingException e) { 
			e.printStackTrace(); 
			return null; 
		}catch (InvalidKeyException e) { 
			throw new Exception("加密公钥非法,请检查"); 
		} catch (IllegalBlockSizeException e) { 
			throw new Exception("明文长度非法"); 
		} catch (BadPaddingException e) { 
			throw new Exception("明文数据已损坏"); 
		} 
	} 
	 
	 
	 
	 
	 
 
	/** 
	 * 解密过程 
	 * @param privateKey 私钥 
	 * @param cipherData 密文数据 
	 * @return 明文 
	 * @throws Exception 解密过程中的异常信息 
	 */ 
	public byte[]  decrypt(byte[] cipherData) throws Exception{ 
		if (privateKey== null){ 
			throw new Exception("解密私钥为空, 请设置"); 
		} 
		Cipher cipher= null; 
		try { 
			cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 
			cipher.init(Cipher.DECRYPT_MODE, privateKey); 
			byte[] output= cipher.doFinal(cipherData); 
			return output; 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此解密算法"); 
		} catch (NoSuchPaddingException e) { 
			e.printStackTrace(); 
			return null; 
		}catch (InvalidKeyException e) { 
			throw new Exception("解密私钥非法,请检查"); 
		} catch (IllegalBlockSizeException e) { 
			throw new Exception("密文长度非法"); 
		} catch (BadPaddingException e) { 
			throw new Exception("密文数据已损坏"); 
		}		 
	} 
	 
	 
	 
 
	 
	 
	/** 
	 * 解密过程 
	 * @param privateKey 私钥 
	 * @param cipherData 密文数据 
	 * @return 明文 
	 * @throws Exception 解密过程中的异常信息 
	 */ 
	public String decrypt(String DEStr) throws Exception{ 
		BASE64Decoder decoder = new BASE64Decoder(); 
		byte[] encryptedData=decoder.decodeBuffer(DEStr); 
		if (privateKey== null){ 
			throw new Exception("解密私钥为空, 请设置"); 
		} 
		Cipher cipher= null; 
		try { 
			 
			cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 
			cipher.init(Cipher.DECRYPT_MODE, privateKey); 
		    int inputLen = encryptedData.length; 
	        ByteArrayOutputStream out = new ByteArrayOutputStream(); 
	        int offSet = 0; 
	        int i = 0; 
	        byte[] cache; 
	        while (inputLen - offSet > 0)  
	        { 
	            if (inputLen - offSet > 128) 
	                cache = cipher.doFinal(encryptedData, offSet, 128); 
	            else 
	            { 
	                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); 
	            } 
	            out.write(cache, 0, cache.length); 
	            i++; 
	            offSet = i * 128; 
	        } 
	        byte[] decryptedData = out.toByteArray(); 
	        out.close(); 
			return new String(decryptedData); 
		} catch (NoSuchAlgorithmException e) { 
			throw new Exception("无此解密算法"); 
		} catch (NoSuchPaddingException e) { 
			e.printStackTrace(); 
			return null; 
		}catch (InvalidKeyException e) { 
			throw new Exception("解密私钥非法,请检查"); 
		} catch (IllegalBlockSizeException e) { 
			throw new Exception("密文长度非法"); 
		} catch (BadPaddingException e) { 
			throw new Exception("密文数据已损坏"); 
		}		 
	} 
	 
 
	 
	/** 
	 * 字节数据转十六进制字符串 
	 * @param data 输入数据 
	 * @return 十六进制内容 
	 */ 
	public static String byteArrayToString(byte[] data){ 
		StringBuilder stringBuilder= new StringBuilder(); 
		for (int i=0; i<data.length; i++){ 
			//取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移 
			stringBuilder.append(HEX_CHAR[(data[i] & 0xf0)>>> 4]); 
			//取出字节的低四位 作为索引得到相应的十六进制标识符 
			stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]); 
			if (i<data.length-1){ 
				stringBuilder.append(' '); 
			} 
		} 
		return stringBuilder.toString(); 
	} 
	 
	/** 
	 *  
	 * @param path 
	 * @return 
	 */ 
	  public static InputStream getPathStream(String path) { 
		  	InputStream inputStream = null; 
	         try { 
	             inputStream = RSAUtil.class.getClassLoader().getResourceAsStream(path); 
	         } catch (Exception e) { 
	             e.printStackTrace(); 
	         } 
	         return inputStream; 
	 } 
	   
	public static void main(String[] args){ 
		RSAUtil rsaEncrypt= new RSAUtil(); 
		 
 
		//测试字符串 
		String encryptStr= "我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我我"; 
 
		try { 
			//加密 
			String cipher = rsaEncrypt.encrypt(encryptStr); 
			 
			String plainText = rsaEncrypt.decrypt(cipher); 
			System.out.println("密文长度:"+ cipher.getBytes().length); 
			System.out.println((cipher)); 
			System.out.println("明文长度:"+ plainText.getBytes().length); 
			 
			System.out.println(plainText); 
			 
		} catch (Exception e) { 
			System.err.println(e.getMessage()); 
		} 
	} 
} 



发布评论
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

Spring +Mybatis 拦截器配置知识解答
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。