· 7 years ago · Sep 03, 2018, 04:04 AM
1javax.crypto.BadPaddingException
2// Get the key generator
3 KeyGenerator kg = KeyGenerator.getInstance("AES");
4 kg.init(128);
5 SecretKey sk = kg.generateKey();
6 byte[] iv = new byte[]{0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f};
7 AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
8
9 ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
10 dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
11
12 ecipher.init(Cipher.ENCRYPT_MODE, sk,paramSpec);
13 dcipher.init(Cipher.DECRYPT_MODE, sk,paramSpec);
14
15public String decr(String str) {
16 try {
17 byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
18 byte[] utf8 = dcipher.doFinal(dec);
19 return new String(utf8, "UTF8");
20 } catch (Exception ex) {
21 return null;
22 }
23 }
24
25public String encr(String str) {
26 try {
27 byte[] utf8 = str.getBytes("UTF8");
28 byte[] enc = ecipher.doFinal(utf8);
29 return new sun.misc.BASE64Encoder().encode(enc);
30 } catch (Exception ex) {
31 return null;
32 }
33 }
34
35package com.sandbox;
36
37import java.io.IOException;
38import java.io.UnsupportedEncodingException;
39import java.security.spec.AlgorithmParameterSpec;
40
41import javax.crypto.BadPaddingException;
42import javax.crypto.Cipher;
43import javax.crypto.IllegalBlockSizeException;
44import javax.crypto.KeyGenerator;
45import javax.crypto.SecretKey;
46import javax.crypto.spec.IvParameterSpec;
47
48public class EncryptionTest
49{
50 private final Cipher ecipher;
51 private final Cipher dcipher;
52
53 public EncryptionTest() throws Exception
54 {
55 KeyGenerator kg = KeyGenerator.getInstance("AES");
56 kg.init(128);
57 SecretKey sk = kg.generateKey();
58 byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
59 AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
60
61 ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
62 dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
63
64 ecipher.init(Cipher.ENCRYPT_MODE, sk, paramSpec);
65 dcipher.init(Cipher.DECRYPT_MODE, sk, paramSpec);
66 }
67
68 public String encrypt(String str) throws IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
69 {
70 byte[] utf8 = str.getBytes("UTF8");
71 byte[] enc = ecipher.doFinal(utf8);
72 return new sun.misc.BASE64Encoder().encode(enc);
73 }
74
75 public String decrypt(String str) throws IOException, IllegalBlockSizeException, BadPaddingException
76 {
77 byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
78 byte[] utf8 = dcipher.doFinal(dec);
79 return new String(utf8, "UTF8");
80 }
81
82 public static void main(String[] args)
83 {
84 try
85 {
86 EncryptionTest sandbox = new EncryptionTest();
87 System.out.println(sandbox.decrypt(sandbox.encrypt("Hello world")));
88 }
89 catch (Exception e)
90 {
91 e.printStackTrace();
92 }
93 }
94}