Java加密算法

本文介绍了Java中常见的四种加密技术:MD5用于简单数据哈希,Bcrypt提供不可逆加密且每次加密结果不同,增强安全性;AES实现对称加密,适合大量数据加密;RSA则采用非对称加密,适用于公钥/私钥场景,确保数据传输安全。通过示例代码展示了如何使用这些加密算法。
摘要由CSDN通过智能技术生成

MD5加密

/**
 * @author @全体人员
 * @nickname Tim
 * @date 2022-09-23 10:21:03
 */
public class Md5Util {
    private Md5Util(){}

    public static String digest(String str){
        try {
            MessageDigest m=MessageDigest.getInstance("MD5");
            byte[] bytes=m.digest(str.getBytes("utf-8"));
            String result=new BigInteger(1,bytes).toString(16);
            return result;
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
             throw new RuntimeException(e);
        }
    }

    public static boolean isEqueal(String input,String md5String){
        return digest(input).equals(md5String);
    }
}
Bcrypt加密

每次相同字符串的加密结果不一样,能防止暴力破解。

导入依赖

<dependency>
     <groupId>org.mindrot</groupId>
     <artifactId>jbcrypt</artifactId>
     <version>0.4</version>
</dependency>
import org.mindrot.jbcrypt.BCrypt;

/**
 * @author @全体人员
 * @nickname Tim
 * @date 2022-09-23 10:31:38
 */
public class BcryptTest {
    public static void main(String[] args) {
        String str="zxhjjb m,";
        String hashpw = BCrypt.hashpw(str, BCrypt.gensalt());
        //密文
        System.out.println(hashpw);
        //对比
        boolean checkpw = BCrypt.checkpw("zxhjjb m,",hashpw);
        System.out.println(checkpw);
    }
}

AES加密(对称加密)

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * @author @全体人员
 * @nickname Tim
 * @date 2022-09-23 10:53:41
 */
