密码系统AES私钥RSA公钥的加解密示例

 更新时间:2022年03月07日 16:54:26   作者:kl  
这篇文章主要为大家诠释并介绍了AES私钥RSA公钥的加解密系统示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步

前言

密钥是成对存在的,加密和解密是采用不同的密钥(公开密钥),也就是非对称密钥密码系统,每个通信方均需要两个密钥,即公钥和私钥,使用公钥进行加密操作,使用私钥进行解密操作。公钥是公开的,不需要保密,而私钥是由个人自己持有,并且必须妥善保管和注意保密。密码学里面博大精深,下面的实例仅供参考

百科的诠释

公钥(Public Key)与私钥(Private Key)是通过一种算法得到的一个密钥对(即一个公钥和一个私钥),公钥是密钥对中公开的部分,私钥则是非公开的部分。公钥通常用于加密会话密钥、验证数字签名,或加密可以用相应的私钥解密的数据。通过这种算法得到的密钥对能保证在世界范围内是唯一的。使用这个密钥对的时候,如果用其中一个密钥加密一段数据,必须用另一个密钥解密。比如用公钥加密数据就必须用私钥解密,如果用私钥加密也必须用公钥解密,否则解密将不会成功。

java使用公私钥加解密的实例

仅供参考

/**
     * 数据加密 plainTextData要加密的字符串
     * @param plainTextData
     * @return
     * @throws Exception
     */
    public static Map encrypt(String plainTextData)
            throws Exception {
        HashMap result = new HashMap();
        // keySpec 生成对称密钥
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
        // RSA 用对方公钥对‘对称密钥'进行加密
        Cipher cipher = Cipher.getInstance("RSA");
        String keyFilePathName = pertery.getProperty("bsbank_Key_path")+"PublicKey.keystore";
        cipher.init(Cipher.WRAP_MODE,
                loadPublicKeyByStr(loadKeyByFile(keyFilePathName)));
        byte[] wrappedKey = cipher.wrap(keySpec);
        result.put("wrappedKey", Base64.encodeBase64String(wrappedKey));
        // 加密数据
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encryptedData = cipher.doFinal(plainTextData.getBytes("UTF-8"));
        result.put("encryptedData", Base64.encodeBase64String(encryptedData));
        return result;
    }
    /**
     * 数据解密 encryptedData
     * @param encryptedData
     * @return
     * @throws Exception
     */
    public static Map decrypt(Map encryptedData)
            throws Exception {
        // 获取密钥
        byte[] wrappedKey = Base64.decodeBase64(encryptedData.get("wrappedKey")
                .toString());
        HashMap result = new HashMap();
        // RSA解密密钥
        Cipher cipher = Cipher.getInstance("RSA");
        String keyFilePathName = pertery.getProperty("bsbank_Key_path")+"privateKey.keystore";//使用对方的私钥解密
        cipher.init(Cipher.UNWRAP_MODE,
                loadPrivateKeyByStr(loadKeyByFile(keyFilePathName)));
        Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
        // 解密数据
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedData = cipher.doFinal(Base64.decodeBase64(encryptedData
                .get("encryptedData").toString()));
        result.put("decryptedData", new String(decryptedData, "UTF-8"));
        result.put("wrappedKey", Base64.encodeBase64String(wrappedKey));
        return result;
    }
    private static String loadKeyByFile(String filePathName) throws Exception {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            br = new BufferedReader(new FileReader(filePathName));
            String readLine = null;
            while ((readLine = br.readLine()) != null) {
                sb.append(readLine);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != br) {
                br.close();
            }
        }
        return sb.toString();
    }
    private static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
            throws Exception {
        RSAPublicKey publicKey = null;
        try {
            byte[] buffer = Base64.decodeBase64(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (Exception e) {
            logger.error("failed to load pubKey", e);
            throw e;
        }
        return publicKey;
    }
    private static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
            throws Exception {
        RSAPrivateKey privateKey = null;
        try {
            byte[] buffer = Base64.decodeBase64(privateKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (Exception e) {
            logger.error("failed to loadPrivateKeyByStr", e);
            throw e;
        }
        return privateKey;
    }
    /**
     * 输出公私钥对
     * @param filePath
     * @throws Exception
     */
    private static void genKeyPair(String filePath) throws Exception {
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            logger.error("failed to do key gen", e);
            throw e;
        }
        keyPairGen.initialize(1024, new SecureRandom());
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        try {
            String publicKeyString = Base64.encodeBase64String(publicKey
                    .getEncoded());
            String privateKeyString = Base64.encodeBase64String(privateKey
                    .getEncoded());
            FileWriter pubfw = new FileWriter(filePath + "/PublicKey.keystore");
            FileWriter prifw = new FileWriter(filePath + "/PrivateKey.keystore");
            BufferedWriter pubbw = new BufferedWriter(pubfw);
            BufferedWriter pribw = new BufferedWriter(prifw);
            pubbw.write(publicKeyString);
            pribw.write(privateKeyString);
            pubbw.flush();
            pubbw.close();
            pubfw.close();
            pribw.flush();
            pribw.close();
            prifw.close();
        } catch (IOException e) {
            logger.error("failed to genKeypair", e);
        }
    }

以上就是诠释AES私钥RSA公钥的加解密示例的详细内容,更多关于AES RSA公私钥加解密的资料请关注脚本之家其它相关文章!

相关文章

  • 解决spring结合mybatis时一级缓存失效的问题

    解决spring结合mybatis时一级缓存失效的问题

    这篇文章主要介绍了解决spring结合mybatis时一级缓存失效的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-11-11
  • Java异常处理try catch的基本用法

    Java异常处理try catch的基本用法

    try就像一个网,把try{}里面的代码所抛出的异常都网住,然后把异常交给catch{}里面的代码去处理。最后执行finally之中的代码。无论try中代码有没有异常,也无论catch是否将异常捕获到,finally中的代码都一定会被执行。
    2021-12-12
  • 详解Spring如何解析占位符

    详解Spring如何解析占位符

    Spring一直支持将属性定义到外部的属性的文件中,并使用占占位符的形式为使用"${}"包装的属性名称,为了使用属性占位符,我们必须配置一个PropertyPlaceholderConfigurer或PropertySourcesPlaceholderConfigurer实例,本文将介绍如何解析占位符
    2021-06-06
  • Spring JDBC 框架简介

    Spring JDBC 框架简介

    Spring JDBC 提供几种方法和数据库中相应的不同的类与接口。我将给出使用JdbcTemplate类框架的经典和最受欢迎的方法。本文给大家介绍Spring JDBC 框架的相关知识,感兴趣的朋友一起看看吧
    2021-12-12
  • Java多线程案例实战之定时器的实现

    Java多线程案例实战之定时器的实现

    在Java中可以使用多线程和定时器来实现定时任务,下面这篇文章主要给大家介绍了关于Java多线程案例之定时器实现的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2024-01-01
  • Java数据库连接PreparedStatement的使用详解

    Java数据库连接PreparedStatement的使用详解

    这篇文章主要介绍了Java数据库连接PreparedStatement的使用详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • java中的Object类的toSpring()方法

    java中的Object类的toSpring()方法

    这篇文章主要介绍了java中的Object类的toSpring()方法,Object是类层次结构的根,每个类都可以将Object作为超类。所有类都直接或者间接的继承自该类,下文相关资料,需要的朋友可以参考下
    2022-04-04
  • Java内存模型知识详解

    Java内存模型知识详解

    这篇文章主要介绍了Java内存模型知识详解,文中通过对内存访问时的交互关系图解介绍的十分详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • Java模拟计算机的整数乘积计算功能示例

    Java模拟计算机的整数乘积计算功能示例

    这篇文章主要介绍了Java模拟计算机的整数乘积计算功能,简单分析了计算机数值进制转换与通过位移进行乘积计算的原理,并结合具体实例给出了java模拟计算机成绩运算的相关操作技巧,需要的朋友可以参考下
    2017-09-09
  • 详解SpringMVC使用MultipartFile实现文件的上传

    详解SpringMVC使用MultipartFile实现文件的上传

    本篇文章主要介绍了SpringMVC使用MultipartFile实现文件的上传,本地的文件上传到资源服务器上,比较好的办法就是通过ftp上传。这里是结合SpringMVC+ftp的形式上传的,有兴趣的可以了解一下。
    2016-12-12

最新评论