· 7 years ago · Sep 11, 2018, 04:40 AM
1Java AES CBC Decryption
2$privateKey = "1234567812345678";
3$iv = "1234567812345678";
4$data = "Test string";
5
6$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateKey, $data, MCRYPT_MODE_CBC, $iv);
7
8echo(base64_encode($encrypted));
9
10Result: iz1qFlQJfs6Ycp+gcc2z4w==
11
12public static String decrypt() throws Exception{
13 try{
14 String Base64EncodedText = "iz1qFlQJfs6Ycp+gcc2z4w==";
15 String decodedText = com.sun.xml.internal.messaging.saaj.util.Base64.base64Decode(Base64EncodedText);
16 String key = "1234567812345678";
17 String iv = "1234567812345678";
18
19 javax.crypto.spec.SecretKeySpec keyspec = new javax.crypto.spec.SecretKeySpec(key.getBytes(), "AES");
20 javax.crypto.spec.IvParameterSpec ivspec = new javax.crypto.spec.IvParameterSpec(iv.getBytes());
21
22 javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("AES/CBC/NoPadding");
23 cipher.init(javax.crypto.Cipher.DECRYPT_MODE, keyspec, ivspec);
24 byte[] decrypted = cipher.doFinal(decodedText.getBytes());
25
26 String str = new String(decrypted);
27
28 return str;
29
30 }catch(Exception e){
31 return null;
32 }
33}
34
35String decodedText = com.sun.xml.internal.messaging.saaj.util.Base64.base64Decode(Base64EncodedText);
36
37import java.nio.charset.Charset;
38
39import javax.crypto.Cipher;
40import javax.crypto.SecretKey;
41import javax.crypto.spec.IvParameterSpec;
42import javax.crypto.spec.SecretKeySpec;
43
44import org.apache.commons.codec.binary.Base64;
45import org.apache.commons.codec.binary.Hex;
46
47public class AESToy3 {
48
49 private static final Charset ASCII = Charset.forName("US-ASCII");
50
51 public static void main(String[] args) throws Exception {
52 String base64Cipher = "iz1qFlQJfs6Ycp+gcc2z4w==";
53 byte [] cipherBytes = Base64.decodeBase64(base64Cipher);
54 byte [] iv = "1234567812345678".getBytes(ASCII);
55 byte [] keyBytes = iv.clone();
56
57 SecretKey aesKey = new SecretKeySpec(keyBytes, "AES");
58
59 Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
60 cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
61
62 byte[] result = cipher.doFinal(cipherBytes);
63 System.out.println(Hex.encodeHexString(result));
64 }
65
66}
67
685465737420737472696e670000000000