RSA加密解密

RSA加密解密代码

代码有待整理

package com.tongbanjie.commons.util;


import java.security.Key;

import java.security.KeyFactory;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.PrivateKey;

import java.security.interfaces.RSAPrivateKey;

import java.security.interfaces.RSAPublicKey;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.RSAPrivateKeySpec;

import java.security.spec.X509EncodedKeySpec;

import java.util.HashMap;

import java.util.Map;


import javax.crypto.Cipher;


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

import org.bouncycastle.asn1.ASN1Sequence;

import org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure;



/**

* RSA+Base64加密解密工具类

* RSA 一般用在数据传输过程中的加密和解密 先用RSA加密后是字节数组 再用BASE64加密 成字符串进行传输

* 测试 RSA1024产生的公钥字节长度在160-170之间 私钥长度在630-640之间

* 经过base64加密后长度 公钥字节产度在210-220之间 私钥长度在840-850之间

* 所以数据库设计时如果存公钥长度设计varchar(256) 私钥长度varchar(1024)

* @author huang.qun

*/

public abstract class TbjRSAUtil {

public static final String KEY_ALGORITHM = "RSA";



private static final String PUBLIC_KEY = "rsa_public_key";

private static final String PRIVATE_KEY = "rsa_private_key";



private static final String ENCODING = "UTF-8";





/**

* 加密

* 用公钥加密

* @param content

* @param base64PublicKeyStr

* @return

* @throws Exception

*/

public static String encryptByPublicKey(String content, String base64PublicKeyStr)

throws Exception {

byte[] inputBytes = content.getBytes(ENCODING);

byte[] outputBytes = encryptByPublicKey(inputBytes, base64PublicKeyStr);

return Base64.encodeBase64String(outputBytes);

}



/**

* 加密

* 用私钥加密

* @param content

* @param base64PrivateKeyStr

* @return

* @throws Exception

*/

public static String encryptByPrivateKey(String content, String base64PrivateKeyStr)

throws Exception {

byte[] inputBytes = content.getBytes(ENCODING);

byte[] outputBytes = encryptByPrivateKey(inputBytes, base64PrivateKeyStr);

return Base64.encodeBase64String(outputBytes);

}



/**

* 解密

* 用公钥解密

* @param content

* @param base64PublicKeyStr

* @return

* @throws Exception

*/

public static String decryptByPublicKey(String content, String base64PublicKeyStr)

throws Exception {

byte[] inputBytes = Base64.decodeBase64(content);

byte[] outputBytes = decryptByPublicKey(inputBytes, base64PublicKeyStr);

return new String(outputBytes, ENCODING);

}



/**

* 解密

* 用私钥解密

* @param content

* @param privateKeyStr

* @return

* @throws Exception

*/

public static String decryptByPrivateKey(String content, String base64PrivateKeyStr)

throws Exception {

byte[] inputBytes = Base64.decodeBase64(content);

byte[] outputBytes = decryptByPrivateKey(inputBytes, base64PrivateKeyStr);

return new String(outputBytes, ENCODING);

}







/**

* 加密

* 用公钥加密

* @param content

* @param base64PublicKeyStr

* @return

* @throws Exception

*/

public static byte[] encryptByPublicKey(byte[] content, String base64PublicKeyStr)

throws Exception {

// 对公钥解密

byte[] publicKeyBytes = Base64.decodeBase64(base64PublicKeyStr);



// 取得公钥

X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

Key publicKey = keyFactory.generatePublic(x509KeySpec);



// 对数据加密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.ENCRYPT_MODE, publicKey);



return cipher.doFinal(content);

}



/**

* 加密

* 用私钥加密

* @param content

* @param base64PrivateKeyStr

* @return

* @throws Exception

*/

public static byte[] encryptByPrivateKey(byte[] content, String base64PrivateKeyStr)

throws Exception {

// 对密钥解密

byte[] privateKeyBytes = Base64.decodeBase64(base64PrivateKeyStr);



// 取得私钥

PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);



// 对数据加密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.ENCRYPT_MODE, privateKey);



return cipher.doFinal(content);

}



