java怎么对byte数组进行加密解密

   2024-10-13 7690
核心提示:在Java中,可以使用Cipher类来对byte数组进行加密和解密。下面是一个简单的示例代码,实现了对byte数组的加密和解密:加密:impo

在Java中,可以使用Cipher类来对byte数组进行加密和解密。下面是一个简单的示例代码,实现了对byte数组的加密和解密:

加密:

import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import java.security.Key;import java.util.Base64;public class Encryption {    public static byte[] encrypt(byte[] input, Key key) throws Exception {        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");        cipher.init(Cipher.ENCRYPT_MODE, key);        return cipher.doFinal(input);    }    public static void main(String[] args) throws Exception {        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");        keyGenerator.init(128);        SecretKey secretKey = keyGenerator.generateKey();        byte[] input = "Hello, World!".getBytes();        byte[] encryptedBytes = encrypt(input, secretKey);        String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes);        System.out.println("Encrypted string: " + encryptedString);    }}

解密:

public static byte[] decrypt(byte[] input, Key key) throws Exception {    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");    cipher.init(Cipher.DECRYPT_MODE, key);    return cipher.doFinal(input);}public static void main(String[] args) throws Exception {    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");    keyGenerator.init(128);    SecretKey secretKey = keyGenerator.generateKey();    byte[] input = "Hello, World!".getBytes();    byte[] encryptedBytes = encrypt(input, secretKey);    byte[] decryptedBytes = decrypt(encryptedBytes, secretKey);    String decryptedString = new String(decryptedBytes);    System.out.println("Decrypted string: " + decryptedString);}

请注意,以上代码中使用了AES加密算法和ECB工作模式进行加密和解密操作。在实际应用中,应根据需求选择适当的加密算法和工作模式,并确保密钥管理的安全性。

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

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