温馨提示×

java加密与解密代码怎么写

小亿
85
2024-08-11 14:42:38
栏目: 编程语言

在Java中,常用的加密算法有对称加密和非对称加密。以下是一个简单的示例代码,展示如何使用对称加密算法AES进行加密和解密:

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

public class EncryptionUtils {

    private static final String SECRET_KEY = "mysecretkey12345";

    public static String encrypt(String plainText) {
        try {
            SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String encryptedText) {
        try {
            SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String plainText = "Hello, world!";
        String encryptedText = encrypt(plainText);
        System.out.println("Encrypted text: " + encryptedText);
        String decryptedText = decrypt(encryptedText);
        System.out.println("Decrypted text: " + decryptedText);
    }
}

在上面的示例中,我们定义了一个EncryptionUtils类,其中包含了encryptdecrypt方法来进行加密和解密操作。我们使用AES算法和一个固定的密钥mysecretkey12345来加密和解密文本数据。您可以替换为自己的密钥来增强安全性。在main方法中,我们对一个简单的文本进行加密和解密,并输出结果。

请注意,以上示例只是一个简单的演示,实际应用中需要根据具体需求选择更加安全和复杂的加密算法和实现。

0