亲宝软件园·资讯

展开

java RSAUtils加密工具类 java RSAUtils 加密工具类操作

after95 人气:0
想了解java RSAUtils 加密工具类操作的相关内容吗,after95在本文为您仔细讲解java RSAUtils加密工具类的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java,RSAUtils,加密工具类,下面大家一起来学习吧。

1.RSA加密算法是一种非对称加密算法。在公开密钥加密和电子商业中RSA被广泛使用。RSA公开密钥密码体制。所谓的公开密钥密码体制就是使用不同的加密密钥与解密密钥,是一种“由已知加密密钥推导出解密密钥在计算上是不可行的”密码体制。在公开密钥密码体制中,加密密钥(即公开密钥)PK是公开信息,而解密密钥(即秘密密钥)SK是需要保密的。加密算法E和解密算法D也都是公开的。虽然解密密钥SK是由公开密钥PK决定的,但却不能根据PK计算出SK。

2.本工具类涉及到BASE64编码,所以先展示出BASE64Utils:

package com.example.springboottest.common.util;
 
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.security.MessageDigest;
 
/**
 * BASE64的加解密
 * @author Neo
 * @date 2018-4-15 22:21:51
 *
 */
@SuppressWarnings("restriction")
public class Base64Utils { 
 public static final String KEY_SHA = "SHA"; 
 public static final String KEY_MD5 = "MD5"; 
 
 /** 
  * BASE64解密 
  * 
  * @param key 
  * @return 
  * @throws Exception 
  */ 
 public static byte[] decryptBASE64(String key) throws Exception { 
  return (new BASE64Decoder()).decodeBuffer(key); 
 } 
 
 /** 
  * BASE64加密 
  * 
  * @param key 
  * @return 
  * @throws Exception 
  */ 
 public static String encryptBASE64(byte[] key) throws Exception { 
  return (new BASE64Encoder()).encodeBuffer(key); 
 } 
 
 /** 
  * MD5加密 
  * 
  * @param data 
  * @return 
  * @throws Exception 
  */ 
 public static byte[] encryptMD5(byte[] data) throws Exception { 
 
  MessageDigest md5 = MessageDigest.getInstance(KEY_MD5); 
  md5.update(data); 
  return md5.digest(); 
 
 } 
 
 /** 
  * SHA加密 
  * 
  * @param data 
  * @return 
  * @throws Exception 
  */ 
 public static byte[] encryptSHA(byte[] data) throws Exception { 
 
  MessageDigest sha = MessageDigest.getInstance(KEY_SHA); 
  sha.update(data); 
 
  return sha.digest(); 
 
 } 
} 

3.然后我们展示RSAUtils:

package com.example.springboottest.common.util;
 
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
 
/**
 * RSA安全编码组件
 *
 * @version 1.0
 * @desc 公钥和私钥存放在properties文件的时候每行的末尾加上“\r\n\” <br/>
 * “\r\n” 起到换行的作用,最后的“\”在properties在里表示连接
 * 
 * @author Neo 
 * @date 2018-4-15 22:23:19
 * @since 1.0
 */
public class RSAUtils extends Base64Utils {
 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";
 
 /**
  * 用私钥对信息生成数字签名
  *
  * @param data  加密数据
  * @param privateKey 私钥
  * @return
  * @throws Exception
  */
 public static String sign(String data, String privateKey) throws Exception {
  return sign(data.getBytes(), privateKey);
 }
 
 /**
  * 用私钥对信息生成数字签名
  *
  * @param data  加密数据
  * @param privateKey 私钥
  * @return
  * @throws Exception
  */
 public static String sign(byte[] data, String privateKey) throws Exception {
  // 解密由base64编码的私钥
  byte[] keyBytes = decryptBASE64(privateKey);
 
  // 构造PKCS8EncodedKeySpec对象
  PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
 
  // KEY_ALGORITHM 指定的加密算法
  KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
 
  // 取私钥匙对象
  PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
 
  // 用私钥对信息生成数字签名
  Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
  signature.initSign(priKey);
  signature.update(data);
 
  return encryptBASE64(signature.sign());
 }
 
 /**
  * 校验数字签名
  *
  * @param data  加密数据
  * @param publicKey 公钥
  * @param sign  数字签名
  * @return 校验成功返回true 失败返回false
  * @throws Exception
  */
 public static boolean verify(String data, String publicKey, String sign) throws Exception {
  return verify(data.getBytes(), publicKey, sign);
 }
 
