Java加密算法:MD5加密,对称加密,非对称加密

目录

Java:密码算法

1、base64加密方式

2、jdk原生api实现MD5

3、使用codec依赖实现MD5加密

4、SHA加密

5、MAC算法加密

6、对称加密

7、非对称加密


Java:密码算法

1、base64算法

public class demo {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();

    public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "张三写java";
        //编码
        String encodedStr = Base64.getEncoder().encodeToString(str.getBytes(UTF8));
        System.out.println("encodedStr:" + encodedStr);

        //解码
        byte[] decode = Base64.getDecoder().decode(encodedStr.getBytes(UTF8));
        System.out.println("decode:"+ new String(decode,UTF8));

    }
}

结果:

注意:Base64 不是加密算法,而是一种编码方式。Base64 主要用于将二进制数据编码成文本格式,以便在文本协议中传输,如在电子邮件、XML、JSON 等中。它并不是为了提供加密或安全性而设计的。

URL编码

public class URLTest {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();

    public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "张三写java";
        //编码
        String encodedStr = URLEncoder.encode(str,UTF8);
        System.out.println("编码:"+encodedStr);
        //解码
        String decode = URLDecoder.decode(encodedStr,UTF8);
        System.out.println("解码后:"+decode);

    }
}

结果:

MD5: Message-Digest Algorithm,结果占128位==>16个byte=>转成16进制字符后是32个

11111111--->ff

2、jdk原生api实现MD5

