RSA加解密之解决117字节加密和126字节解密问题


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.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

/**
* @author lyx
* @version 创建时间:2019年3月17日 下午5:27:48
* 类说明
*/
public class RSAEncrypt {
	private static Map<Integer, String> keyMap = new HashMap<Integer, String>();  //用于封装随机产生的公钥与私钥
	public static void main(String[] args) throws Exception {
		//生成公钥和私钥
		genKeyPair();
		//加密字符串
		String message = "<request><branchCode></branchCode><orderMode>0</orderMode><startTime>2019-03-17</startTime><endTime>2019-03-17</endTime><regMode>0</regMode><orderNo></orderNo></request>";
		String  publicKey = keyMap.get("publicKey");
        publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6v5CO6av98q5CFxOh7wckytdtijoYb34VNEr3ZQ2I6LrUbhatCfUzqOFSc+VTDt6+soG9w29UI8SckfaFkw7+ee09e1voCu03XOwecck1JFePsbtZe/swJdZvi/fGfLICT4IwslGCx8ndg1Y3Oj2Z0zK7NyQht7UHdOG1y5ObdwIDAQAB";
        String  privateKey = keyMap.get("privateKey");
        privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALq/kI7pq/3yrkIXE6HvByTK122KOhhvfhU0SvdlDYjoutRuFq0J9TOo4VJz5VMO3r6ygb3Db1QjxJyR9oWTDv557T17W+gK7Tdc7B5xyTUkV4+xu1l7+zAl1m+L98Z8sgJPgjCyUYLHyd2DVjc6PZnTMrs3JCG3tQd04bXLk5t3AgMBAAECgYEAluPb0K1by8e/JyVwNoJk2kSPBjIOuNm1HTrwa66Z3gp1ktkUt2H5XnFRBgcgvxifv6OKEyMLHAf+f6escccd7/m33tFIfxsZcoPBi+NCFYPxJFLVu+qpnRKarZSUcPOAz0VI6rDPL732KqzPzGWYzButQrDUJHpwpsCVsI/CJykCQQD4H205OlwHms0OkywvZggP6vahibqMWgHb7vpzFpb8xtbILBFJhcQq5IJfItE5ZjSHrhiOq4+P2KUvSF1X1bIrAkEAwK1T/MTwzxUvA9pLYQYLvHybwFevElVwu5BZU6NDVLqEV6S2SPYhbwWjN/2nDxUzd/WsXsA4oMj1QNg2W3Mx5QJBAMSVgaAZ0NhlmZm2mQdku3aBHq6VxKt2lIqAKQYOG8pib8FgyMGLrgSdz304xLPJek0Vbnd7Dd9WMmnn16zDrskCQA8rlnlIaE1ltZXwEg9JkpL8nKbAQKCI6Z9a9i2HpT1+kfz0kwWbm3ZKU1eNOSIO4UaIqVGsgMjoCadZXq5Em6ECQHjkhuD69BGTo9W8rI8+f9Kmn/RBnBHaUGbfkrWsbliye4ajyZ1fQ8MIG5wHwkwK1T9ulSE4i7rIy7yV/b1Kqek=";
		System.out.println("随机生成的公钥为:" + publicKey);
		System.out.println("随机生成的私钥为:" + privateKey);
		String messageEn = encrypt(message,publicKey);
		messageEn = "oj03ZFjyji5vfZ07mplVw4oS2GD19OhLo8F+MmojwW7Hlzi52wUL9j3TYOJ3LGKgmXyZ27AywbXW7Pzx59S/9DAm/69KefczvnTRVlEUVqW9e9nwRM60ZArFHiPJgLxyeQy89eNUKQkwFEGbLodfRaePc3mrbl6eEZjJElqth7c=";
		System.out.println(message + "\t加密后的字符串为:" + messageEn);
		String messageDe = decrypt(messageEn,privateKey);
		System.out.println("还原后的字符串为:" + messageDe);
		String result = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + 
				"   <soap:Body>\r\n" + 
				"      <ns1:getOrderRecordsResponse xmlns:ns1=\"http://service.ws.bsoft.com\">\r\n" + 
				"         <ns1:out>h/g1nnPx6iMNA5AnTF8SMW0z+2n2UqsPGjelKmnMWi8zO+00eqpbOXRHMVQiGeMX4kjhwEdjDxVJ9ZFuChcl1KijeIYLabEUWXPJbIWmtz47uQAC5EUwIEHcI5yeu90YsZdrK+GpwQFHZTCoVnEtbifB+arAXL4XV67gf2S1V+w=</ns1:out>\r\n" + 
				"      </ns1:getOrderRecordsResponse>\r\n" + 
				"   </soap:Body>\r\n" + 
				"</soap:Envelope>";
		result = result.substring(result.indexOf("<ns1:out>")+9, result.indexOf("</ns1:out>"));
		System.out.println(result);
		result = RSAEncrypt.decrypt(result, privateKey);
		result = result.replaceAll("&lt;", "<");
		result = result.replaceAll("&gt;", ">");
		System.out.println("返回参数:" + result);
	}