/**

* 解密

* 用公钥解密

* @param content

* @param base64PublicKeyStr

* @return

* @throws Exception

*/

public static byte[] decryptByPublicKey(byte[] content, String base64PublicKeyStr)

throws Exception {

// 对密钥解密

byte[] publicKeyBytes = Base64.decodeBase64(base64PublicKeyStr);



// 取得公钥

X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

Key publicKey = keyFactory.generatePublic(x509KeySpec);



// 对数据解密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.DECRYPT_MODE, publicKey);



return cipher.doFinal(content);

}



/**

* 解密

* 用私钥解密

* @param content

* @param privateKeyStr

* @return

* @throws Exception

*/

public static byte[] decryptByPrivateKey(byte[] content, String base64PrivateKeyStr)

throws Exception {







// 对密钥解密

byte[] privateKeyBytes = Base64.decodeBase64(base64PrivateKeyStr);



RSAPrivateKeyStructure asn1PrivKey = new RSAPrivateKeyStructure((ASN1Sequence) ASN1Sequence.fromByteArray(privateKeyBytes));

RSAPrivateKeySpec rsaPrivKeySpec = new RSAPrivateKeySpec(asn1PrivKey.getModulus(), asn1PrivKey.getPrivateExponent());

KeyFactory keyFactory= KeyFactory.getInstance("RSA");

PrivateKey priKey= keyFactory.generatePrivate(rsaPrivKeySpec);



// 取得私钥

// PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);

// KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

// Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);



// 对数据解密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.DECRYPT_MODE, priKey);



return cipher.doFinal(content);

}





/**

* 取得私钥

* @param keyMap

* @return

* @throws Exception

*/

public static String getBase64PrivateKeyStr(Map keyMap)

throws Exception {

Key key = (Key) keyMap.get(PRIVATE_KEY);

return Base64.encodeBase64String(key.getEncoded());

}



/**

* 取得公钥

* @param keyMap

* @return

* @throws Exception

*/

public static String getBase64PublicKeyStr(Map keyMap)

throws Exception {

Key key = (Key) keyMap.get(PUBLIC_KEY);

return Base64.encodeBase64String(key.getEncoded());

}



/**

* 初始化密钥

* @return

* @throws Exception

*/

public static Map initKey() throws Exception {

KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);

keyPairGen.initialize(1024); //初始化RSA1024安全些



KeyPair keyPair = keyPairGen.generateKeyPair();

RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 公钥

RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 私钥



Map keyMap = new HashMap(2);

keyMap.put(PUBLIC_KEY, publicKey);

keyMap.put(PRIVATE_KEY, privateKey);

return keyMap;

}



private static void test() throws Exception {

String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0Y9rmhe4fIsFrrm0m/jrbfZsq"

+ "xMYvg8qdvbSGHC9vnYm4K5p3bFBqqULAFlv2ZGjrWDFcBfa562E5hXtAoACXtsDH"

+ "8WCkhfNiPkGQn3wNDGRpfYVup/F1LdceunSu0IYDP0MACzKY1S7KM2qJi8P8YlXZ"

+ "91oyRfgb8lgqdQoXmQIDAQAB";

String str = "123456";

String content = encryptByPublicKey(str, pubKey);

System.out.println(content);



String priKey = "MIICXAIBAAKBgQC0Y9rmhe4fIsFrrm0m/jrbfZsqxMYvg8qdvbSGHC9vnYm4K5p3bFBqqULAFlv2ZGjrWDFcBfa562E5hXtAoACXtsDH8WCkhfNiPkGQn3wNDGRpfYVup/F1LdceunSu0IYDP0MACzKY1S7KM2qJi8P8YlXZ91oyRfgb8lgqdQoXmQIDAQABAoGAIG90BM9AKckODlamucQswRqss9v95r1DyWk69IJM5Tzmbn8onyCStRsKLY/XqU4Ur3yEI4/O9U8lhDpEFzKt6ExkITkiVcVlRuK0lkAKS4Uu4W+YoPzNLwKoL3dS1my+wPOxgswJ+QPSrYfWoGDoDNiZctskcHprplkECYI9/aECQQDXvkZl9IHXRolUCQWfS5MFWVgPwaXNP3X3gXaqdfhoopIPsZphurd+hxDWforh+KNkdRejbbwIveGTxkXqxTe3AkEA1gzPz9IAzFPx8RjkOxgRag3g+Rp+35nuLw18Rt04EODinurCsg3t5k2rOx2Fic6GVozqM3B3p4ATr4GsyhALLwJAFi8vp/47d7p+FpES7e1kgdFNF9muxes3oyrB3Adjcsb8w/ZcTJ5Zjf4vgg7jExdxHbxYoOqAwllcH8jsmZaMAwJAXdJjzF3qR6WL6PfWIijciTXoJIf+kJfyFOG+VXllt9A6xRl1mYINguMMaO75t3u02n8NsNpdOCgleMpIKJF7tQJBALsDYb59npdnKL2V0zk5bZ7Nd40dy4KbRcXIG2Ll/Lo6CeY/6Jes868R0yyuyLGP5CcayMKVAhcVk3xEWI7dluU=";

String output = decryptByPrivateKey(content, priKey);

System.out.println(output);

}



