Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java des加密

作者:—只賣身不賣藝   发布日期:2026-04-30   浏览:122

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class DESUtil {

    private static final String ALGORITHM = "DES";

    // 生成密钥
    public static String generateKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
        keyGen.init(56); // DES 密钥长度为 56 位
        SecretKey secretKey = keyGen.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    // 加密
    public static String encrypt(String data, String key) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(key);
        SecretKey secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedData = cipher.doFinal(data.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    // 解密
    public static String decrypt(String encryptedData, String key) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(key);
        SecretKey secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedData = cipher.doFinal(decodedData);
        return new String(decryptedData, "UTF-8");
    }

    public static void main(String[] args) {
        try {
            // 生成密钥
            String key = generateKey();
            System.out.println("Generated Key: " + key);

            // 原始数据
            String originalData = "Hello, DES!";
            System.out.println("Original Data: " + originalData);

            // 加密数据
            String encryptedData = encrypt(originalData, key);
            System.out.println("Encrypted Data: " + encryptedData);

            // 解密数据
            String decryptedData = decrypt(encryptedData, key);
            System.out.println("Decrypted Data: " + decryptedData);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

解释说明:

  1. 生成密钥:使用 KeyGenerator 生成一个 DES 算法的密钥,并将其编码为 Base64 字符串以便存储和传输。
  2. 加密:使用生成的密钥对输入的数据进行加密。加密后的数据也会被编码为 Base64 字符串。
  3. 解密:使用相同的密钥对加密后的数据进行解密,恢复原始数据。
  4. 主函数:演示了如何生成密钥、加密和解密数据。

此代码展示了如何在 Java 中使用 DES 算法进行加密和解密操作。

上一篇:java hibernate

下一篇:java打印数组

大家都在看

java url decode

java判断是windows还是linux

java连接数据库的代码

java date类型比较大小

java djl

ubuntu 卸载java

es java api

java list 查找

java 解压rar

jsonobject.tojavaobje

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站