DES3是一种对称加密算法,即加密和解密使用相同的密钥。它的密钥长度为24字节(192位),比DES的56位密钥强大得多。以下是一个Java实现的示例。

加密方法:

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

public class DES3Util {

    private static final String ENCRYPTION_ALGORITHM = "DESede"; // 加密算法

    /**
     * 3DES加密
     *
     * @param plainText 明文
     * @param secretKey 密钥,长度必须为24字节
     * @return 密文
     */
    public static String encrypt(String plainText, String secretKey) throws Exception {
        byte[] keyBytes = secretKey.getBytes("UTF-8");
        SecretKey desKey = new SecretKeySpec(keyBytes, ENCRYPTION_ALGORITHM);
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, desKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

}

解密方法:

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

public class DES3Util {

    private static final String ENCRYPTION_ALGORITHM = "DESede"; // 加密算法

    /**
     * 3DES解密
     *
     * @param encryptedText 密文
     * @param secretKey 密钥,长度必须为24字节
     * @return 明文
     */
    public static String decrypt(String encryptedText, String secretKey) throws Exception {
        byte[] keyBytes = secretKey.getBytes("UTF-8");
        SecretKey desKey = new SecretKeySpec(keyBytes, ENCRYPTION_ALGORITHM);
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, desKey);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }

}

使用示例:

public class Main {
    public static void main(String[] args) throws Exception {
        String plainText = "hello world";
        String secretKey = "123456789012345678901234";
        String encryptedText = DES3Util.encrypt(plainText, secretKey);
        System.out.println("Encrypted text: " + encryptedText);
        String decryptedText = DES3Util.decrypt(encryptedText, secretKey);
        System.out.println("Decrypted text: " + decryptedText);
    }
}
des3如何加解密n写一个java实现

原文地址: https://www.cveoy.top/t/topic/q2i 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录