Java加密算法RSA代码实例

 更新时间:2020年02月13日 11:26:27   作者:Ivy_Xu  
这篇文章主要介绍了Java加密算法RSA代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

这篇文章主要介绍了Java加密算法RSA代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

代码如下

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
 
public class RSADecrypt {
  public static Map<String, String> createKeyPair() throws NoSuchAlgorithmException {
    //创建秘钥对生成器
    KeyPairGenerator generator = KeyPairGenerator.getInstance("rsa");
    //初始化密钥对生成器
    generator.initialize(1024);
    //生成密钥对
    KeyPair keyPair = generator.generateKeyPair();
    //获取公钥私钥
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    String publicKeyStr = new String(publicKey.getEncoded());
    String privateKeyStr = new String(privateKey.getEncoded());
    //公钥私钥存放map
    Map<String, String> keyMap = new HashMap<>();
    keyMap.put("publicKey", publicKeyStr);
    keyMap.put("privateKey", privateKeyStr);
    return keyMap;
  }
 
  /**
   * 获取公钥
   * @param publicKey
   * @return
   */
  public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance("rsa");
    //X509编码
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getBytes());
    RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(x509EncodedKeySpec);
    return rsaPublicKey;
  }
 
  /**
   * 获取私钥
   * @param privateKey
   * @return
   */
  public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance("rsa");
    //PKCS#8编码
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getBytes());
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    return rsaPrivateKey;
  }
 
  /**
   * 公钥加密
   * @param src
   * @param publicKey
   * @return
   */
  public static byte[] publicEncrypt(String src, RSAPublicKey publicKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Cipher cipher = Cipher.getInstance("rsa");
    cipher.init(Cipher.ENCRYPT_MODE,publicKey);
    byte[] encryptedData = cipher.doFinal(src.getBytes());
    return encryptedData;
  }
 
  /**
   * 私钥解密
   * @param data
   * @param privateKey
   * @return
   * @throws NoSuchPaddingException
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeyException
   * @throws BadPaddingException
   * @throws IllegalBlockSizeException
   */
  public static String privateDecrypt(byte[] data, RSAPrivateKey privateKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Cipher cipher = Cipher.getInstance("rsa");
    cipher.init(Cipher.DECRYPT_MODE,privateKey);
    byte[] result = cipher.doFinal(data);
    return new String(result);
  }
 
  public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchPaddingException {
    Map<String,String> keyPair = createKeyPair();
    RSAPublicKey publicKey = getPublicKey(keyPair.get("publicKey"));
    RSAPrivateKey privateKey = getPrivateKey(keyPair.get("privateKey"));
    String str = "hello world";
    /**
     * 公钥加密,私钥解密
     */
    byte[] encryptedData = publicEncrypt(str,publicKey);
    String result = privateDecrypt(encryptedData, privateKey);
 
    /**
     * 私钥加密,公钥解密
     */
    byte[] encrypted = privateEncrypt(str, privateKey);
    String source = publicDecrypt(encrypted, publicKey);
 
  }
 
  /**
   * 私钥加密
   * @param src
   * @param privateKey
   * @return
   * @throws NoSuchPaddingException
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeyException
   * @throws BadPaddingException
   * @throws IllegalBlockSizeException
   */
  public static byte[] privateEncrypt(String src, RSAPrivateKey privateKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Cipher cipher = Cipher.getInstance("rsa");
    cipher.init(Cipher.DECRYPT_MODE,privateKey);
    byte[] result = cipher.doFinal(src.getBytes());
    return result;
  }
 
  /**
   * 公钥解密
   * @param data
   * @param publicKey
   * @return
   * @throws NoSuchPaddingException
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeyException
   * @throws BadPaddingException
   * @throws IllegalBlockSizeException
   */
  public static String publicDecrypt(byte[] data, RSAPublicKey publicKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Cipher cipher = Cipher.getInstance("rsa");
    cipher.init(Cipher.DECRYPT_MODE,publicKey);
    byte[] result = cipher.doFinal(data);
    return new String(result);
  }
}

上面例子使用密钥长度1024,如果想使用2048密钥,只需要在初始化密钥对生成器做一些变动,其他部分可以复用。

generator.initialize(2048);

这个例子只是基本常用的RSA加解密,也可加入base64,签名。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Java超详细讲解多态的调用

    Java超详细讲解多态的调用

    多态就是指程序中定义的引用变量所指向的具体类型和通过该引用变量发出的方法调用在编程时并不确定,而是在程序运行期间才确定,即一个引用变量到底会指向哪个类的实例对象,该引用变量发出的方法调用到底是哪个类中实现的方法,必须在由程序运行期间才能决定
    2022-05-05
  • 一文带你解读所有HashMap的面试题

    一文带你解读所有HashMap的面试题

    HashMap在面试的时候,是非常容易被问到的。因为在JDK8出来之后,非常容易被问到关于HashMap的知识点,而如果对于没有研究过他的源代码的同学来说,这个可能只是说出一部分来。本文就把HashMap上面大部分会被在面试中问到的内容,做个总结,希望有所帮助
    2022-09-09
  • 详解SpringBoot中的统一功能处理的实现

    详解SpringBoot中的统一功能处理的实现

    这篇文章主要为大家详细介绍了SpringBoot如何实现统一功能处理,文中的示例代码讲解详细,对我们学习或工作有一定借鉴价值,需要的可以参考一下
    2023-01-01
  • SpringBoot操作mongo实现方法解析

    SpringBoot操作mongo实现方法解析

    这篇文章主要介绍了SpringBoot操作mongo实现方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08
  • Java操作minio删除文件夹及其文件方法(MinIO基本使用)

    Java操作minio删除文件夹及其文件方法(MinIO基本使用)

    MinIO是一个高性能、无限扩展的开源对象存储服务器,它以对象的形式存储数据,并兼容Amazon S3接口,它适用于大规模数据存储、大数据分析、文件共享和备份等应用场景,这篇文章主要介绍了java操作minio删除文件夹及其文件方法,需要的朋友可以参考下
    2024-02-02
  • SpringBoot生产环境和测试环境配置分离的教程详解

    SpringBoot生产环境和测试环境配置分离的教程详解

    这篇文章主要介绍了SpringBoot生产环境和测试环境配置分离的教程详解,需要的朋友可以参考下
    2020-08-08
  • JAVA代码实现MongoDB动态条件之分页查询

    JAVA代码实现MongoDB动态条件之分页查询

    这篇文章主要介绍了JAVA如何实现MongoDB动态条件之分页查询,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-07-07
  • 浅析Spring和MyBatis整合及逆向工程

    浅析Spring和MyBatis整合及逆向工程

    这篇文章主要介绍了Spring和MyBatis整合及逆向工程的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2016-06-06
  • java中aop实现接口访问频率限制

    java中aop实现接口访问频率限制

    本文主要介绍了java中aop实现接口访问频率限制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • Spring Cloud Zuul的重试配置详解

    Spring Cloud Zuul的重试配置详解

    这篇文章主要介绍了Spring Cloud Zuul的重试配置详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-04-04

最新评论