java字符串怎么加密和解密

   2024-10-13 4090
核心提示:在Java中,字符串的加密和解密可以通过很多种方式实现,以下是其中一种常见的加密和解密方法:加密:import javax.crypto.Cipher

在Java中,字符串的加密和解密可以通过很多种方式实现,以下是其中一种常见的加密和解密方法:

加密:

import javax.crypto.Cipher;import javax.crypto.spec.SecretKeySpec;import java.util.Base64;public class EncryptionUtil {    private static final String key = "secretkey";    public static String encrypt(String strToEncrypt) {        try {            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");            cipher.init(Cipher.ENCRYPT_MODE, secretKey);            byte[] encryptedBytes = cipher.doFinal(strToEncrypt.getBytes());            return Base64.getEncoder().encodeToString(encryptedBytes);        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    public static String decrypt(String strToDecrypt) {        try {            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");            cipher.init(Cipher.DECRYPT_MODE, secretKey);            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(strToDecrypt));            return new String(decryptedBytes);        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    public static void main(String[] args) {        String originalText = "Hello, World!";        String encryptedText = encrypt(originalText);        System.out.println("Encrypted Text: " + encryptedText);        String decryptedText = decrypt(encryptedText);        System.out.println("Decrypted Text: " + decryptedText);    }}

在上面的代码中,我们使用AES算法对字符串进行加密和解密。首先定义了一个密钥key,然后通过SecretKeySpec和Cipher类来实现加密和解密操作。

请注意,在实际应用中,使用固定的密钥来加密和解密数据是不安全的,建议使用更安全的方式来管理密钥。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号