public static void main(String[] args) throws Exception {

test();

/*Map keyMap = initKey();

String base64PublicKeyStr = getBase64PublicKeyStr(keyMap);

String base64PrivateKeyStr = getBase64PrivateKeyStr(keyMap);

System.out.println("公钥:" + base64PublicKeyStr);

System.out.println("私钥:" + base64PrivateKeyStr);


System.out.println("===========公钥加密私钥解密====111111=========");

String inputStr = "黄sfsfj;kasjdkf群我们这个世界真是个好玩的世界";

byte[] content = encryptByPublicKey(inputStr.getBytes(ENCODING), base64PublicKeyStr);

String str = Base64.encodeBase64String(content);

System.out.println(str.length());

System.out.println("加密输出到前台的字符串" + str);

content = Base64.decodeBase64(str);

//解密用字节数组 content

byte[] outByte = decryptByPrivateKey(content, base64PrivateKeyStr);

String outputStr = new String(outByte, ENCODING);

System.out.println("公钥加密前:" + inputStr);

System.out.println("私钥加密后:" + outputStr);


System.out.println("=============私钥加密公钥解密====222222===============");

String input = "你好谁开个房间了睡觉爱国;刻录机skdfld";

byte[] data = encryptByPrivateKey(input.getBytes(ENCODING), base64PrivateKeyStr);

String aaa = Base64.encodeBase64String(data);

System.out.println("加密输出到前台的字符串" + aaa);

data = Base64.decodeBase64(aaa);

byte[] out = decryptByPublicKey(data, base64PublicKeyStr);

String outStr = new String(out, ENCODING);

System.out.println("私钥加密前:" + input);

System.out.println("公钥解密后:" + outStr);


System.out.println("=============公钥加密私钥解密====333333===============");

String inputStr3 = "黄sfsfj群我们这个世界真是个好玩的世界";

String middleStr3 = encryptByPublicKey(inputStr3, base64PublicKeyStr);

String outputStr3 = decryptByPrivateKey(middleStr3, base64PrivateKeyStr);

System.out.println("公钥加密前:" + inputStr3);

System.out.println("私钥加密后:" + middleStr3);

System.out.println("私钥加密后:" + outputStr3);


System.out.println("===========私钥加密公钥解密====4444444=========");

String inputStr4 = "黄sfsfj群我们这个世界真是个好玩的世界";

String middleStr4 = encryptByPrivateKey(inputStr4, base64PrivateKeyStr);

String outputStr4 = decryptByPublicKey(middleStr4, base64PublicKeyStr);

System.out.println("公钥加密前:" + inputStr4);

System.out.println("私钥加密后:" + middleStr4);

System.out.println("私钥加密后:" + outputStr4);*/

}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值