public class MD5Test {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();

    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        String algorithm = "MD5";
        //获取消息摘要算法对象
        MessageDigest md = MessageDigest.getInstance(algorithm);
        //  获取原始内容的字节数组
        byte[] originalBytes = str.getBytes(UTF8);
        //获取到摘要结果
        byte[] digestBytes = md.digest(originalBytes);
        //当originalBytes比较大的时候,循环的进行update()
        //md.update(originalBytes);
        //md.digest();
        //把每一个字节转为16进制字符,最终再拼接起来这些16进制字符
       String hexStr = converBytes(digestBytes);
        System.out.println("hexStr:" + hexStr);
    }

    private static String converBytes(byte[] digestBytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : digestBytes) {
            //获取b的补码的后8位
            String hex = Integer.toHexString(((int)b)&0xff);
            // 15-->Integer.toHexString (15&Oxff)-->f-->0f
            // 16-- >Integer.toHexString(16&0xff)->10
            if (hex.length() == 1){
                hex = "0" + hex;
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}

 代码封装,把上面公共部分提取出来

public class HexUtils {
    
    /**
     * @description 把字节数组转为16进制字符串,如果一个字节转为16进制字符后不足两位,则前面补0
     * @author
     * @date 2023-02-23 21:02:13
     * @param digestBytes
     * @return {@link String}
     */
    public static String converBytes(byte[] digestBytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : digestBytes) {
            //获取b的补码的后8位
            String hex = Integer.toHexString(((int)b)&0xff);
            // 15-->Integer.toHexString (15&Oxff)-->f-->0f
            // 16-- >Integer.toHexString(16&0xff)->10
            if (hex.length() == 1){
                hex = "0" + hex;
            }
            sb.append(hex);
        }
        return sb.toString();
    }
     /**
     * 把16进制字符串(一定是偶数位的,因为converBytes已经处理过)转为字节数组
     * @param hexStr 16进制字符串
     * @return
     */
    public static byte[] converHex2Bytes(String hexStr) {
        //一个字节可以转为2个16进制字符
        int length = hexStr.length() / 2;

        byte[] reault = new byte[length];

        for (int i = 0; i < length; i++) {
            //hexStr : abcd
            //Integer.parseInt :把s转为10进制数,radix指定s是什么进制的数
            //获取每个字节的高4位, hexStr.substring(2,3)=>c
            int high4 = Integer.parseInt(hexStr.substring(i * 2,i * 2 + 1),16);
            //获取每个字节的低4位,hexStr.substring( 3,4)=>d
            int low4 = Integer.parseInt(hexStr.substring(i * 2 + 1,i * 2 + 2),16);
            reault[i] = (byte) (high4* 16 + low4);
        }
   return reault;
}
public class MessageDigestUtils {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    /**
     * @description 执行信息再要
     * @author
     * @date 2023-02-23 21:09:55
     * @param originContent 原始字符串
     * @param algorithm 算法名字,如MD5
     * @return {@link String}
     */
    public static String doDigest(String originContent,String algorithm){

        try {
            //获取消息摘要算法对象
            MessageDigest md = MessageDigest.getInstance(algorithm);
            //  获取原始内容的字节数组
            byte[] originalBytes = originContent.getBytes(UTF8);
            //获取到摘要结果
            byte[] digestBytes = md.digest(originalBytes);
            //当originalBytes比较大的时候,循环的进行update()
            //md.update(originalBytes);
            //md.digest();
            //把每一个字节转为16进制字符,最终再拼接起来这些16进制字符
            String hexStr = HexUtils.converBytes(digestBytes);
            return hexStr;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

3、使用codec依赖实现MD5加密

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.15</version>
        </dependency>
public class MD5Test {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();

    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        System.out.println( "str:" + DigestUtils.md5Hex(str.getBytes(UTF8)));
    }
}

结果: 

4、SHA加密

SHA(Secure Hash Algorithm) :安全散列算法

sha-256=>转成16进制字符后是64个

其他如sha-0,sha-1, sha-512

SHA-256加密:

public class Sha256Test {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        String algorithm = "SHA-256";
        //封装的类进行编码
        String hexStr = MessageDigestUtils.doDigest(str,algorithm);
        System.out.println("自己封装的str:" + hexStr);

        System.out.println("codec的str:" + DigestUtils.sha256Hex(str.getBytes(UTF8)));
    }
}

结果:

SHA-512

public class SHA512Test {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        String algorithm = "SHA-512";
        //封装的类进行编码
        String hexStr = MessageDigestUtils.doDigest(str,algorithm);
        System.out.println("自己封装的str:" + hexStr);

        System.out.println("codec的str:" + DigestUtils.sha512Hex(str.getBytes(UTF8)));
    }
}

5、MAC算法加密

MAC(Message Authentication Code):消息认证码,是一种带有秘钥的hash函数

使用jdk实现在添加一个方法 

/**
     * @description 获取mac的消息摘要
     * @author
     * @date 2023-02-23 21:37:36
     * @param originContent 原始内容
     * @param algorithm mac算法的key
     * @param key 算法名字,例如HmacMD5
     * @return {@link String}
     */
    public static String doMacDigest(String originContent,String algorithm,String key){

        try {
            //获取消息摘要算法对象
            Mac mac = Mac.getInstance(algorithm);
            //
            SecretKey secretKey = new SecretKeySpec(key.getBytes(UTF8),algorithm);
            mac.init(secretKey);
            //  获取原始内容的字节数组
            byte[] originalBytes = originContent.getBytes(UTF8);
            //获取到摘要结果
            byte[] digestBytes = mac.doFinal(originalBytes);
            //当originalBytes比较大的时候,循环的进行update()
            //md.update(originalBytes);
            //md.digest();
            //把每一个字节转为16进制字符,最终再拼接起来这些16进制字符
            String hexStr = HexUtils.converBytes(digestBytes);
            return hexStr;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

使用自己封装的方法及使用codec实现mac加密

public class MACTest {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        String algorithm1 = "HmacMD5";
        String algorithm2 = "HmacSHA256";
        String algorithm3 = "HmacSHA512";
        //指定秘钥, mac摘要和digest算法( md5 , sha)不同的地方就是加了盐
        String key = "123";
        //封装的类进行编码
        String hexStr1 = MessageDigestUtils.doMacDigest(str,algorithm1,key);
        String hexStr2 = MessageDigestUtils.doMacDigest(str,algorithm2,key);
        String hexStr3 = MessageDigestUtils.doMacDigest(str,algorithm3,key);
        System.out.println("HmacMD5:" + hexStr1);
        System.out.println("HmacMD5:" + hexStr2);
        System.out.println("HmacMD5:" + hexStr3);

        String hmacMD5HexStr = new HmacUtils(HmacAlgorithms.HMAC_MD5,key.getBytes(UTF8)).hmacHex(str.getBytes(UTF8));
        String hmacSHA256HexStr = new HmacUtils(HmacAlgorithms.HMAC_SHA_256,key.getBytes(UTF8)).hmacHex(str.getBytes(UTF8));
        String hmacSHA512HexStr = new HmacUtils(HmacAlgorithms.HMAC_SHA_512,key.getBytes(UTF8)).hmacHex(str.getBytes(UTF8));
        System.out.println("hmacMD5HexStr:"+ hmacMD5HexStr);
        System.out.println("hmacSHA256HexStr:"+ hmacSHA256HexStr);
        System.out.println("hmacSHA512HexStr:"+ hmacSHA512HexStr);
    }
}

结果: 

6、对称加密

也叫单秘钥加密。所谓单秘钥,指的是加密和解密的过程使用相同的密钥,相比非对称加密,因只有一把钥匙,因而速度更快,更适合加解密大文件。

DES : data encryption standard,已经过时

AES : advanced encryption standard,替代des。
 

DES:使用Base64加密

public class DesTest {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    private static final String KEY = "12345678";
    //加密模式
    private static final String ALGORITHM = "DES";

    /**
     * 加密
     * @param text 加密内容
     * @return
     */
    public static String encrypt(String text) throws Exception {
        //获取示例
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        //创建加密规则
        SecretKey secretKey = new SecretKeySpec(KEY.getBytes(UTF8), ALGORITHM);
        //加密模式规则
        cipher.init(Cipher.ENCRYPT_MODE,secretKey);
        byte[] bytes = cipher.doFinal(text.getBytes(UTF8));
        //1,使用Base64 2,转成16进制
        return Base64.encodeBase64String(bytes);
    }

    /**
     *  解密
     * @param encodedText 加密后的字符串
     * @return
     * @throws Exception
     */
    public static String decrypt(String encodedText) throws Exception {
        //获取示例
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        //创建加密规则
        SecretKey secretKey = new SecretKeySpec(KEY.getBytes(UTF8), ALGORITHM);
        //加密模式规则
        cipher.init(Cipher.DECRYPT_MODE,secretKey);
        byte[] bytes = cipher.doFinal(Base64.decodeBase64(encodedText.getBytes(UTF8)));
        //1,使用Base64
        return new String(bytes,UTF8);
    }

    public static void main(String[] args) throws Exception {
         String str = "张三写java";
        //加密
        String encodedText = encrypt(str);
        System.out.println("base64编码加密后的结果"+encodedText);
        //解密
        String decrypt = decrypt(encodedText);
        System.out.println("des解密后的结果"+decrypt);
    }
}

结果:

 AES:16进制加密模式

public class AesTest {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    //aes默认key的长度 16,24,32位
    private static final String KEY = "12345678abcdefgh";
    //加密模式
    private static final String ALGORITHM = "AES";

    /**
     * 加密
     * @param text 加密内容
     * @return
     */
    public static String encrypt(String text) throws Exception {
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, KEY);
        byte[] bytes = cipher.doFinal(text.getBytes(UTF8));
        //转成16进制
        return HexUtils.converBytes(bytes);
    }

    /**
     *  解密
     * @param encodedText 16进制编码后的字符串
     * @return
     * @throws Exception
     */
    public static String decrypt(String encodedText) throws Exception {
        byte[] bytes = HexUtils.converHex2Bytes(encodedText);
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE, KEY);
        byte[] decryptedBytes = cipher.doFinal(bytes);
        //2,转成16进制
        return new String(decryptedBytes,UTF8);
    }

    /**
     * 获取Cipher对象
     * @param type 加密解密模式
     * @param seed 密钥
     * @return
     * @throws Exception
     */
    public static Cipher getCipher(int type,String seed) throws Exception{
        //获取示例
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        //创建加密规则
        SecretKey secretKey = new SecretKeySpec(seed.getBytes(UTF8), ALGORITHM);
        //加密模式规则
        cipher.init(type,secretKey);

        return cipher;
    }

    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        //加密
        String encodedText = encrypt(str);
        System.out.println("16进制编码aes加密后的结果"+encodedText);
        //解密
        String decrypt = decrypt(encodedText);
        System.out.println("aes解密后的结果"+decrypt);
    }
}

 