 /**
  * 校验数字签名
  *
  * @param data  加密数据
  * @param publicKey 公钥
  * @param sign  数字签名
  * @return 校验成功返回true 失败返回false
  * @throws Exception
  */
 public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
 
  // 解密由base64编码的公钥
  byte[] keyBytes = decryptBASE64(publicKey);
 
  // 构造X509EncodedKeySpec对象
  X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
 
  // KEY_ALGORITHM 指定的加密算法
  KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
 
  // 取公钥匙对象
  PublicKey pubKey = keyFactory.generatePublic(keySpec);
 
  Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
  signature.initVerify(pubKey);
  signature.update(data);
 
  // 验证签名是否正常
  return signature.verify(decryptBASE64(sign));
 }
 
 /**
  * 解密<br>
  * 用私钥解密
  *
  * @param data
  * @param key
  * @return
  * @throws Exception
  */
 public static String decryptByPrivateKey(String data, String key) throws Exception {
  return new String(decryptByPrivateKey(Base64Utils.decryptBASE64(data), key));
 }
 
 /**
  * 解密<br>
  * 用私钥解密
  *
  * @param data
  * @param key
  * @return
  * @throws Exception
  */
 public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception {
  // 对密钥解密
  byte[] keyBytes = decryptBASE64(key);
 
  // 取得私钥
  PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
  KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
 
  // 对数据解密
  Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
  cipher.init(Cipher.DECRYPT_MODE, privateKey);
 
  return cipher.doFinal(data);
 }
 
 /**
  * 解密<br>
  * 用私钥解密
  *
  * @param data
  * @param key
  * @return
  * @throws Exception
  */
 public static String decryptByPublicKey(String data, String key) throws Exception {
  return new String(decryptByPublicKey(Base64Utils.decryptBASE64(data), key));
 }
 
 /**
  * 解密<br>
  * 用私钥解密
  *
  * @param data
  * @param key
  * @return
  * @throws Exception
  */
 public static byte[] decryptByPublicKey(byte[] data, String key) throws Exception {
  // 对密钥解密
  byte[] keyBytes = decryptBASE64(key);
 
  // 取得公钥
  X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
  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(data);
 }
 
 /**
  * 加密<br>
  * 用公钥加密
  *
  * @param data
  * @param key
  * @return
  * @throws Exception
  */
 public static String encryptByPublicKey(String data, String key) throws Exception {
  return Base64Utils.encryptBASE64(encryptByPublicKey(data.getBytes(), key));
 }
 
 /**
  * 加密<br>
  * 用公钥加密
  *
  * @param data
  * @param key
  * @return
  * @throws Exception
  */
 public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception {
  // 对公钥解密
  byte[] keyBytes = decryptBASE64(key);
 
  // 取得公钥
  X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
  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(data);
 }
 
 /**
  * 加密<br>
  * 用私钥加密
  *
  * @param data
  * @param key
  * @return
  * @throws Exception
  */
 public static String encryptByPrivateKey(String data, String key) throws Exception {
  return Base64Utils.encryptBASE64(encryptByPrivateKey(data.getBytes(), key));
 }
 
 /**
  * 加密<br>
  * 用私钥加密
  *
  * @param data
  * @param key
  * @return
  * @throws Exception
  */
 public static byte[] encryptByPrivateKey(byte[] data, String key) throws Exception {
  // 对密钥解密
  byte[] keyBytes = decryptBASE64(key);
 
  // 取得私钥
  PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
  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(data);
 }
 
 /**
  * 取得私钥
  *
  * @param keyMap
  * @return
  * @throws Exception
  */
 public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
  Key key = (Key) keyMap.get(PRIVATE_KEY);
 
  return encryptBASE64(key.getEncoded());
 }
 
 /**
  * 取得公钥
  *
  * @param keyMap
  * @return
  * @throws Exception
  */
 public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
  Key key = (Key) keyMap.get(PUBLIC_KEY);
 
  return encryptBASE64(key.getEncoded());
 }
 
 /**
  * 初始化密钥
  *
  * @return
  * @throws Exception
  */
 public static Map<String, Object> initKey() throws Exception {
  KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
  keyPairGen.initialize(1024);
 
  KeyPair keyPair = keyPairGen.generateKeyPair();
 
  // 公钥
  RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
 
  // 私钥
  RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
 
  Map<String, Object> keyMap = new HashMap<String, Object>(2);
  keyMap.put(PUBLIC_KEY, publicKey);
  keyMap.put(PRIVATE_KEY, privateKey);
  return keyMap;
 }
 
 public static void main(String[] args) {
  try {
   Map<String, Object> map = RSAUtils.initKey();
   String publicKey = RSAUtils.getPublicKey(map);
   String privateKey = RSAUtils.getPrivateKey(map);
   System.out.println("公钥:" + publicKey);
   System.out.println("私钥:" + privateKey);
   String data = "Java是世界上最好的编程语言";
   String encryptData = RSAUtils.encryptByPublicKey(data, publicKey);
   System.out.println("加密后:" + encryptData);
   String decryptData = RSAUtils.decryptByPrivateKey(encryptData, privateKey);
   System.out.println("解密后:" + decryptData);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

4.最后展示测试结果:

补充知识:java使用RSA生成公钥和私钥,并进行加解密

废话不多说,上代码:

import javax.crypto.Cipher;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
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.HashMap;
import java.util.Map;
 
/**
 * Java RSA 加密工具类
 */
public class RSAUtils {
 /**
  * 密钥长度 于原文长度对应 以及越长速度越慢
  */
 private final static int KEY_SIZE = 1024;
 /**
  * 用于封装随机产生的公钥与私钥
  */
 private static Map<Integer, String> keyMap = new HashMap<Integer, String>();
 
 /**
  * 随机生成密钥对
  * @throws Exception 
  */
 public static void genKeyPair() throws Exception {
  // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
  KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
  // 初始化密钥对生成器
  keyPairGen.initialize(KEY_SIZE, new SecureRandom());
  // 生成一个密钥对,保存在keyPair中
  KeyPair keyPair = keyPairGen.generateKeyPair();
  // 得到私钥
  RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
  // 得到公钥
  RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
  String publicKeyString = encryptBASE64(publicKey.getEncoded());
  // 得到私钥字符串
  String privateKeyString = encryptBASE64(privateKey.getEncoded());
  // 将公钥和私钥保存到Map
  //0表示公钥
  keyMap.put(0, publicKeyString);
  //1表示私钥
  keyMap.put(1, privateKeyString);
 }
 
 //编码返回字符串
 public static String encryptBASE64(byte[] key) throws Exception {
  return (new BASE64Encoder()).encodeBuffer(key);
 }
 
 //解码返回byte
 public static byte[] decryptBASE64(String key) throws Exception {
  return (new BASE64Decoder()).decodeBuffer(key);
 }
 
 /**
  * RSA公钥加密
  *
  * @param str  加密字符串
  * @param publicKey 公钥
  * @return 密文
  * @throws Exception 加密过程中的异常信息
  */
 public static String encrypt(String str, String publicKey) throws Exception {
  //base64编码的公钥
  byte[] decoded = decryptBASE64(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 = encryptBASE64(cipher.doFinal(str.getBytes("UTF-8")));
  return outStr;
 }
 
 /**
  * RSA私钥解密
  *
  * @param str  加密字符串
  * @param privateKey 私钥
  * @return 明文
  * @throws Exception 解密过程中的异常信息
  */
 public static String decrypt(String str, String privateKey) throws Exception {
  //64位解码加密后的字符串
  byte[] inputByte = decryptBASE64(str);
  //base64编码的私钥
  byte[] decoded = decryptBASE64(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));
  return outStr;
 }
 
 public static void main(String[] args) throws Exception {
  long temp = System.currentTimeMillis();
  //生成公钥和私钥
  genKeyPair();
  //加密字符串
  System.out.println("公钥:" + keyMap.get(0));
  System.out.println("私钥:" + keyMap.get(1));
  System.out.println("生成密钥消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
 
  String message = "RSA测试aaa";
  System.out.println("原文:" + message);
 
  temp = System.currentTimeMillis();
  String messageEn = encrypt(message, keyMap.get(0));
  System.out.println("密文:" + messageEn);
  System.out.println("加密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
 
  temp = System.currentTimeMillis();
 
  String messageDe = decrypt(messageEn, keyMap.get(1));
  System.out.println("解密:" + messageDe);
  System.out.println("解密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
 }
}

以上这篇java RSAUtils 加密工具类操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论