emmmmmm就是呢,我今天研究了一下非对称数据加密RSA的使用,算法什么的暂时不研究,加密算法还有很多,以后再研究吧,就酱(>人<;)。非对称加密算法需要两个密钥:公开密钥(publicKey)和私有密钥(privateKey);如果用公有密钥加密,对应的就是要私有密钥才能解密;反过来就是私钥加密,公钥解密。

  然后就来实现一下RSA加密的工具类吧

 

  注意:RSA加密明文最大长度是117字节,解密要求密文最大长度为128字节,所以再加密和解密的时候要分段进行,就是每117字节就加密,然后再把这一节节拼起来。

 

public class AES_RSAUtil {

    public static void main(String[] args) throws Exception{
        /*模拟客户端*/
        String msg = "hello 冬竹";
        byte[] key = AESUtil.getKeys();//获取密钥的编码

        byte[] bytes = AESUtil.encrypt(msg,key);
        String seKey = Base64.encodeBase64URLSafeString(key);//转成字符串之后进行再加密
        RSAUtil.init();
        //RSA公钥 加密后的 AES密钥
        String encryptKey = RSAUtil.encryptByPublicKey(seKey,RSAUtil.getPublicKey(RSAUtil.keyMap.get("PUBLIC_KEY")));




        /*模拟服务端*/
        //解码AES密钥
        String aesKey = RSAUtil.decryptByPrivateKey(encryptKey,RSAUtil.getPrivateKey(RSAUtil.keyMap.get("PRIVATE_KEY")));
        //还原aesKey
        byte[] secretKey = Base64.decodeBase64(aesKey);
        String ming = new String(AESUtil.decrypt(bytes,secretKey));
        System.out.println(ming);

    }
}

  

  

 

 

 加密字符串的过程:

    1.   msg.getBytes() 获得字符数组, 然后用rsaSplitCode() 方法加密,再用encodeBase64URLSafeString编码成字符串(密文)

 解密字符串的过程:

    1.  decodeBase64() 把密文解码成字符数组,再用new String()方法转为字符串

 

然后我用的Base64类是commons-net-3.1.jar  里的,这个是我的maven仓库里(maven真的太方便了(●ˇ∀ˇ●))

放上这个:https://github.com/MoisAbby/XZUtils, 以后会把我攒的好用的东西都放上来

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-02
  • 2021-10-08
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-06
  • 2022-01-07
  • 2021-12-27
  • 2021-12-09
  • 2021-06-22
相关资源
相似解决方案