AES:16进制加密模式代码优化

public class AesTest {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    //aes默认key的长度 16,24,32位
    private static final String KEY = "12345678";
    //加密模式
    private static final String ALGORITHM = "AES";

    /**
     * 加密
     * @param text 加密内容
     * @return
     */
    public static String encrypt(String text) throws Exception {
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, KEY);
        byte[] bytes = cipher.doFinal(text.getBytes(UTF8));
        //转成16进制
        return HexUtils.converBytes(bytes);
    }

    /**
     *  解密
     * @param encodedText 16进制编码后的字符串
     * @return
     * @throws Exception
     */
    public static String decrypt(String encodedText) throws Exception {
        byte[] bytes = HexUtils.converHex2Bytes(encodedText);
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE, KEY);
        byte[] decryptedBytes = cipher.doFinal(bytes);
        //2,转成16进制
        return new String(decryptedBytes,UTF8);
    }

    /**
     * 获取Cipher对象
     * @param type 加密解密模式
     * @param seed 密钥
     * @return
     * @throws Exception
     */
    public static Cipher getCipher(int type,String seed) throws Exception{
        //获取示例
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        //创建加密规则
        //创建keyGenerator对象,可以根据传入的key生成一个指定长度的key
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        //初始化secureRandom,并指定生成指定长度key的算法
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(seed.getBytes(UTF8));
        keyGenerator.init(128,secureRandom);
        //通过keyGenerator生成新的秘钥
        SecretKey secretKey = keyGenerator.generateKey();
        //获取到新秘钥的字节数组
        byte[] encoded = secretKey.getEncoded();
        SecretKeySpec secretKeySpec = new SecretKeySpec(encoded, ALGORITHM);

        //加密模式规则
        cipher.init(type,secretKeySpec);

        return cipher;
    }

    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        //加密
        String encodedText = encrypt(str);
        System.out.println("16进制编码aes加密后的结果"+encodedText);
        //解密
        String decrypt = decrypt(encodedText);
        System.out.println("aes解密后的结果"+decrypt);
    }
}

