欢迎访问宙启技术站
智能推送

Java函数使用实例:实现数据加密与解密

发布时间:2023-11-26 12:07:34

在Java中,可以使用javax.crypto库来实现数据的加密与解密。以下是一个示例代码,演示了如何使用Java函数进行数据的加密与解密。

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class EncryptionExample {

    private static final String ENCRYPTION_ALGORITHM = "DES";

    public static void main(String[] args) throws Exception {
        String originalText = "This is the original text to be encrypted.";

        // 生成密钥
        SecretKey secretKey = generateSecretKey("MySecretKey");

        // 加密
        String encryptedText = encrypt(originalText, secretKey);
        System.out.println("Encrypted Text: " + encryptedText);

        // 解密
        String decryptedText = decrypt(encryptedText, secretKey);
        System.out.println("Decrypted Text: " + decryptedText);
    }

    // 生成密钥
    public static SecretKey generateSecretKey(String keyStr) throws Exception {
        byte[] keyBytes = keyStr.getBytes(StandardCharsets.UTF_8);

        DESKeySpec desKeySpec = new DESKeySpec(keyBytes);
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(ENCRYPTION_ALGORITHM);
        return secretKeyFactory.generateSecret(desKeySpec);
    }

    // 加密
    public static String encrypt(String originalText, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        byte[] encryptedBytes = cipher.doFinal(originalText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 解密
    public static String decrypt(String encryptedText, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
}

该示例使用了DES(Data Encryption Standard)对数据进行加密与解密。首先使用给定的密钥字符串生成SecretKey对象。然后,使用SecretKey对象初始化Cipher对象,并指定加密或解密模式。加密时,将原始文本转换为字节数组,然后调用Cipher的doFinal方法进行加密。解密时,将加密字符串解码为字节数组,然后再调用Cipher的doFinal方法进行解密。最后,将解密的字节数组转换为字符串。

需要注意的是,加密后的文本是使用Base64编码的,以便于展示和传输。解密时,先将Base64编码的文本解码为字节数组,再进行解密。

通过使用该示例中的函数,可以方便地实现数据的加密与解密操作。