• JAVA 加密方法


    1. RSA非对称加密

    生成密钥对代码:

    //生成秘钥对
        public static KeyPair getKeyPair() throws NoSuchAlgorithmException {
            KeyPairGenerator keyPairGenerator= KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(1024);
            return keyPairGenerator.generateKeyPair();
        }
    
        //获取公钥字符串
        public static String getPublicKeyString(PublicKey key){
            return new String(Base64.getEncoder().encode(key.getEncoded()));
        }
        //获取私钥字符串
        public static String getPrivateKeyString(PrivateKey key){
            return new String(Base64.getEncoder().encode(key.getEncoded()));
        }

    公钥加密

        //公钥加密
        public static String encrypt(String content,String publicKeyString)throws Exception{
            PublicKey publicKey = getPublicKey(publicKeyString);
            byte[] contentByte = content.getBytes();
            byte[] result = encrypt(contentByte,publicKey);
            return Base64.getEncoder().encodeToString(result);
        }
        private static byte[] encrypt(byte[] content, PublicKey publicKey) throws Exception{
            Cipher cipher=Cipher.getInstance("RSA");//java默认"RSA"="RSA/ECB/PKCS1Padding"
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(content);
        }

    私钥解密

     //解密
        private static byte[] decrypt(byte[] content, PrivateKey privateKey) throws Exception{
            Cipher cipher=Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return cipher.doFinal(content);
        }
        //将base64编码后的私钥字符串转成PrivateKey实例
        private static PrivateKey getPrivateKey(String privateKey) throws Exception{
            byte[ ] keyBytes= Base64.getDecoder().decode(privateKey.getBytes());
            PKCS8EncodedKeySpec keySpec=new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory=KeyFactory.getInstance("RSA");
            return keyFactory.generatePrivate(keySpec);
        }

    2. MD5加密

     Md5PasswordEncoder encoder = new Md5PasswordEncoder();
            String result = encoder.encodePassword(“str”,null).toUpperCase();
            result = encoder.encodePassword(result.substring(1,11),null).toUpperCase();
            
  • 相关阅读:
    CC2540-BLE4.0 学历笔记1之串口体验
    cc2530的PWM实现
    用qt写的一个简单到不能在简单的上位机
    在Kubuntu14.04中安装小企鹅输入法
    初始化umi项目
    工具杂记(三) -- zookeeper
    工具杂记(二) -- Centos7
    工具杂记(一) -- vagrant
    (一)Docker导学
    JVM随笔(二)之搜索类
  • 原文地址:https://www.cnblogs.com/pangkang/p/9407687.html
Copyright © 2020-2023  润新知