千鋒教育-做有情懷、有良心、有品質(zhì)的職業(yè)教育機(jī)構(gòu)

手機(jī)站
千鋒教育

千鋒學(xué)習(xí)站 | 隨時(shí)隨地免費(fèi)學(xué)

千鋒教育

掃一掃進(jìn)入千鋒手機(jī)站

領(lǐng)取全套視頻
千鋒教育

關(guān)注千鋒學(xué)習(xí)站小程序
隨時(shí)隨地免費(fèi)學(xué)習(xí)課程

當(dāng)前位置:首頁(yè)  >  千鋒問(wèn)問(wèn)  > java對(duì)稱加密解密怎么操作

java對(duì)稱加密解密怎么操作

java對(duì)稱加密 匿名提問(wèn)者 2023-09-15 15:51:32

java對(duì)稱加密解密怎么操作

我要提問(wèn)

推薦答案

  在Java中,可以使用javax.crypto包提供的加密算法和密鑰庫(kù)來(lái)進(jìn)行對(duì)稱加密和解密操作。對(duì)稱加密使用相同的密鑰同時(shí)進(jìn)行加密和解密,因此需要安全地管理密鑰以確保數(shù)據(jù)的保密性。下面是一個(gè)使用對(duì)稱加密算法進(jìn)行加密和解密的示例代碼:

千鋒教育

  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 SymmetricEncryption {

  public static void main(String[] args) throws Exception {

  String plainText = "Hello, World!";

  String encryptionKey = "SecretKey";

  byte[] encryptedData = encrypt(plainText, encryptionKey);

  System.out.println("Encrypted Data: " + Base64.getEncoder().encodeToString(encryptedData));

  String decryptedText = decrypt(encryptedData, encryptionKey);

  System.out.println("Decrypted Text: " + decryptedText);

  }

  public static byte[] encrypt(String plainText, String encryptionKey) throws Exception {

  SecretKeySpec secretKey = generateKey(encryptionKey);

  Cipher cipher = Cipher.getInstance("AES");

  cipher.init(Cipher.ENCRYPT_MODE, secretKey);

  byte[] encryptedData = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

  return encryptedData;

  }

  public static String decrypt(byte[] encryptedData, String encryptionKey) throws Exception {

  SecretKeySpec secretKey = generateKey(encryptionKey);

  Cipher cipher = Cipher.getInstance("AES");

  cipher.init(Cipher.DECRYPT_MODE, secretKey);

  byte[] decryptedData = cipher.doFinal(encryptedData);

  return new String(decryptedData, StandardCharsets.UTF_8);

  }

  public static SecretKeySpec generateKey(String encryptionKey) throws Exception {

  byte[] keyBytes = encryptionKey.getBytes(StandardCharsets.UTF_8);

  KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

  keyGenerator.init(128);

  SecretKey secretKey = keyGenerator.generateKey();

  return new SecretKeySpec(keyBytes, "AES");

  }

  }

 

  上述代碼使用AES算法進(jìn)行對(duì)稱加密和解密。首先,通過(guò)generateKey方法生成AES密鑰,然后使用該密鑰初始化加密和解密的Cipher對(duì)象。encrypt方法將明文字符串轉(zhuǎn)換為字節(jié)數(shù)組后進(jìn)行加密,返回加密后的字節(jié)數(shù)組。decrypt方法對(duì)加密后的字節(jié)數(shù)組進(jìn)行解密并返回解密后的明文字符串。

  注意:在實(shí)際應(yīng)用中,密鑰的生成和管理應(yīng)該更加安全可靠,并且考慮使用隨機(jī)生成的密鑰。