AES:base64加密模式 

public class AesBase64Test {
    //设置编码格式
    private static final String UTF8 = StandardCharsets.UTF_8.name();
    private static final String KEY = "12345678";
    //加密模式
    private static final String ALGORITHM = "AES";

    /**
     * 加密
     * @param text 加密内容
     * @return
     */
    public static String encrypt(String text) throws Exception {
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, KEY);
        byte[] bytes = cipher.doFinal(text.getBytes(UTF8));
        //1,使用Base64 2,转成16进制
        return Base64.encodeBase64String(bytes);
    }

    /**
     *  解密
     * @param encodedText 加密后的字符串
     * @return
     * @throws Exception
     */
    public static String decrypt(String encodedText) throws Exception {
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE, KEY);
        byte[] bytes = cipher.doFinal(Base64.decodeBase64(encodedText.getBytes(UTF8)));
        //1,使用Base64 2,转成16进制
        return new String(bytes,UTF8);
    }

    public static Cipher getCipher(int type,String seed) throws Exception{
        //获取示例
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        //创建加密规则
        //创建keyGenerator对象,可以根据传入的key生成一个指定长度的key
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        //初始化secureRandom,并指定生成指定长度key的算法
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(seed.getBytes(UTF8));
        keyGenerator.init(128,secureRandom);
        //通过keyGenerator生成新的秘钥
        SecretKey secretKey = keyGenerator.generateKey();
        //获取到新秘钥的字节数组
        byte[] encoded = secretKey.getEncoded();
        SecretKeySpec secretKeySpec = new SecretKeySpec(encoded, ALGORITHM);

        //加密模式规则
        cipher.init(type,secretKeySpec);

        return cipher;
    }

    /**
     * 测试
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        String str = "张三写java";
        //加密
        String encodedText = encrypt(str);
        System.out.println("base64编码aes加密后的结果" + encodedText);
        //解密
        String decrypt = decrypt(encodedText);
        System.out.println("aes解密后的结果" + decrypt);
    }
}

7、非对称加密

定义:加密和解密使用的是两个不同的密钥(public key和private key).公钥可以给任何人,私钥总

是自己保留。

常见算法:RSA

应用场景:

1、加解密:可以使用公钥加密,对应的就是私钥解密;也可以使用私钥加密,对应的就是公钥解

密。

public class RSATest2 {
    public static final String CHARSET = "UTF-8";
    public static final String RSA_ALGORITHM = "RSA";

    //生成密钥对,一般来说执行一次就行
    public static Map<String, String> createKeys(int keySize) {
        //为RSA算法创建一个KeyPairGenerator对象(KeyPairGenerator,密钥对生成器,用于生成公钥和私钥对)
        KeyPairGenerator kpg;
        try {
            kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
        }

        //初始化KeyPairGenerator对象,密钥长度
        kpg.initialize(keySize);
        //生成密匙对
        KeyPair keyPair = kpg.generateKeyPair();
        //得到公钥
        Key publicKey = keyPair.getPublic();
        String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded()); //返回一个publicKey经过二次加密后的字符串
        //得到私钥
        Key privateKey = keyPair.getPrivate();
        String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded()); //返回一个privateKey经过二次加密后的字符串

        Map<String, String> keyPairMap = new HashMap<String, String>();
        keyPairMap.put("publicKey", publicKeyStr);
        keyPairMap.put("privateKey", privateKeyStr);

        return keyPairMap;
    }

    /**
     * 得到公钥
     *
     * @param publicKey 密钥字符串(经过base64编码)
     * @throws Exception
     */
    public static RSAPublicKey getPublicKey(String publicKey) throws Exception {
        //通过X509编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    }

    /**
     * 得到私钥
     *
     * @param privateKey 密钥字符串(经过base64编码)
     * @throws Exception
     */
    public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception {
        //通过PKCS#8编码的Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        return key;
    }

    /**
     * 公钥加密
     *
     * @param data
     * @param publicKey
     * @return
     */
    public static String publicEncrypt(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥解密
     *
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateDecrypt(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥加密
     *
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateEncrypt(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 公钥解密
     *
     * @param data
     * @param publicKey
     * @return
     */

    public static String publicDecrypt(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
        int maxBlock = 0;
        if (opmode == Cipher.DECRYPT_MODE) {
            maxBlock = keySize / 8;
        } else {
            maxBlock = keySize / 8 - 11;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        try {
            while (datas.length > offSet) {
                if (datas.length - offSet > maxBlock) {
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                } else {
                    buff = cipher.doFinal(datas, offSet, datas.length - offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
        } catch (Exception e) {
            throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
        }
        byte[] resultDatas = out.toByteArray();
        IOUtils.closeQuietly(out);
        return resultDatas;
    }



    //测试
    public static void main(String[] args) throws Exception {
        //生成公私钥
        Map<String, String> keyMap = RSATest2.createKeys(512);
        //公钥
        String publicKey = keyMap.get("publicKey");
        
        //私钥
        String privateKey = keyMap.get("privateKey");


        System.out.println("公钥加密——私钥解密");
        String str = "法外狂徒张三";
        System.out.println("明文:" + str);
        System.out.println("明文大小:" + str.getBytes().length);
        //对内容进行公钥加密
        String encodedData = RSATest2.publicEncrypt(str, RSATest2.getPublicKey(publicKey));
        System.out.println("公钥加密密文:" + encodedData);
        //用私钥对密文进行解密

        String decodedData = RSATest2.privateDecrypt(encodedData, RSATest2.getPrivateKey(privateKey));
        System.out.println("解密后文字: " + decodedData);
    }

}

2、数字签名

3、数字信封

4、数字证书

参考视频:密码学-java信息安全,摘要算法,对称加密(AES)/非对称加密(RSA),一应俱全_哔哩哔哩_bilibili

非对称加密参考:java实现非对称加密(RSA)_qq_1473179505的博客-CSDN博客

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
非对称加密算法在Java中有多种实现,其中最常用的是RSA算法。Java提供了内置的RSA算法库,可以方便地使用公钥加密和私钥解密,或者使用私钥签名和公钥验证签名。 要在Java中使用RSA算法进行非对称加密,可以按照以下步骤进行: 1. 生成RSA密钥对:使用`KeyPairGenerator`类生成一个RSA密钥对,其中包含公钥和私钥。 2. 获取公钥和私钥:从生成的密钥对中获取公钥和私钥,分别用于加密和解密。 3. 使用公钥加密:使用公钥对要加密的数据进行加密,可以使用`Cipher`类来进行加密操作。 4. 使用私钥解密:使用私钥对加密后的数据进行解密,同样可以使用`Cipher`类来进行解密操作。 以下是一个简单的示例代码,演示了如何在Java中使用RSA算法进行非对称加密: ```java import java.security.*; import javax.crypto.Cipher; public class RSAEncryptionExample { public static void main(String[] args) throws Exception { // 1. 生成RSA密钥对 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // 2. 获取公钥和私钥 PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); // 3. 使用公钥加密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedData = cipher.doFinal("Hello, World!".getBytes()); // 4. 使用私钥解密 cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedData = cipher.doFinal(encryptedData); // 打印加密后和解密后的数据 System.out.println("加密后的数据:" + new String(encryptedData)); System.out.println("解密后的数据:" + new String(decryptedData)); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值