java class加密工具_Java 加密解密工具类
packagecom.chitic.supplywater.common.service;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.UnsupportedEncodingException;importjava.net.URLDecode
packagecom.chitic.supplywater.common.service;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.UnsupportedEncodingException;importjava.net.URLDecoder;importjava.net.URLEncoder;importjava.security.Key;importjava.security.KeyFactory;importjava.security.KeyPair;importjava.security.KeyPairGenerator;importjava.security.NoSuchAlgorithmException;importjava.security.PrivateKey;importjava.security.PublicKey;importjava.security.Signature;importjava.security.interfaces.RSAPrivateKey;importjava.security.interfaces.RSAPublicKey;importjava.security.spec.PKCS8EncodedKeySpec;importjava.security.spec.X509EncodedKeySpec;importjava.util.Arrays;importjavax.crypto.Cipher;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importsun.misc.BASE64Decoder;importsun.misc.BASE64Encoder;
@SuppressWarnings("restriction")public classRSACoder {private static final Logger logger = LoggerFactory.getLogger(RSACoder.class);/*** 加密方式*/
public static final String KEY_ALGORITHM = "RSA";/*** 签名方式*/
public static final String KEY_SIGN = "SHA1withRSA";/*** RSA最大加密明文大小*/
public static final int MAX_ENCRYPT_BLOCK = 117;/*** RSA最大解密密文大小*/
public static final int MAX_DECRYPT_BLOCK = 128;/*** RSA最大解密密文大小*/
public static final int MAX_DECRYPT_BLOCK_256 = 256;/** static { KeyPairGenerator keyPairGen = null; try { keyPairGen =
* KeyPairGenerator.getInstance(KEY_ALGORITHM); } catch
* (NoSuchAlgorithmException e) { logger.error("创建密钥失败", e); }
* keyPairGen.initialize(1024);
*
* KeyPair keyPair = keyPairGen.generateKeyPair(); // 公钥 RSAPublicKey
* publicKey = (RSAPublicKey) keyPair.getPublic(); PUBLIC_KEY =
* encryptBASE64(publicKey.getEncoded()); // 私钥 RSAPrivateKey privateKey =
* (RSAPrivateKey) keyPair.getPrivate(); PRIVATE_KEY =
* encryptBASE64(privateKey.getEncoded()); }*/
public static voidmain(String[] args) {
KeyPairGenerator keyPairGen= null;try{
keyPairGen=KeyPairGenerator.getInstance(KEY_ALGORITHM);
}catch(NoSuchAlgorithmException e) {
}
keyPairGen.initialize(1024);
KeyPair keyPair=keyPairGen.generateKeyPair();
RSAPublicKey publicKey=(RSAPublicKey) keyPair.getPublic();
System.out.println(RSACoder.encryptBASE64(publicKey.getEncoded()));
System.out.println("-----------------------------");
RSAPrivateKey privateKey=(RSAPrivateKey) keyPair.getPrivate();
System.out.println(RSACoder.encryptBASE64(privateKey.getEncoded()));
String pubKey= "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCPEaBoSSdHgK32dsM4H407pOmqSliYz6qh1m5i2ZHY1rF+0ze2VAXf4d+XU4kk2L5L1itHIdxMzMoxHI+F4ZGaeETQLluDJlRpcJL+ZTjEAI6CBNtmGFCTd1QB3AHco1txch04PzMpcjLIa6WzHrI65/bF0kCmo2mQNHLQ+W5hvwIDAQAB";
String priKey= "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAI8RoGhJJ0eArfZ2wzgfjTuk6apKWJjPqqHWbmLZkdjWsX7TN7ZUBd/h35dTiSTYvkvWK0ch3EzMyjEcj4XhkZp4RNAuW4MmVGlwkv5lOMQAjoIE22YYUJN3VAHcAdyjW3FyHTg/MylyMshrpbMesjrn9sXSQKajaZA0ctD5bmG/AgMBAAECgYBuKgR6SNoWFN/fiFOKQ8Fcy/+hQN43zLB3LcaSFzZW4fqKzdl4a/qaCjNBMvHHjZ36h0+L1mbsPET0zCk3zhluzSb+PqmpRfhX8jjEwAd3BB4qHVv2qg5BhDj7JpS7/+iKDztmeHLIAmWNCoI3/fyymuTVPcol46qoCeIjtJ26AQJBAOQQojEPWsTTA+G8E6Qya2B2btm9RkYYgtRwO4ZW/ZYhfYdJdVwYSO4fyALhYfbSBI6lqcL/tp/24n1hqNq3MvcCQQCgl8tsnkIc1IWlez6N/XaZKyh08teNXVfOlduaQQRIng/hYlelc9VeqzEwrzNym0x4CpMy+FsVYg+pDgDh1U15AkASVtwUAd4UsbtALbWOoJdN3HgxfizmehYbKyM+PESMDAliFaAgVbuXmmqlAKa2CFFhfyTVj2aKGnpABthjLhQlAkAMiAvNrAPIsCTFpvpYpiCtDxsXFSQQ2enSKwt52/zzlbHzinMAbCuIOZ+bBvDizo+HBnw6C/s/jele7cLP3I8xAkBFzb9eBxIFzmi7a1+shTXCoSfpsND4fvYbQrHpwzZ4+uLEderoao8JjetHIE4IhXagbfwXKRif27uq/mkEoeGO";try{
String jiami= RSACoder.encryptByPublicKey(pubKey, URLEncoder.encode("{\"sDate\":\"20160101\",\"eDate\":\"20181201\"}", "UTF-8"));//String params = RSACoder.encryptByPublicKey(pubKey,URLEncoder.encode("{\"contractNo\":\"4号\"}", "UTF-8"));//String params = RSACoder.encryptByPublicKey(pubKey,URLEncoder.encode("{\"projName\":\"新密\"}", "UTF-8"));
System.out.println("加密后的密文:" +jiami);
String jiemi= URLDecoder.decode(RSACoder.decryptByPrivateKey(priKey, jiami), "utf-8");
System.out.println("解密加密后的密文:" +jiemi);
}catch(UnsupportedEncodingException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}/*** 公钥加密
*
*@parampubKey
*@paramdata
*@return
*/
public staticString encryptByPublicKey(String pubKey, String data) {try{return encryptBASE64(encryptByPublicKey(pubKey, data.getBytes("utf-8")));
}catch(UnsupportedEncodingException e) {throw new RuntimeException("加密失败", e);
}
}/*** 公钥加密
*
*@parampubKey
*@paramdata
*@return
*/
public static byte[] encryptByPublicKey(String pubKey, byte[] data) {try{byte[] keyBytes =decryptBASE64(pubKey);
X509EncodedKeySpec x509KeySpec= newX509EncodedKeySpec(keyBytes);
KeyFactory keyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
Key key=keyFactory.generatePublic(x509KeySpec);
Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, key);int inputLen =data.length;
ByteArrayOutputStream out= newByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;//对数据分段加密
while (inputLen - offSet > 0) {if (inputLen - offSet >MAX_ENCRYPT_BLOCK) {
cache=cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
}else{
cache= cipher.doFinal(data, offSet, inputLen -offSet);
}
out.write(cache,0, cache.length);
i++;
offSet= i *MAX_ENCRYPT_BLOCK;
}returnout.toByteArray();
}catch(Exception e) {throw new RuntimeException("加密失败", e);
}
}/*** 私钥解密
*
*@parampubKey
*@paramdata
*@return
*/
public staticString decryptByPrivateKey(String priKey, String data) {try{return newString(decryptByPrivateKey(priKey, decryptBASE64(data)),"utf-8");
}catch(IOException e) {throw new RuntimeException("解密失败", e);
}
}/*** 私钥解密
*
*@paramprikey
*@paramdata
*@return
*/
public static byte[] decryptByPrivateKey(String priKey, byte[] data) {try{byte[] keyBytes =decryptBASE64(priKey);
PKCS8EncodedKeySpec pkcs8KeySpec= newPKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
Key key=keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, key);int inputLen =data.length;
ByteArrayOutputStream out= newByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;//对数据分段解密
while (inputLen - offSet > 0) {if (inputLen - offSet >MAX_DECRYPT_BLOCK) {
cache=cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
}else{
cache= cipher.doFinal(data, offSet, inputLen -offSet);
}
out.write(cache,0, cache.length);
i++;
offSet= i *MAX_DECRYPT_BLOCK;
}
cache=out.toByteArray();
out.close();returncache;
}catch(Exception e) {throw new RuntimeException("解密失败", e);
}
}/*** 使用私钥加密数据 用一个已打包成的私钥加密数据,即数字签名
*
*@parampriKey 获取到的的私钥(我方的)
*@paramsource 要签名的数据,一般应是数字摘要
*@return签名 byte[]*/
public static String sign(String priKey, byte[] source) {try{byte[] keyBytes =decryptBASE64(priKey);
PKCS8EncodedKeySpec priSpec= newPKCS8EncodedKeySpec(keyBytes);
KeyFactory mykeyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey key=mykeyFactory.generatePrivate(priSpec);
Signature sig=Signature.getInstance(KEY_SIGN);
sig.initSign(key);
sig.update(source);returnencryptBASE64(sig.sign());
}catch(Exception e) {throw new RuntimeException("加签失败", e);
}
}/*** 验证数字签名
*
*@parampubKey 获取到的公钥(我方的)
*@paramsource 原文的数字摘要
*@paramsign 签名(对原文的数字摘要的签名)
*@return是否证实 boolean*/
public static boolean verify(String pubKey, byte[] source, String sign) {try{byte[] keyBytes =decryptBASE64(pubKey);
KeyFactory mykeyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
Signature sig=Signature.getInstance(KEY_SIGN);
X509EncodedKeySpec pubSpec= newX509EncodedKeySpec(keyBytes);
PublicKey key=mykeyFactory.generatePublic(pubSpec);
sig.initVerify(key);
sig.update(source);returnsig.verify(decryptBASE64(sign));
}catch(Exception e) {
logger.error("验签失败", e);return false;
}
}/*** 私钥加密
*
*@parampriKey
*@paramdata
*@return
*/
public staticString encryptByPrivateKey(String priKey, String data) {try{return encryptBASE64(encryptByPrivateKey(priKey, data.getBytes("utf-8")));
}catch(UnsupportedEncodingException e) {throw new RuntimeException("加密失败", e);
}
}/*** 私钥加密
*
*@parampriKey
*@paramdata
*@return
*/
public static byte[] encryptByPrivateKey(String priKey, byte[] data) {try{byte[] bytes =decryptBASE64(priKey);//取得私钥
PKCS8EncodedKeySpec keySpec = newPKCS8EncodedKeySpec(bytes);
KeyFactory factory=KeyFactory.getInstance(KEY_ALGORITHM);
Key key=factory.generatePrivate(keySpec);//对数据加密
Cipher cipher =Cipher.getInstance(factory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, key);int inputLen =data.length;
ByteArrayOutputStream out= newByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;//对数据分段加密
while (inputLen - offSet > 0) {if (inputLen - offSet >MAX_ENCRYPT_BLOCK) {
cache=cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
}else{
cache= cipher.doFinal(data, offSet, inputLen -offSet);
}
out.write(cache,0, cache.length);
i++;
offSet= i *MAX_ENCRYPT_BLOCK;
}
cache=out.toByteArray();
out.close();returncache;
}catch(Exception e) {throw new RuntimeException("加密失败", e);
}
}/*** 公钥解密
*
*@parampubKey
*@paramdata
*@return
*/
public staticString decryptByPublicKey(String pubKey, String data) {try{return newString(decryptByPublicKey(pubKey, decryptBASE64(data)),"utf-8");
}catch(IOException e) {throw new RuntimeException("解密失败", e);
}
}/*** 公钥解密
*
*@parampubKey
*@paramdata
*@return
*/
public static byte[] decryptByPublicKey(String pubKey, byte[] data) {try{//对公钥解密
byte[] bytes =decryptBASE64(pubKey);//取得公钥
X509EncodedKeySpec keySpec = newX509EncodedKeySpec(bytes);
KeyFactory factory=KeyFactory.getInstance(KEY_ALGORITHM);
Key key=factory.generatePublic(keySpec);//对数据解密
Cipher cipher =Cipher.getInstance(factory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, key);int inputLen =data.length;
ByteArrayOutputStream out= newByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;//对数据分段解密
while (inputLen - offSet > 0) {if (inputLen - offSet >MAX_DECRYPT_BLOCK) {
cache=cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
}else{
cache= cipher.doFinal(data, offSet, inputLen -offSet);
}
out.write(cache,0, cache.length);
i++;
offSet= i *MAX_DECRYPT_BLOCK;
}
cache=out.toByteArray();
out.close();returncache;
}catch(Exception e) {throw new RuntimeException("解密失败", e);
}
}public static byte[] decryptBASE64(String key) throwsIOException {return newBASE64Decoder().decodeBuffer(key);
}public static String encryptBASE64(byte[] bytes) {return newBASE64Encoder().encodeBuffer(bytes);
}public static String encryptBASE64(InputStream in) throwsIOException {
StringBuilder builder= newStringBuilder();
BASE64Encoder encoder= newBASE64Encoder();byte[] byteBuf = new byte[6 * 760];intlength;while ((length = in.read(byteBuf)) != -1) {if (length !=byteBuf.length) {byte[] copy =Arrays.copyOf(byteBuf, length);
builder.append(encoder.encode(copy));
}else{
builder.append(encoder.encode(byteBuf));
}
}returnbuilder.toString();
}public static String encryptBASE64(InputStream in, String prefix) throwsIOException {
StringBuilder builder= newStringBuilder(prefix);
BASE64Encoder encoder= newBASE64Encoder();byte[] byteBuf = new byte[6 * 760];intlength;while ((length = in.read(byteBuf)) != -1) {if (length !=byteBuf.length) {byte[] copy =Arrays.copyOf(byteBuf, length);
builder.append(encoder.encode(copy));
}else{
builder.append(encoder.encode(byteBuf));
}
}returnbuilder.toString();
}
}
更多推荐
所有评论(0)