Java中如何实现字符串的加密解密

发布时间:2025-03-21 17:14:49 作者:小樊
来源:亿速云 阅读:112

在Java中,可以使用Java Cryptography Extension (JCE)来实现字符串的加密和解密。JCE提供了一套加密算法,包括对称加密算法(如AES、DES等)和非对称加密算法(如RSA、DSA等)。以下是一个使用AES对称加密算法实现字符串加密和解密的示例:

首先,确保你的Java环境已经安装了JCE。

然后,创建一个名为AESEncryptionExample.java的文件,并添加以下代码:

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;

public class AESEncryptionExample {

    public static void main(String[] args) throws Exception {
        String originalString = "Hello, World!";
        System.out.println("Original String: " + originalString);

        // 加密
        String encryptedString = encrypt(originalString, "mySecretKey123");
        System.out.println("Encrypted String: " + encryptedString);

        // 解密
        String decryptedString = decrypt(encryptedString, "mySecretKey123");
        System.out.println("Decrypted String: " + decryptedString);
    }

    public static String encrypt(String plainText, String secretKey) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedText, String secretKey) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
}

在这个示例中,我们使用了AES/ECB/PKCS5Padding加密模式。你可以根据需要更改加密模式和填充方式。运行这个程序,你将看到原始字符串、加密后的字符串和解密后的字符串。

注意:在实际应用中,密钥管理非常重要。不要将密钥硬编码在代码中,而是使用安全的方式存储和管理密钥。

推荐阅读:
  1. Java中什么是JMM
  2. java数组与以逗号分隔开的字符串实现相互转换

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Java中字符串比较要注意什么

下一篇:Java字符串与字符数组如何转换

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》