欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java中常用文本加解密工具類(lèi)總結(jié)

 更新時(shí)間:2024年11月15日 08:21:34   作者:一線大碼  
這篇文章主要為大家詳細(xì)介紹了Java中常用的幾種文本加解密工具類(lèi),包括AES對(duì)稱加密、RSA非對(duì)稱加密、哈希算法加密和Base64編解碼,需要的可以參考下

1. AES 對(duì)稱加解密

package com.example.demo.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * AES對(duì)稱加密
 *
 * @author wangbo
 * @date 2024/11/14
 */
public class AesUtil {

    private AesUtil() {
    }

    /**
     * 生成AES密鑰
     *
     * @param password 加密密碼
     * @return 密鑰
     * @throws NoSuchAlgorithmException 密鑰生成算法不支持異常
     */
    private static SecretKey generateAesKey(String password) throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        byte[] passwordBytes = password.getBytes(StandardCharsets.UTF_8);
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] keyBytes = digest.digest(passwordBytes);
        return new SecretKeySpec(keyBytes, "AES");
    }

    /**
     * 對(duì)稱加密算法AES加密
     *
     * @param plaintext 待加密文本
     * @param password  加密密碼
     * @return 加密后的密文
     * @throws Exception 加密異常
     */
    public static String encryptWithAes(String plaintext, String password) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        SecretKey secretKey = generateAesKey(password);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 對(duì)稱加密算法AES解密
     *
     * @param ciphertext 加密后的密文
     * @param password   加密密碼
     * @return 解密后的明文
     * @throws Exception 解密異常
     */
    public static String decryptWithAes(String ciphertext, String password) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        SecretKey secretKey = generateAesKey(password);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws Exception {
        // AES 對(duì)稱加密示例
        String plaintext = "Hello, world!";
        String password = "secretPassword";
        // AES 加密
        String encryptWithAes = encryptWithAes(plaintext, password);
        System.out.println("AES Encrypted: " + encryptWithAes);
        // AES 解密
        String decryptWithAes = decryptWithAes(encryptWithAes, password);
        System.out.println("AES Decrypted: " + decryptWithAes);
    }
}

2. RSA 非對(duì)稱加解密

package com.example.demo.util;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * RSA非對(duì)稱加密
 *
 * @author wangbo
 * @date 2024/11/14
 */
public class RsaUtil {

    private RsaUtil() {
    }

