· 7 years ago · Sep 11, 2018, 08:34 AM
1why decryption fails for certain data only
2public class App
3{
4 static byte[] seckey=null;
5 static
6 {
7 try
8 {
9 KeyGenerator kgen = KeyGenerator.getInstance("AES");
10 kgen.init(128);
11
12 // Generate the secret key specs.
13 // SecretKey skey = kgen.generateKey();
14 // seckey = skey.getEncoded();
15 // above won't work as can't generate new secret key for decrypt. Have to use same key for encrypt and decrypt
16
17 // seckey = new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
18 seckey = new byte[]{(byte)172,(byte)236,(byte)125,(byte)222,(byte)188,(byte)33,(byte)210,(byte)4,(byte)202,(byte)31,(byte)188,(byte)152,(byte)220,(byte)104,(byte)62,(byte)64};
19
20
21 } catch (NoSuchAlgorithmException e)
22 {
23 e.printStackTrace();
24 }
25
26
27 }
28 public static void main( String[] args )
29 {
30
31 String password = encrypt("A123456"); //working
32 System.out.println(password);
33 System.out.println(decrypt(password));
34
35 String password = encrypt("A*501717"); //NOT working
36 System.out.println(password);
37 System.out.println(decrypt(password));
38
39 }
40 public static String encrypt(String passwd)
41 {
42 SecretKeySpec key = new SecretKeySpec(seckey, "AES");
43 byte[] output;
44 try
45 {
46 Cipher cipher = Cipher.getInstance("AES");
47
48 // encryption pass
49 cipher.init(Cipher.ENCRYPT_MODE, key);
50 output = cipher.doFinal(passwd.getBytes());
51 } catch (Exception e)
52 {
53 System.out.println("Unable to encrypt password.");
54 output = "".getBytes();
55 }
56
57 return new String(output);
58
59 }
60
61 public static String decrypt(String passwd)
62 {
63 if (!StringUtils.isNotBlank(passwd))
64 return "";
65
66 SecretKeySpec key = new SecretKeySpec(seckey, "AES");
67
68 byte[] output;
69 try
70 {
71 Cipher cipher = Cipher.getInstance("AES");
72 // decryption pass
73 cipher.init(Cipher.DECRYPT_MODE, key);
74 output = cipher.doFinal(passwd.getBytes());
75 } catch (Exception e)
76 {
77 System.out.println("Unable to decrypt password");
78 output = "".getBytes();
79 }
80
81 return new String(output);
82
83 }
84 }
85
86seckey = new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};