rsa简单使用

RSAUtils.java

public final class RSAUtils {

   /** 安全服务提供者 */
   private static final Provider PROVIDER = new BouncyCastleProvider();

   /** 密钥大小 */
   private static final int KEY_SIZE = 2048;
   
   private static List<KeyPair> keys = new ArrayList<KeyPair>();
   
   private static int MAX_KEYS = 500;//最大公钥数量
   
   /**
    * 不可实例化
    */
   private RSAUtils() {
   }

   /**
    * 生成密钥对
    * 
    * @return 密钥对
    */
   private static KeyPair getNewKeyPair() {
      try {
	//密钥生成器
         KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", PROVIDER);
	//初始化密钥生成器
         keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
	//返回生成的密钥
         return keyPairGenerator.generateKeyPair();
      } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
         return null;
      }
   }

   public static KeyPair generateKeyPair() {
      //若达到最大公钥数量,从当前公钥库返回一个,否则生成新公钥并返回
      if(keys.size()>MAX_KEYS){
         return keys.get((int)(System.currentTimeMillis()%keys.size()));
      }else{
//       keys.get(-1);
         KeyPair key = getNewKeyPair();
         keys.add(key);
         //System.out.println("生成密钥成功,当前密钥库"+keys.size());
         return key;
      }
   }

	
/**
 * 加密
 * 
 * @param publicKey
 *            公钥
 * @param data
 *            数据
 * @return 加密后的数据
 */
public static byte[] encrypt(PublicKey publicKey, byte[] data) {
   Assert.notNull(publicKey);
   Assert.notNull(data);
   try {
	//RSA密码器实例
      Cipher cipher = Cipher.getInstance("RSA", PROVIDER);
	//初始化密码器为加密模式
      cipher.init(Cipher.ENCRYPT_MODE, publicKey);
      return cipher.doFinal(data);
   } catch (Exception e) {
      e.printStackTrace();
      return null;
   }
}
/**
 * 解密
 * 
 * @param privateKey
 *            私钥
 * @param data
 *            数据
 * @return 解密后的数据
 */
public static byte[] decrypt(PrivateKey privateKey, byte[] data) {
   Assert.notNull(privateKey);
   Assert.notNull(data);
   try {
	//生成密码器实例(填充模式)
      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", PROVIDER);
	//初始化密码器为加密模式
      cipher.init(Cipher.DECRYPT_MODE, privateKey);
      return cipher.doFinal(data);
   } catch (Exception e) {
      return null;
   }
}
}

RSAServiceImpl.java

@Service("rsaServiceImpl")
public class RSAServiceImpl implements RSAService {

   /** "私钥"参数名称 */
   private static final String PRIVATE_KEY_ATTRIBUTE_NAME = "privateKey";

   @Transactional(readOnly = true)
   public RSAPublicKey generateKey(HttpServletRequest request) {
      Assert.notNull(request);
	//生成密钥
      KeyPair keyPair = RSAUtils.generateKeyPair();
	//获取公钥
      RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
	//获取私钥
      RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
	//私钥设置在Session中
      HttpSession session = request.getSession();
      session.setAttribute(PRIVATE_KEY_ATTRIBUTE_NAME, privateKey);
	//公钥返回前端页面,并用其对明文进行加密
      return publicKey;
   }

   @Transactional(readOnly = true)
   public String decryptParameter(String name, HttpServletRequest request) {
      Assert.notNull(request);
      if (name != null) {
	//获取Session中的私钥
         HttpSession session = request.getSession();
         RSAPrivateKey privateKey = (RSAPrivateKey) session.getAttribute(PRIVATE_KEY_ATTRIBUTE_NAME);
	//获取密文
         String parameter = request.getParameter(name);
         if (privateKey != null && StringUtils.isNotEmpty(parameter)) {
		//用密钥对密文进行解密
            return RSAUtils.decrypt(privateKey, parameter);
         }
      }
      return null;
   }
}
RSA算法是一种非对称加密算法,它可以用于加密数据和数字签名。在Java中,可以使用Java Cryptography Architecture(JCA)提供的API来实现RSA加密和解密。下面是简单的示例代码: ```java import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; public class RSAEncryption { public static void main(String[] args) throws Exception { String plainText = "Hello World"; // 生成RSA公钥和私钥 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048, new SecureRandom()); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); // 使用公钥加密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] cipherText = cipher.doFinal(plainText.getBytes()); // 使用私钥解密 cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedText = cipher.doFinal(cipherText); System.out.println("Plain Text: " + plainText); System.out.println("Encrypted Text: " + new String(cipherText)); System.out.println("Decrypted Text: " + new String(decryptedText)); } } ``` 上面的代码先生成了一个2048位的RSA公钥和私钥,然后使用公钥加密了一个字符串,再使用私钥解密获得原始字符串。在实际使用中,我们通常需要将公钥和私钥保存在文件中,以便在不同的应用程序中使用。可以使用PKCS8EncodedKeySpec和X509EncodedKeySpec类来将公钥和私钥转换为字节数组,以便在文件中保存。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值