    /**
     * 生成RSA密鑰對(duì)
     *
     * @return 密鑰對(duì)
     * @throws NoSuchAlgorithmException 密鑰生成算法不支持異常
     */
    public static KeyPair generateRsaKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        return keyPairGenerator.generateKeyPair();
    }

    /**
     * 獲取RSA公鑰的Base64編碼字符串
     *
     * @return RSA公鑰Base64編碼字符串
     */
    public static String getRsaPublicKeyString(PublicKey publicKey) {
        KeyFactory keyFactory;
        try {
            keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
            return Base64.getEncoder().encodeToString(keyFactory.generatePublic(publicKeySpec).getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根據(jù)Base64編碼的字符串還原為RSA公鑰
     *
     * @param publicKeyString RSA公鑰Base64編碼字符串
     * @return RSA公鑰
     */
    public static PublicKey getPublicKey(String publicKeyString) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyString));
            return keyFactory.generatePublic(publicKeySpec);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 獲取RSA私鑰的Base64編碼字符串
     *
     * @return RSA私鑰Base64編碼字符串
     */
    public static String getRsaPrivateKeyString(PrivateKey privateKey) {
        KeyFactory keyFactory;
        try {
            keyFactory = KeyFactory.getInstance("RSA");
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
            return Base64.getEncoder().encodeToString(keyFactory.generatePrivate(privateKeySpec).getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根據(jù)Base64編碼的字符串還原為RSA私鑰
     *
     * @param privateKeyString RSA私鑰Base64編碼字符串
     * @return RSA私鑰
     */
    public static PrivateKey getPrivateKey(String privateKeyString) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyString));
            return keyFactory.generatePrivate(privateKeySpec);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 非對(duì)稱加密算法RSA加密
     *
     * @param plaintext 明文
     * @param publicKey 公鑰
     * @return 加密后的密文
     * @throws Exception 加密異常
     */
    public static String encryptWithRsa(String plaintext, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 非對(duì)稱加密算法RSA解密
     *
     * @param ciphertext 密文
     * @param privateKey 私鑰
     * @return 解密后的明文
     * @throws Exception 解密異常
     */
    public static String decryptWithRsa(String ciphertext, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws Exception {
        //RSA非對(duì)稱加密示例
        String plaintext = "Hello, RSA!";
        //生成RSA密鑰對(duì)
        KeyPair keyPair = generateRsaKeyPair();
        //公鑰字符串獲取
        String publicKeyString = getRsaPublicKeyString(keyPair.getPublic());
        System.out.println("RSA publicKeyString: " + publicKeyString);
        //公鑰還原
        PublicKey publicKey = getPublicKey(publicKeyString);
        //私鑰字符串獲取
        String privateKeyString = getRsaPrivateKeyString(keyPair.getPrivate());
        System.out.println("RSA privateKeyString: " + privateKeyString);
        //私鑰還原
        PrivateKey privateKey = getPrivateKey(privateKeyString);
        // RSA公鑰加密
        String encryptedRSA = encryptWithRsa(plaintext, publicKey);
        System.out.println("RSA Encrypted: " + encryptedRSA);
        // RSA私鑰解密
        String decryptedRSA = decryptWithRsa(encryptedRSA, privateKey);
        System.out.println("RSA Decrypted: " + decryptedRSA);
    }
}

3. 哈希算法加密

package com.example.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 哈希算法加密
 *
 * @author wangbo
 * @date 2024/11/14
 */
@Slf4j
public class HashUtil {

    private HashUtil() {
    }

    /**
     * 哈希算法SHA-256
     *
     * @param plaintext 明文
     * @return 哈希值
     * @throws NoSuchAlgorithmException 哈希算法不支持異常
     */
    public static String hashWithSha256(String plaintext) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hashBytes = digest.digest(plaintext.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(hashBytes);
    }

    /**
     * 將字節(jié)數(shù)組轉(zhuǎn)換為十六進(jìn)制字符串
     *
     * @param bytes 字節(jié)數(shù)組
     * @return 十六進(jìn)制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * SHA密碼加密
     *
     * @param sourceStr 源字符串
     * @return 加密字符串
     */
    public static String sha(String sourceStr) {
        try {
            MessageDigest sha = MessageDigest.getInstance("SHA");
            sha.update(sourceStr.getBytes(StandardCharsets.UTF_8));
            return new BigInteger(1, sha.digest()).toString(32);
        } catch (NoSuchAlgorithmException e) {
            log.error("SHA字符串加密異常", e);
            return null;
        }
    }

    /**
     * MD5密碼加密
     *
     * @param sourceStr 源字符串
     * @return 加密字符串
     */
    public static String md5(String sourceStr) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(sourceStr.getBytes(StandardCharsets.UTF_8));
            return new BigInteger(1, md5.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            log.error("MD5字符串加密異常", e);
            return null;
        }
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String plaintext = "Hello Hash!";
        String hashValue = hashWithSha256(plaintext);
        System.out.println("SHA-256 Hash: " + hashValue);
        String sha = sha(plaintext);
        System.out.println("SHA: " + sha);
        String md5 = md5(plaintext);
        System.out.println("MD5: " + md5);
        //spring的工具類(lèi)進(jìn)行MD5加密
        String md5Spring = DigestUtils.md5DigestAsHex(plaintext.getBytes(StandardCharsets.UTF_8));
        System.out.println("MD5Spring: " + md5Spring);
        //commons-codec的工具類(lèi)進(jìn)行MD5加密
        String md5Commons = org.apache.commons.codec.digest.DigestUtils.md5Hex(plaintext);
        System.out.println("MD5Commons: " + md5Commons);
    }
}

如果使用 commons-codec 的工具類(lèi)進(jìn)行 MD5 加密,可能需要引入下面的依賴:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>${commons.codec.version}</version>
</dependency>

4. Base64 編解碼

package com.example.demo.util;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * Base64
 *
 * @author wangbo
 * @date 2024/11/14
 */
public class Base64Util {

    private Base64Util() {
    }

    /**
     * Base64 編碼
     *
     * @param plainText 內(nèi)容
     * @return 十六進(jìn)制字符串
     */
    public static String encodeBase64(String plainText) {
        byte[] plainBytes = plainText.getBytes(StandardCharsets.UTF_8);
        return Base64.getEncoder().encodeToString(plainBytes);
    }

    /**
     * Base64 解碼
     *
     * @param base64Text 十六進(jìn)制字符串
     * @return 內(nèi)容
     */
    public static String decodeBase64(String base64Text) {
        byte[] base64Bytes = Base64.getDecoder().decode(base64Text);
        return new String(base64Bytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        // Base64 編碼
        String base64Text = Base64Util.encodeBase64("Hello Base64!");
        System.out.println("Base64 Encoded: " + base64Text);
        // Base64 解碼
        String decodedText = Base64Util.decodeBase64(base64Text);
        System.out.println("Base64 Decoded: " + decodedText);
    }
}

到此這篇關(guān)于Java中常用文本加解密工具類(lèi)總結(jié)的文章就介紹到這了,更多相關(guān)Java加解密工具類(lèi)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java實(shí)戰(zhàn)項(xiàng)目之記賬軟件

    java實(shí)戰(zhàn)項(xiàng)目之記賬軟件

    這篇文章主要介紹了java實(shí)戰(zhàn)項(xiàng)目之記賬軟件,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-04-04
  • 淺談mybatis mapper.xml文件中$和#的區(qū)別

    淺談mybatis mapper.xml文件中$和#的區(qū)別

    這篇文章主要介紹了淺談mybatis mapper.xml文件中$和#的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-11-11
  • SpringBoot+thymeleaf+Echarts+Mysql 實(shí)現(xiàn)數(shù)據(jù)可視化讀取的示例

    SpringBoot+thymeleaf+Echarts+Mysql 實(shí)現(xiàn)數(shù)據(jù)可視化讀取的示例

    本文主要介紹了SpringBoot+thymeleaf+Echarts+Mysql 實(shí)現(xiàn)數(shù)據(jù)可視化讀取的示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-04-04
  • Java常見(jiàn)問(wèn)題之javac Hello.java找不到文件的解決方法

    Java常見(jiàn)問(wèn)題之javac Hello.java找不到文件的解決方法

    剛開(kāi)始編寫(xiě)java代碼時(shí),肯定會(huì)遇到各種各樣的bug,當(dāng)然對(duì)于初學(xué)者這也是能理解的,下面這篇文章主要給大家介紹了關(guān)于Java常見(jiàn)問(wèn)題之javac Hello.java找不到文件解決的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下。
    2018-01-01
  • 一文詳解Java項(xiàng)目中如何優(yōu)雅的使用枚舉類(lèi)型

    一文詳解Java項(xiàng)目中如何優(yōu)雅的使用枚舉類(lèi)型

    枚舉類(lèi)型在開(kāi)發(fā)中是很常見(jiàn)的,有非常多的應(yīng)用場(chǎng)景,這篇文章我們就來(lái)學(xué)習(xí)一下項(xiàng)目中如何優(yōu)雅的使用枚舉類(lèi)型,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-03-03
  • Java hashCode() 方法詳細(xì)解讀

    Java hashCode() 方法詳細(xì)解讀

    Java.lang.Object 有一個(gè)hashCode()和一個(gè)equals()方法,這兩個(gè)方法在軟件設(shè)計(jì)中扮演著舉足輕重的角色,本文對(duì)hashCode()方法深入理解,希望能幫助大家
    2016-07-07
  • 解決cmd執(zhí)行javac報(bào)錯(cuò):不是內(nèi)部或外部命令,也不是可運(yùn)行的程序

    解決cmd執(zhí)行javac報(bào)錯(cuò):不是內(nèi)部或外部命令,也不是可運(yùn)行的程序

    剛接觸JAVA的新手可能就不知道怎么解決'JAVAC'不是內(nèi)部命令或外部命令,這篇文章主要給大家介紹了關(guān)于解決cmd執(zhí)行javac報(bào)錯(cuò):不是內(nèi)部或外部命令,也不是可運(yùn)行的程序的相關(guān)資料,需要的朋友可以參考下
    2023-11-11
  • Spring內(nèi)置定時(shí)任務(wù)調(diào)度@Scheduled使用詳解

    Spring內(nèi)置定時(shí)任務(wù)調(diào)度@Scheduled使用詳解

    這篇文章主要介紹了Spring內(nèi)置定時(shí)任務(wù)調(diào)度@Scheduled使用詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-12-12
  • SpringBoot實(shí)現(xiàn)動(dòng)態(tài)配置及項(xiàng)目打包部署上線功能

    SpringBoot實(shí)現(xiàn)動(dòng)態(tài)配置及項(xiàng)目打包部署上線功能

    本文講解的是如何使用Spring動(dòng)態(tài)配置文件,實(shí)現(xiàn)不同環(huán)境不同配置,靈活切換配置文件;以及講述了如何使用?Maven?打包,然后上傳至Linux服務(wù)器進(jìn)行部署,對(duì)SpringBoot打包部署上線過(guò)程感興趣的朋友一起看看吧
    2022-10-10
  • SpringMVC使用第三方組件實(shí)現(xiàn)文件上傳

    SpringMVC使用第三方組件實(shí)現(xiàn)文件上傳

    這篇文章主要介紹了SpringMVC使用第三方組件實(shí)現(xiàn)文件上傳,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08

最新評(píng)論