Cipher_demo

参考:Java使用Cipher类实现加密,包括DES,DES3,AES和RSA加密 - 蔡昭凯 - 博客园 (cnblogs.com)

Main.java

 1 package com.hmb;
 2 
 3 import javax.crypto.*;
 4 import javax.crypto.spec.IvParameterSpec;
 5 import javax.crypto.spec.SecretKeySpec;
 6 import java.security.InvalidAlgorithmParameterException;
 7 import java.security.InvalidKeyException;
 8 import java.security.NoSuchAlgorithmException;
 9 import java.util.Base64;
10 
11 public class Main {
12     public static void main(String[] args) {
13         String content = "hmb";
14         String salt = "saltsaltsaltsalt";
15         String iv = "iviviviviviviviv";
16 
17         try {
18             Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
19             SecretKey secretKey = new SecretKeySpec(salt.getBytes(), "AES");
20             IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
21             cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
22             byte[] encrypted = cipher.doFinal(content.getBytes());
23             String encryptedStr = Base64.getEncoder().encodeToString(encrypted);
24             System.out.println(encryptedStr);
25 
26             byte[] decrypted = Base64.getDecoder().decode(encryptedStr);
27             Cipher decriptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
28             decriptCipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
29             byte[] contentDecrypt = decriptCipher.doFinal(decrypted);
30             String decryptStr = new String(contentDecrypt);
31             System.out.println(decryptStr);
32         } catch (NoSuchAlgorithmException e) {
33             throw new RuntimeException(e);
34         } catch (NoSuchPaddingException e) {
35             throw new RuntimeException(e);
36         } catch (InvalidAlgorithmParameterException e) {
37             throw new RuntimeException(e);
38         } catch (InvalidKeyException e) {
39             throw new RuntimeException(e);
40         } catch (IllegalBlockSizeException e) {
41             throw new RuntimeException(e);
42         } catch (BadPaddingException e) {
43             throw new RuntimeException(e);
44         }
45 
46     }
47 }

 执行结果

 

posted @ 2023-07-02 23:55  hemeiwolong  阅读(9)  评论(0编辑  收藏  举报