Userjava把字符串用DES方式加密,解密

在 Java 中,你可以使用 javax.crypto 包提供的 Cipher 类来进行 DES 加密和解密。下面是一个简单的示例:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;

public class DesExample {

    public static void main(String[] args) {
        try {
            // 1. 指定密钥
            String keyString = "yourSecretKey"; // 替换为你的密钥,长度必须是8个字符
            Key secretKey = generateKey(keyString);

            // 2. 创建 Cipher 实例
            Cipher cipher = Cipher.getInstance("DES");

            // 3. 加密
            String plaintext = "Hello, DES!";
            byte[] encryptedBytes = encrypt(plaintext, secretKey, cipher);
            System.out.println("Encrypted: " + bytesToHex(encryptedBytes));

            // 4. 解密
            String decryptedText = decrypt(encryptedBytes, secretKey, cipher);
            System.out.println("Decrypted: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Key generateKey(String keyString) throws Exception {
        DESKeySpec desKeySpec = new DESKeySpec(keyString.getBytes(StandardCharsets.UTF_8));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        return keyFactory.generateSecret(desKeySpec);
    }

    private static byte[] encrypt(String plaintext, Key secretKey, Cipher cipher) throws Exception {
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
    }

    private static String decrypt(byte[] ciphertext, Key secretKey, Cipher cipher) throws Exception {
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(ciphertext);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte aByte : bytes) {
            result.append(String.format("%02X ", aByte));
        }
        return result.toString().trim();
    }
}

在上述代码中,请将 yourSecretKey 替换为你的 8 字符密钥。这个例子中使用了 DES 加密算法,但需要注意 DES 已经被认为是不安全的,推荐使用更强大的算法,如 AES。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值