{"id":51,"date":"2019-07-06T10:17:13","date_gmt":"2019-07-06T04:47:13","guid":{"rendered":"http:\/\/techieshouts.com\/?p=51"},"modified":"2022-08-09T19:08:57","modified_gmt":"2022-08-09T13:38:57","slug":"aes-encryption-and-decryption-in-java","status":"publish","type":"post","link":"https:\/\/techieshouts.com\/home\/aes-encryption-and-decryption-in-java\/","title":{"rendered":"AES Encryption and Decryption in Java"},"content":{"rendered":"\n<div class=\"wp-block-media-text alignwide has-media-on-the-right is-stacked-on-mobile\" style=\"grid-template-columns:auto 34%\"><figure class=\"wp-block-media-text__media\"><img loading=\"lazy\" width=\"300\" height=\"300\" src=\"https:\/\/techieshouts.com\/wp-content\/uploads\/2019\/07\/AES-300x300.jpg\" alt=\"AES\" class=\"wp-image-67 size-full\" srcset=\"https:\/\/techieshouts.com\/wp-content\/uploads\/2019\/07\/AES-300x300.jpg 300w, https:\/\/techieshouts.com\/wp-content\/uploads\/2019\/07\/AES-150x150.jpg 150w, https:\/\/techieshouts.com\/wp-content\/uploads\/2019\/07\/AES.jpg 626w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/figure><div class=\"wp-block-media-text__content\">\n<p class=\"has-text-align-left\">While there are many encryption and decryption algorithms available, AES is one of the robust and reliable modes of encrypting the data. The implementation can be done in many languages as there are libraries and packages available for multiple languages. <\/p>\n<\/div><\/div>\n\n\n\n<p><\/p>\n\n\n\n<h2><strong>Creating the AES encryption\/decryption library<\/strong><\/h2>\n\n\n\n<p>We do not need any special library to be downloaded for creating the AES encryption\/decryption library.  All we need is the javax.crypto package which is already available as a part of JDK <\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"classic\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import javax.crypto.Cipher;\nimport javax.crypto.spec.IvParameterSpec;\nimport javax.crypto.spec.SecretKeySpec;\nimport javax.xml.bind.DatatypeConverter;\npublic final class EncDec \n{\npublic static String encrypt(String value, String ivVal, String key) {\n    try {\n        IvParameterSpec iv = new IvParameterSpec(ivVal.getBytes(\"UTF-8\"));\n        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(\"UTF-8\"), \"AES\");\n        Cipher cipher = Cipher.getInstance(\"AES\/CBC\/PKCS5PADDING\");\n        cipher.init(1, skeySpec, iv);\n        byte[] encrypted = cipher.doFinal(value.getBytes());\n        return DatatypeConverter.printBase64Binary(encrypted);\n    } catch (Exception ex) {\n        ex.printStackTrace();\n    }\n    return null;\n}\npublic static String decrypt(String encrypted, String ivVal, String key) {\n    try {\n        IvParameterSpec iv = new IvParameterSpec(ivVal.getBytes(\"UTF-8\"));\n        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(\"UTF-8\"), \"AES\");\n        Cipher cipher = Cipher.getInstance(\"AES\/CBC\/PKCS5PADDING\");\n        cipher.init(2, skeySpec, iv);\n        byte[] original = cipher.doFinal(DatatypeConverter.parseBase64Binary(encrypted));\n        return new String(original);\n    } catch (Exception ex) {\n        ex.printStackTrace();\n    }\n    return null;\n}\n}<\/pre>\n\n\n\n<p>Now let us look into the above code by each section<\/p>\n\n\n\n<h2>Imports required for AES Encryption<\/h2>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"classic\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import javax.crypto.Cipher;\nimport javax.crypto.spec.IvParameterSpec;\nimport javax.crypto.spec.SecretKeySpec;\nimport javax.xml.bind.DatatypeConverter;<\/pre>\n\n\n\n<p>These are the classes required to perform encryption\/decryption. AES is using Cipher padding for performing the encryption. There are two main classes that we are using here.  IvParameterSpec will receive a byte array of the iv(initial vector).<\/p>\n\n\n\n<p> IV is used along with the secret key to prevent the repetition of sequence in encryption. This will make the job of a hacker tough. <\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"classic\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">IvParameterSpec iv = new IvParameterSpec(ivVal.getBytes(\"UTF-8\"));<\/pre>\n\n\n\n<p>The next one is the secret key.  Similar to IvParameterSpec the SecretKeySpec class will also accept a byte array of the secret key. Along with that, it will receive the value of the encryption type that we want to use.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"classic\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(\"UTF-8\"), \"AES\");<\/pre>\n\n\n\n<p>After this, the Cipher object will be created with the above two objects and the mode(Encryption or Decryption) is indicated with the help of the first parameter while creating the Cipher object.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Cipher cipher = Cipher.getInstance(\"AES\/CBC\/PKCS5PADDING\");\ncipher.init(1, skeySpec, iv);<\/pre>\n\n\n\n<p>The different types of cipher class instances are<\/p>\n\n\n\n<ul><li>1 &#8211; Encryption<\/li><li>2 &#8211; Decryption <\/li><li>3 &#8211; Key wrapping<\/li><li>4 &#8211; Key unwrapping<\/li><\/ul>\n\n\n\n<p>The next part is receiving the encrypted content as a bytes array and converting it to a string<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">byte[] encrypted = cipher.doFinal(value.getBytes());\nreturn DatatypeConverter.printBase64Binary(encrypted);<\/pre>\n\n\n\n<p>Next, we will compile and export the full code to a java library. <\/p>\n\n\n\n<h2><strong>Creating a java client to use the library<\/strong><\/h2>\n\n\n\n<p>Now that we have created the library that can encrypt and decrypt the string, we will create a sample client to import and use this library.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import com.java.encdec.EncDec;\npublic class AESEncDecClient {\n\tpublic static void main(String[] args) {\n\t\t\n\t\t\/\/Plain text message that we are going to encrypt\n\t\tString plainMessage = \"We are learning AES encryption\/decryption in techieshouts.com\";\n\t\tString encryptedMessage = \"\";\n\t\tString decryptedMessage = \"\";\n\t\tString iv = \"TestMeInitVector\";\n\t\tString encryptionKey = \"YourSampleEncKey\";\n\t\t\n\t\tSystem.out.println(\"Plain text: \" + plainMessage);\n\t\t\n\t\tSystem.out.println(\"\\nEncrypting the plain text..\");\n\t\t\n\t\t\/\/Calling the encrypt method of the library to encrypt the plain text\n\t\tencryptedMessage = EncDec.encrypt(plainMessage, iv, encryptionKey);\n\t\tSystem.out.println(\"Encrypted text: \" + encryptedMessage);\n\t\t\n\t\tSystem.out.println(\"\\nDecrypting the encrypted text..\");\n\t\t\/\/Calling the decrypt method of the library to decrypt the encrypted message\n\t\tdecryptedMessage = EncDec.decrypt(encryptedMessage, iv, encryptionKey);\n\t\tSystem.out.println(\"Decrypted text: \" + decryptedMessage);\n\t}\n}<\/pre>\n\n\n\n<p>In the above code snippet, we are first importing the library that we created earlier for encrypting and decrypting the text<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import com.java.encdec.EncDec;<\/pre>\n\n\n\n<p>After that, we are creating the iv and key for encryption.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">String iv = \"TestMeInitVector\";\nString encryptionKey = \"YourSampleEncKey\";<\/pre>\n\n\n\n<p>Care should be taken while choosing the iv and encryptionKey values. Both of these values should be 16 digits. The reason is, that the block size of AES-128 or AES-256 algorithm is 16 bytes(128 bits). So the iv and keys used to encrypt the message should be of the same size as the block.<\/p>\n\n\n\n<p>Also, check the same <a href=\"https:\/\/techieshouts.com\/aes-encryption-and-decryption-using-python\/\">&#8220;AES Encryption and Decryption using Python&#8221;<\/a><\/p>\n\n\n\n<p>Reference &#8211; <a href=\"https:\/\/en.wikipedia.org\/wiki\/Advanced_Encryption_Standard\" target=\"_blank\" rel=\"noopener\">Advance Encryption Standard<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>While there are many encryption and decryption algorithms available, AES is one of the robust and reliable modes of encrypting the data. The implementation can be done in many languages as there are libraries and packages available for multiple languages. Creating the AES encryption\/decryption library We do not need any special library to be downloaded\u2026 <span class=\"read-more\"><a href=\"https:\/\/techieshouts.com\/home\/aes-encryption-and-decryption-in-java\/\">Read More &raquo;<\/a><\/span><\/p>\n","protected":false},"author":1,"featured_media":67,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[6],"tags":[30,31,34,35],"_links":{"self":[{"href":"https:\/\/techieshouts.com\/home\/wp-json\/wp\/v2\/posts\/51"}],"collection":[{"href":"https:\/\/techieshouts.com\/home\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techieshouts.com\/home\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techieshouts.com\/home\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techieshouts.com\/home\/wp-json\/wp\/v2\/comments?post=51"}],"version-history":[{"count":30,"href":"https:\/\/techieshouts.com\/home\/wp-json\/wp\/v2\/posts\/51\/revisions"}],"predecessor-version":[{"id":1174,"href":"https:\/\/techieshouts.com\/home\/wp-json\/wp\/v2\/posts\/51\/revisions\/1174"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techieshouts.com\/home\/wp-json\/wp\/v2\/media\/67"}],"wp:attachment":[{"href":"https:\/\/techieshouts.com\/home\/wp-json\/wp\/v2\/media?parent=51"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techieshouts.com\/home\/wp-json\/wp\/v2\/categories?post=51"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techieshouts.com\/home\/wp-json\/wp\/v2\/tags?post=51"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}