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

如何用Java实现加密和解密字符串的函数

发布时间:2023-07-06 12:59:39

要实现加密和解密字符串的函数,可以使用Java提供的加密算法库,例如javax.crypto包中的类。下面是一个示例代码,演示如何使用Java实现AES对称加密和解密字符串。

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class EncryptionExample {

    private static final String ALGORITHM = "AES";
    private static final String KEY = "ThisIsASecretKey";

    public static String encrypt(String stringToEncrypt) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(stringToEncrypt.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedString) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedString.getBytes(StandardCharsets.UTF_8));
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        try {
            String originalString = "This is a string to be encrypted";
            String encryptedString = encrypt(originalString);
            String decryptedString = decrypt(encryptedString);

            System.out.println("Original String: " + originalString);
            System.out.println("Encrypted String: " + encryptedString);
            System.out.println("Decrypted String: " + decryptedString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

上述代码中,首先定义了加密算法和密钥,然后编写了encrypt和decrypt两个函数分别用于加密和解密字符串。在加密函数中,首先根据密钥生成一个SecretKeySpec对象,然后使用Cipher类进行加密操作。加密结果使用Base64编码转换为字符串后返回。

在解密函数中,同样先根据密钥生成SecretKeySpec对象,然后使用Base64解码密文。接着使用Cipher类进行解密操作,并将解密结果转换为字符串后返回。

最后,在main函数中演示了如何使用这两个函数进行加密和解密操作。