温馨提示×

如何实现cipher类java加密解密

小樊
84
2024-09-09 10:29:29
栏目: 编程语言

在Java中,可以使用javax.crypto包中的类和方法来实现加密和解密。以下是一个简单的示例,展示了如何使用AES加密算法实现加密和解密。

首先,需要导入所需的类:

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

接下来,创建一个名为CipherUtils的工具类,用于封装加密和解密方法:

public class CipherUtils {

    private static final String ALGORITHM = "AES";

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

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

    public static SecretKey generateSecretKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(128);
        return keyGenerator.generateKey();
    }
}

现在,可以使用CipherUtils类进行加密和解密操作:

public class Main {
    public static void main(String[] args) {
        try {
            SecretKey secretKey = CipherUtils.generateSecretKey();

            String plainText = "Hello, World!";
            String encryptedText = CipherUtils.encrypt(plainText, secretKey);
            System.out.println("Encrypted text: " + encryptedText);

            String decryptedText = CipherUtils.decrypt(encryptedText, secretKey);
            System.out.println("Decrypted text: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

运行上述代码,将看到加密后的文本以及解密后的原始文本。请注意,为了安全起见,应该妥善保管密钥,不要将其暴露给未经授权的用户。

0