public class AESUtil {
    public static String AESEncode(String encodeRules,String content){
        try {
            KeyGenerator keygen=KeyGenerator.getInstance("AES");
            keygen.init(128, new SecureRandom(encodeRules.getBytes()));
            SecretKey original_key=keygen.generateKey();
            byte [] raw=original_key.getEncoded();
            SecretKey key=new SecretKeySpec(raw, "AES");
            Cipher cipher=Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte [] byte_encode=content.getBytes("utf-8");
            byte [] byte_AES=cipher.doFinal(byte_encode);
            String AES_encode=new String(new BASE64Encoder().encode(byte_AES));
            return AES_encode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String AESDncode(String encodeRules,String content){
        try {
            KeyGenerator keygen=KeyGenerator.getInstance("AES");
            keygen.init(128, new SecureRandom(encodeRules.getBytes()));
            SecretKey original_key=keygen.generateKey();
            byte [] raw=original_key.getEncoded();
            SecretKey key=new SecretKeySpec(raw, "AES");
            Cipher cipher=Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte [] byte_content= new BASE64Decoder().decodeBuffer(content);
            byte [] byte_decode=cipher.doFinal(byte_content);
            String AES_decode=new String(byte_decode,"utf-8");
            return AES_decode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        //需要加密的字符串
        String str="tdfyghkjl";
        //密钥
        String rules="12345678";
        String str1=AESEncode(rules,str);
        String str2=AESDncode(rules,str1);
        System.out.println("加密密文:"+str1);
        System.out.println("解密结果:"+str2);
    }
}

ASE非对称加密

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk16</artifactId>
    <version>1.46</version>
</dependency>
package com.lin.rabbit.test;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import java.io.*;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @author @全体人员
 * @nickname Tim
 * @date 2022-09-23 13:08:04
 */
public class RsaUtil {

    public static KeyPair generateKeyPair() throws Exception {
        //获取一对钥匙
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        KeyPair keyPair = keyGen.generateKeyPair();
        return keyPair;
    }

    public static void createAndSaveKeys(String publicPath,String privatePath) throws Exception {
        //创建密钥对并保存成文件
        KeyPair keys= generateKeyPair();
        FileOutputStream pubOut=new FileOutputStream(publicPath);
        pubOut.write(Base64.getEncoder().encode(keys.getPublic().getEncoded()));
        pubOut.flush();
        pubOut.close();
        FileOutputStream priOut=new FileOutputStream(privatePath);
        priOut.write(Base64.getEncoder().encode(keys.getPrivate().getEncoded()));
        priOut.flush();
        priOut.close();
    }

    public static PublicKey loadPublicKey(String publicPath) throws Exception {
        //加载文件转换成公钥对象
        System.out.println(publicPath);
        FileInputStream pubIn=new FileInputStream(publicPath);
        byte[] byteData=new byte[pubIn.available()];
        pubIn.read(byteData);
        pubIn.close();
        String publicKeyBase64=new String(byteData);
        return convertPublicKey(publicKeyBase64);
    }

    public static PublicKey convertPublicKey(String publicKeyBase64) throws Exception {
        //字符串转换成公钥对象
        byte[] bytes=Base64.getDecoder().decode(publicKeyBase64);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA",new BouncyCastleProvider());
        X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(bytes);
        PublicKey publicKey = keyFactory.generatePublic(bobPubKeySpec);
        return publicKey;
    }

    public static PrivateKey loadPrivateKey(String privateKey) throws Exception {
        //加载文件转换成私钥对象
        FileInputStream priIn=new FileInputStream(privateKey);
        byte[] byteData=new byte[priIn.available()];
        priIn.read(byteData);
        priIn.close();
        String publicKeyBase64=new String(byteData);
        return convertPrivateKey(publicKeyBase64);
    }

    public static PrivateKey convertPrivateKey(String privateKeyBase64) throws Exception {
        //字符串转换成私钥对象
        byte[] bytes=Base64.getDecoder().decode(privateKeyBase64);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA",new BouncyCastleProvider());
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(bytes);
        PrivateKey privateKey = keyFactory.generatePrivate(priPKCS8);
        return privateKey;
    }

    public static byte[] encrypt(byte[] originalBytes,Key key) throws Exception {
        //加密 公钥加密私钥解
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] cipherBytes = cipher.doFinal(originalBytes);
        return cipherBytes;
    }

    public static String encrypt(String content,Key key) throws Exception {
        byte[] originalBytes=content.getBytes("utf-8");
        return Base64.getEncoder().encodeToString(encrypt(originalBytes,key));
    }

    public static String encrypt(String content,String privateKeyBase64) throws Exception {
        byte[] originalBytes=content.getBytes("utf-8");
        return Base64.getEncoder().encodeToString(encrypt(originalBytes,RsaUtil.loadPrivateKey(privateKeyBase64)));
    }

    public static String encrypt(String content,String keyBase64,boolean publicKey) throws Exception {
        byte[] originalBytes=content.getBytes("utf-8");
        if(publicKey){
            return Base64.getEncoder().encodeToString(encrypt(originalBytes,RsaUtil.loadPublicKey(keyBase64)));
        }
        return Base64.getEncoder().encodeToString(encrypt(originalBytes,RsaUtil.loadPrivateKey(keyBase64)));
    }


    public static byte[] decrypt(byte[] cipherBytes, Key key) throws Exception {
        //解密 公钥加密私钥解
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE,key);
        byte[] originalBytes = cipher.doFinal(cipherBytes);
        return originalBytes;
    }

    public static String decrypt(String content, Key key) throws Exception {
        byte[] originalBytes=Base64.getDecoder().decode(content.getBytes());
        return new String(decrypt(originalBytes,key));
    }

    public static String decrypt(String content,String publicKeyBase64) throws Exception {
        byte[] originalBytes=Base64.getDecoder().decode(content.getBytes());
        return new String(decrypt(originalBytes,RsaUtil.loadPublicKey(publicKeyBase64)));
    }

    public static String decrypt(String content,String keyBase64,boolean publicKey) throws Exception {
        byte[] originalBytes=Base64.getDecoder().decode(content.getBytes());
        if(publicKey){
            return new String(decrypt(originalBytes,RsaUtil.loadPublicKey(keyBase64)));
        }
        return new String(decrypt(originalBytes,RsaUtil.loadPrivateKey(keyBase64)));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值