· 9 years ago · Sep 14, 2016, 07:20 AM
1Cipher aesCipherForEncryption = Cipher.getInstance("AES/CBC/PKCS5PADDING");
2
3No Such Algorithm exists java.security.NoSuchAlgorithmException: Cannot find any provider supporting DES/CBC/PKCS7Padding.
4
5String strDataToEncrypt = new String();
6 String strCipherText = new String();
7 String strDecryptedText = new String();
8
9 try {
10 KeyGenerator keyGen = KeyGenerator.getInstance("AES");
11 keyGen.init(128);
12 SecretKey secretKey = keyGen.generateKey();
13
14 final int AES_KEYLENGTH = 128;
15 byte[] iv = new byte[AES_KEYLENGTH / 8];
16 SecureRandom prng = new SecureRandom();
17 prng.nextBytes(iv);
18
19 Cipher aesCipherForEncryption = Cipher.getInstance("AES/CBC/PKCS7PADDING");
20
21 aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
22
23 strDataToEncrypt = "Hello World of Encryption using AES ";
24 byte[] byteDataToEncrypt = strDataToEncrypt.getBytes();
25 byte[] byteCipherText = aesCipherForEncryption.doFinal(byteDataToEncrypt);
26
27 strCipherText = new BASE64Encoder().encode(byteCipherText);
28 System.out.println("Cipher Text generated using AES is " + strCipherText);
29
30
31 Cipher aesCipherForDecryption = Cipher.getInstance("AES/CBC/PKCS7PADDING");
32
33 aesCipherForDecryption.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
34 byte[] byteDecryptedText = aesCipherForDecryption.doFinal(byteCipherText);
35 strDecryptedText = new String(byteDecryptedText);
36
37 System.out.println(" Decrypted Text message is " + strDecryptedText);
38
39 } catch (NoSuchAlgorithmException noSuchAlgo) {
40 System.out.println(" No Such Algorithm exists " + noSuchAlgo);
41 } catch (NoSuchPaddingException noSuchPad) {
42 System.out.println(" No Such Padding exists " + noSuchPad);
43 } catch (InvalidKeyException invalidKey) {
44 System.out.println(" Invalid Key " + invalidKey);
45 } catch (BadPaddingException badPadding) {
46 System.out.println(" Bad Padding " + badPadding);
47 } catch (IllegalBlockSizeException illegalBlockSize) {
48 System.out.println(" Illegal Block Size " + illegalBlockSize);
49 } catch (InvalidAlgorithmParameterException invalidParam) {
50 System.out.println(" Invalid Parameter " + invalidParam);
51 }