	/** 
	 * 随机生成密钥对 
	 * @throws NoSuchAlgorithmException 
	 */  
	public static void genKeyPair() throws NoSuchAlgorithmException {  
		// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象  
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");  
		// 初始化密钥对生成器,密钥大小为96-1024位  
		keyPairGen.initialize(1024,new SecureRandom());  
		// 生成一个密钥对,保存在keyPair中  
		KeyPair keyPair = keyPairGen.generateKeyPair();  
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥  
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥  
		String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));  
		// 得到私钥字符串  
		String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));  
		// 将公钥和私钥保存到Map
		keyMap.put(0,publicKeyString);  //0表示公钥
		keyMap.put(1,privateKeyString);  //1表示私钥
	}  
	/** 
	 * RSA公钥加密 
	 *  
	 * @param str 
	 *            加密字符串
	 * @param publicKey 
	 *            公钥 
	 * @return 密文 
	 * @throws Exception 
	 *             加密过程中的异常信息 
	 */  
	public static String encrypt( String str, String publicKey ) throws Exception{
		//base64编码的公钥
		byte[] decoded = Base64.decodeBase64(publicKey);
		RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
		//RSA加密
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);
//		String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
		String outStr = null;
		byte[] inputArray = str.getBytes("UTF-8");
		int inputLength = inputArray.length;
		System.out.println("加密字节数:" + inputLength);
		// 最大加密字节数,超出最大字节数需要分组加密
		int MAX_ENCRYPT_BLOCK = 117;
		// 标识
		int offSet = 0;
		byte[] resultBytes = {};
		byte[] cache = {};
		while (inputLength - offSet > 0) {
			if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
				offSet += MAX_ENCRYPT_BLOCK;
			} else {
				cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
				offSet = inputLength;
			}
			resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
			System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
		}
		outStr = Base64.encodeBase64String(resultBytes);
		return outStr;
	}

	/** 
	 * RSA私钥解密
	 *  
	 * @param str 
	 *            加密字符串
	 * @param privateKey 
	 *            私钥 
	 * @return 铭文
	 * @throws Exception 
	 *             解密过程中的异常信息 
	 */  
	public static String decrypt(String str, String privateKey) throws Exception{
		//64位解码加密后的字符串
		byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
		//base64编码的私钥
		byte[] decoded = Base64.decodeBase64(privateKey);  
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));  
		//RSA解密
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, priKey);
//		String outStr = new String(cipher.doFinal(inputByte));
		String outStr = null;
		byte[] inputArray = Base64.decodeBase64(str.getBytes("UTF-8"));
		int inputLength = inputArray.length;
		System.out.println("加密字节数:" + inputLength);
		// 最大加密字节数,超出最大字节数需要分组加密
		int MAX_ENCRYPT_BLOCK = 128;
		// 标识
		int offSet = 0;
		byte[] resultBytes = {};
		byte[] cache = {};
		while (inputLength - offSet > 0) {
			if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
				offSet += MAX_ENCRYPT_BLOCK;
			} else {
				cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
				offSet = inputLength;
			}
			resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
			System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
		}
		outStr = new String(resultBytes);
		return outStr;
	}

}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是Java语言实现RSA加密解密程序的代码: ```java import java.math.BigInteger; import java.security.SecureRandom; public class RSA { private BigInteger n, d, e; public RSA(int bitlen) { SecureRandom r = new SecureRandom(); BigInteger p = new BigInteger(bitlen / 2, 100, r); BigInteger q = new BigInteger(bitlen / 2, 100, r); n = p.multiply(q); BigInteger m = (p.subtract(BigInteger.ONE)) .multiply(q.subtract(BigInteger.ONE)); e = new BigInteger("3"); while (m.gcd(e).intValue() > 1) { e = e.add(new BigInteger("2")); } d = e.modInverse(m); } public BigInteger encrypt(BigInteger message) { return message.modPow(e, n); } public BigInteger decrypt(BigInteger message) { return message.modPow(d, n); } public static void main(String[] args) { RSA rsa = new RSA(1024); BigInteger message = new BigInteger("123456789"); BigInteger encrypted = rsa.encrypt(message); BigInteger decrypted = rsa.decrypt(encrypted); System.out.println("Original message: " + message); System.out.println("Encrypted message: " + encrypted); System.out.println("Decrypted message: " + decrypted); } } ``` 该程序使用了Java的BigInteger类来处理大数运算。在构造函数中,随机生成两个大素数p和q,并计算n和m。然后选择一个小于m的整数e作为加密密钥,计算d作为解密密钥。encrypt和decrypt方法分别实现了RSA加密解密算法。在main方法中,使用生成的密钥对一个数字进行加密解密,并输出结果。 要使用该程序对文本进行加密解密,可以将文本转换为BigInteger类型,然后调用encrypt和decrypt方法。以下是一个简单的示例: ```java import java.math.BigInteger; public class RSAExample { public static void main(String[] args) { RSA rsa = new RSA(1024); String message = "Hello, world!"; BigInteger plaintext = new BigInteger(message.getBytes()); BigInteger encrypted = rsa.encrypt(plaintext); BigInteger decrypted = rsa.decrypt(encrypted); System.out.println("Original message: " + message); System.out.println("Encrypted message: " + encrypted); System.out.println("Decrypted message: " + new String(decrypted.toByteArray())); } } ``` 该程序将字符串"Hello, world!"转换为字节数组,然后将其转换为BigInteger类型并加密解密后再将结果转换为字节数组,最终转换为字符串输出。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值