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

avatar
作者
筋斗云
阅读量:0

在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工作模式进行加密和解密操作。在实际应用中,应根据需求选择适当的加密算法和工作模式,并确保密钥管理的安全性。

    广告一刻

    为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!