首页 > 其他分享 >RSA加密

RSA加密

时间:2023-03-11 12:44:40浏览次数:39  
标签:return String RSA static KEY key 加密 public

    public static final String KEY_ALGORITHM = "RSA";

    private static final String PUBLIC_KEY = "RSAPublicKey";

    private static final String PRIVATE_KEY = "RSAPrivateKey";

    // 1024 bits 的 RSA 密钥对,最大加密明文大小
    private static final int MAX_ENCRYPT_BLOCK = 117;

    // 1024 bits 的 RSA 密钥对,最大解密密文大小
    private static final int MAX_DECRYPT_BLOCK = 128;
    /**
     *生成密钥对
     * @param keysize 密钥长度  待加密的明文长度与此长度成正比  即明文再打长度与设置的密钥长度为;1:1
     * @return
     * @throws Exception
     */
    public static Map<String, Object> initKey(int keysize) throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        // 设置密钥对的 bit 数,越大越安全
        keyPairGen.initialize(keysize);
        KeyPair keyPair = keyPairGen.generateKeyPair();

        // 获取公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        // 获取私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

 

// 获取公钥
    public static PublicKey getPublicKey(String publicKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] publicKeyByte = Base64.getDecoder().decode(publicKeyString);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyByte);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePublic(keySpec);
    }

    // 获取私钥
    public static PrivateKey getPrivateKey(String privateKeyString) throws Exception {
        byte[] privateKeyByte = Base64.getDecoder().decode(privateKeyString);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyByte);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
    }

 

    // 获取公钥字符串
    public static String getPublicKeyStr(Map<String, Object> keyMap) {
        // 获得 map 中的公钥对象,转为 key 对象
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        // 编码返回字符串
        return encryptBASE64(key.getEncoded());
    }

    // 获取私钥字符串
    public static String getPrivateKeyStr(Map<String, Object> keyMap) {
        // 获得 map 中的私钥对象,转为 key 对象
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        // 编码返回字符串
        return encryptBASE64(key.getEncoded());
    }

 

    /**
     * BASE64 编码返回加密字符串
     *
     * @param key 需要编码的字节数组
     * @return 编码后的字符串
     */
    public static String encryptBASE64(byte[] key) {
        return new String(Base64.getEncoder().encode(key));
    }

    /**
     * BASE64 解码,返回字节数组
     *
     * @param key 待解码的字符串
     * @return 解码后的字节数组
     */
    public static byte[] decryptBASE64(String key) {
        return Base64.getDecoder().decode(key);
    }

 

    /**
     * 公钥加密
     *
     * @param text         待加密的明文字符串
     * @param publicKeyStr 公钥
     * @return 加密后的密文
     */
    public static String encrypt(String text, String publicKeyStr) {
        try {
            log.info("明文字符串为:[{}]", text);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKeyStr));
            byte[] tempBytes = cipher.doFinal(text.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(tempBytes);
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + text + "]时遇到异常", e);
        }
    }

    /**
     * 私钥解密
     *
     * @param secretText    待解密的密文字符串
     * @param privateKeyStr 私钥
     * @return 解密后的明文
     */
    public static String decrypt(String secretText, String privateKeyStr) {
        try {
            // 生成私钥
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKeyStr));
            // 密文解码
            byte[] secretTextDecoded = Base64.getDecoder().decode(secretText.getBytes("UTF-8"));
            byte[] tempBytes = cipher.doFinal(secretTextDecoded);
            return new String(tempBytes);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + secretText + "]时遇到异常", e);
        }
    }

 

标签:return,String,RSA,static,KEY,key,加密,public
From: https://www.cnblogs.com/wangbiaohistory/p/17205671.html

相关文章

  • 《渗透测试》算法分析&传输加密&数据格式&密文存储&代码混淆&逆向保护 2023 day8
           1数据在传输的时候为什么要进行编码   安全测试的时候往往会对url等地方进行修改、构造数据。数据传输的时候被编码的话,如果不按照对应编码......
  • JS代码加密:Eval的终极用法
    Eval加密的终极用法Eval加密,做为一种传统且古老的JS代码加密方法,相信很多人都知道。例如这个在线Eval加密:​​https://www.fairysoftware.com/js_jia_mi_eval.html​​但这......
  • 如何通过Java程序加密或者解密PDF文档
    PDF文档加密是一种用于保护文件内容的功能。加密后的文档需要提供密码才能打开和查看。这一功能有效防止未经授权的访问、复制和修改PDF文件。FreeSpire.PDFforJava支......
  • golang 自行实现一个base64加密
    packagemainimport( "fmt" "strconv")constbase64table="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"funcMybase64(astring){......
  • rsa公钥和私钥到底哪个才是用来加密,哪个用来解密?
    本文转自:91博客;原文地址:http://www.9191boke.com/138589019.html 公钥和私钥在一些银行系统、第三方支付系统SDK中经常会遇到,刚接触公钥私钥的朋友们估计很难区分两者......
  • 加密中间件对比
    MD5md5不可逆的原因是由于它是一种散列函数,使用的是hash(摘要)算法;不过基于键值对的字典关系原理,有一些收集海量md5信息与摘要的数据库(如彩虹表),采用枚举法能够从md5......
  • JAVA (Spring Boot)数据AES加密解密
    packagecom.example.controller;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.client.RestTemplate;importjavax......
  • rsa公钥和私钥区别 哪个加密那个解密
    公钥和私钥在一些银行系统、第三方支付系统SDK中经常会遇到,刚接触公钥私钥的朋友们估计很难区分两者的区别。RSA公钥和私钥是什么?首先来说,RSA是一种非对称加密算法,它是由三......
  • api接口使用MD5加密加盐签名校验
    最近一个A系统需要向B系统推送数据,因为数据每天不一定有多少,有时候多有时候少,且由UGC生成,需要B系统做一些处理,用mq比较麻烦,且公司用的付费rocketmq。除了重要数据一般不使......
  • 106. Construct Binary Tree from Inorder and Postorder Traversal
    题目Giveninorderandpostordertraversalofatree,constructthebinarytree.Note:Youmayassumethatduplicatesdonotexistinthetree.思路本题......