其他答案

  •   下面是另一種使用Java進(jìn)行對(duì)稱加密和解密的示例代碼:

      import javax.crypto.Cipher;

      import javax.crypto.SecretKey;

      import javax.crypto.SecretKeyFactory;

      import javax.crypto.spec.PBEKeySpec;

      import javax.crypto.spec.PBEParameterSpec;

      import java.nio.charset.StandardCharsets;

      import java.security.spec.AlgorithmParameterSpec;

      public class SymmetricEncryption {

      public static void main(String[] args) throws Exception {

      String plainText = "Hello, World!";

      String encryptionKey = "SecretKey";

      byte[] encryptedData = encrypt(plainText, encryptionKey);

      System.out.println("Encrypted Data: " + new String(encryptedData, StandardCharsets.UTF_8));

      String decryptedText = decrypt(encryptedData, encryptionKey);

      System.out.println("Decrypted Text: " + decryptedText);

      }

      public static byte[] encrypt(String plainText, String encryptionKey) throws Exception {

      char[] password = encryptionKey.toCharArray();

      byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8 };

      int iterationCount = 1000;

      PBEKeySpec pbeKeySpec = new PBEKeySpec(password);

      SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");

      SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);

      Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");

      AlgorithmParameterSpec parameterSpec = new PBEParameterSpec(salt, iterationCount);

      cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);

      byte[] encryptedData = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

      return encryptedData;

      }

      public static String decrypt(byte[] encryptedData, String encryptionKey) throws Exception {

      char[] password = encryptionKey.toCharArray();

      byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8 };

      int iterationCount = 1000;

      PBEKeySpec pbeKeySpec = new PBEKeySpec(password);

      SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");

      SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);

      Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");

      AlgorithmParameterSpec parameterSpec = new PBEParameterSpec(salt, iterationCount);

      cipher.init(Cipher.DECRYPT_MODE, secretKey, parameterSpec);

      byte[] decryptedData = cipher.doFinal(encryptedData);

      return new String(decryptedData, StandardCharsets.UTF_8);

      }

      }

      上述代碼使用PBEWithMD5AndDES算法進(jìn)行對(duì)稱加密和解密。通過(guò)使用相同的密碼和鹽值參數(shù),可以生成相應(yīng)的密鑰并初始化Cipher對(duì)象。encrypt方法將明文字符串轉(zhuǎn)換為字節(jié)數(shù)組后進(jìn)行加密,返回加密后的字節(jié)數(shù)組。decrypt方法對(duì)加密后的字節(jié)數(shù)組進(jìn)行解密并返回解密后的明文字符串。

  •   下面是另一種使用Java進(jìn)行對(duì)稱加密和解密的示例代碼,使用了更加高級(jí)的AES算法和加密模式,同時(shí)采用密鑰生成器和Base64進(jìn)行密鑰和密文的編碼:

      import javax.crypto.Cipher;

      import javax.crypto.SecretKey;

      import javax.crypto.SecretKeyFactory;

      import javax.crypto.spec.IvParameterSpec;

      import javax.crypto.spec.PBEKeySpec;

      import javax.crypto.spec.SecretKeySpec;

      import java.nio.charset.StandardCharsets;

      import java.security.SecureRandom;

      import java.security.spec.KeySpec;

      import java.util.Base64;

      public class SymmetricEncryption {

      public static void main(String[] args) throws Exception {

      String plainText = "Hello, World!";

      String encryptionKey = "SecretKey";

      byte[] encryptedData = encrypt(plainText, encryptionKey);

      System.out.println("Encrypted Data: " + Base64.getEncoder().encodeToString(encryptedData));

      String decryptedText = decrypt(encryptedData, encryptionKey);

      System.out.println("Decrypted Text: " + decryptedText);

      }

      public static byte[] encrypt(String plainText, String encryptionKey) throws Exception {

      SecureRandom random = new SecureRandom();

      byte[] salt = new byte[16];

      random.nextBytes(salt);

      SecretKey secretKey = generateKey(encryptionKey, salt);

      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

      cipher.init(Cipher.ENCRYPT_MODE, secretKey);

      byte[] encryptedData = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

      byte[] iv = cipher.getIV();

      byte[] encryptedDataWithIV = new byte[iv.length + encryptedData.length];

      System.arraycopy(iv, 0, encryptedDataWithIV, 0, iv.length);

      System.arraycopy(encryptedData, 0, encryptedDataWithIV, iv.length, encryptedData.length);

      return encryptedDataWithIV;

      }

      public static String decrypt(byte[] encryptedDataWithIV, String encryptionKey) throws Exception {

      byte[] iv = new byte[16];

      System.arraycopy(encryptedDataWithIV, 0, iv, 0, iv.length);

      byte[] encryptedData = new byte[encryptedDataWithIV.length - iv.length];

      System.arraycopy(encryptedDataWithIV, iv.length, encryptedData, 0, encryptedData.length);

      SecretKey secretKey = generateKey(encryptionKey, iv);

      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

      cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));

      byte[] decryptedData = cipher.doFinal(encryptedData);

      return new String(decryptedData, StandardCharsets.UTF_8);

      }

      public static SecretKey generateKey(String encryptionKey, byte[] salt) throws Exception {

      SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");

      KeySpec spec = new PBEKeySpec(encryptionKey.toCharArray(), salt, 65536, 256);

      SecretKey tempSecretKey = factory.generateSecret(spec);

      return new SecretKeySpec(tempSecretKey.getEncoded(), "AES");

      }

      }

      上述代碼使用更強(qiáng)大的AES算法和加密模式(CBC),并使用隨機(jī)的初始化向量(IV)來(lái)提供更好的安全性。encrypt方法生成隨機(jī)的salt并使用密碼基礎(chǔ)導(dǎo)出(PBKDF2)算法生成密鑰,并使用CBC模式進(jìn)行加密。密文包括IV和加密數(shù)據(jù)。decrypt方法從密文中提取IV并使用密鑰進(jìn)行解密。最終返回解密后的明文字符串。

      無(wú)論使用哪種方法,對(duì)稱加密和解密都需要處理密鑰的安全性,選擇合適的加密算法和使用正確的密鑰長(zhǎng)度是保護(hù)數(shù)據(jù)安全的重要因素。同時(shí),對(duì)密鑰的生成、存儲(chǔ)和分發(fā)也需要考慮到安全性要求。在真實(shí)的應(yīng)用中,請(qǐng)遵循密碼學(xué)最佳實(shí)踐,并確保密鑰和加密的數(shù)據(jù)在傳輸和存儲(chǔ)過(guò)程中受到適當(dāng)?shù)谋Wo(hù)。