There are many problems when you try encrypting a string such password, credit card nos, phone no. etc ie
1. which algorithm to use.
2. how to store the generated Key in the database.
3. should i use MD5, AES etc.
Here is the question to all your answers. After spending sometime on this i finally got the best algorithm that a person can use to encrypt and decrypt data while he/she also wants to store those encrypted strings and later on want to decrypt it while retrieving the data.
Many people face problem while decrypting the encrypted data as the KEY used for encryption if stored as String in database then it becomes very tough to use that string as the KEY. So below is the code where you only need to store the encrypted code and not the key. The decryption will take place as an when wanted.
For encryption we must use a secret key along with an algorithm. In the following example we use an algorithm called AES 128 and the bytes of the word "TheBestSecretKey" as the secret key (the best secret key we found in this world). AES algorithm can use a key of 128 bits (16 bytes * 8); so we selected that key.
Below is the code how you can use the above encryption algorithm.
1. which algorithm to use.
2. how to store the generated Key in the database.
3. should i use MD5, AES etc.
Here is the question to all your answers. After spending sometime on this i finally got the best algorithm that a person can use to encrypt and decrypt data while he/she also wants to store those encrypted strings and later on want to decrypt it while retrieving the data.
Many people face problem while decrypting the encrypted data as the KEY used for encryption if stored as String in database then it becomes very tough to use that string as the KEY. So below is the code where you only need to store the encrypted code and not the key. The decryption will take place as an when wanted.
For encryption we must use a secret key along with an algorithm. In the following example we use an algorithm called AES 128 and the bytes of the word "TheBestSecretKey" as the secret key (the best secret key we found in this world). AES algorithm can use a key of 128 bits (16 bytes * 8); so we selected that key.
package nomad;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.*;
import sun.misc.*;
public class AESencrp {
private static final String ALGO = "AES";
private static final byte[] keyValue =
new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't',
'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };
public static String encrypt(String Data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;
}
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGO);
return key;
}
}
We use "generateKey()" method to generate a secret key for AES algorithm with a given key.Below is the code how you can use the above encryption algorithm.
package nomad; public class Checker { public static void main(String[] args) throws Exception { String password = "mypassword"; String passwordEnc = AESencrp.encrypt(password); String passwordDec = AESencrp.decrypt(passwordEnc); System.out.println("Plain Text : " + password); System.out.println("Encrypted Text : " + passwordEnc); System.out.println("Decrypted Text : " + passwordDec); } }
NOTE :
I have got emails from user saying that the above code gives error when using in ECLIPSE. Error like :
Access restriction: The type BASE64Decoder is not accessible due to restriction on required library C:\Program Files\Java\jre6\lib\rt.jar
So to avoid this do the following :
* Go to Window-->Preferences-->Java-->Compiler-->Error/Warnings.
* Select Deprecated and Restricted API. Change it to warning.
* Change forbidden and Discouraged Reference and change it to warning. (or as your need.)
Note: 12-12-2013
One of our readers (Saurabh Moghel), has given a solution about some issue:
Issue: Issue Of Access Restriction
Solution: Removing JRE system Library then adding it back from Build Path settings in the project properties.
what a great post
ReplyDeletethanks
awesome...thanks dude
ReplyDeletegood one.......quite helpful
ReplyDelete@Anonymous thank you dear..
ReplyDeleteThe above code is still really basic its not the best we can do with AES.
ReplyDeletebyte[] key = null; // TODO
byte[] input = null; // TODO
byte[] output = null;
SecretKeySpec keySpec = null;
keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
output = cipher.doFinal(input)
an you can pad the password to 256 and not 128
@JasonYes its a basic code. I never said its the best Code using AES. I just posted the Basic structure of how to use AES in java
ReplyDeleteNice post farhan, spring security also provides way to encrypt password outofbox using MD5 and other encryption algorithm. Though this can be used a nice utility.
ReplyDeleteThanks
Javin
Ldap authentication using Spring with Example
Hello
ReplyDeletei have an error with this code.. could you help me ?
the error is class, interface, or enum expected;
@StudentMake sure the class name and the file name both are the exact same..
ReplyDeleteI made this program in ECLIPSE IDE.. in that i make a project and then in that i made a package named 'nomad' and inside it i had these two classes.
Here is the link on Java programming with eclipse : Basic
Thanks!
ReplyDeleteSmall improvement to the code is to change the usage of sun.misc.BASE64 to Apache Commons Codec which provides Base64 http://commons.apache.org/codec/api-release/org/apache/commons/codec/binary/Base64.html
You should be using java.sun.misc.base64 even in Java 6, because it's not part of the API of java.
For more info: http://java.sun.com/products/jdk/faq/faq-sun-packages.html
@Unknown Thank you for the information..
ReplyDeleteSplit Sort Java Code SVP?
ReplyDeleteis there any method for steganography like this??????????
ReplyDeleteWell I don't have any experience on Steganography. But yeah there are blog posts available.
Deletehey there could you please help me out i have an error with this code posted above and it says"Base64.decode cannot be resolved to a type"
Deletehey there could you please help me out i've an error that says"Base64.decode cannot be resolved to a type"
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDeletehow to make it with with password i.e
ReplyDeletewe pass the data and the password to encrypt with...
??
i tried creating a function which takes the password ,converts it to byte and then store it in keyValue
but it gives a error of "Invalid AES key length: 10 bytes"
plz reply ..i need it for my project
What is the correct way to save the keyValue? (java keystore?)
ReplyDeleteThanks, that was exactly wath I was looking for. But since Base64 is now in Java8, it's better to use Base64.getEncoder() (import java.util.Base64;) rather than new BASE64Encoder().encode()
ReplyDeletevery good.. works with eclipse
ReplyDeletehello...can u give me MATLAB code of AES for images
ReplyDeleteThank you for writing this. It was very useful for me.
ReplyDeleteuseful for me, many thanks!
ReplyDeleteYou have really save me from a very big challenge that gave me sleepless nite.
ReplyDeleteI was just looking for something like this to know my way forward and all i could get from Stackoverflow was the first class AESencrp but how to checkout was another brain dump.
I believe you have got this code working. I'm getting this error when i run the file!
DeleteAESencrp.java:21: warning: BASE64Encoder is internal proprietary API and may be removed in a future release
String encryptedValue = new BASE64Encoder().encode(encVal);
^
AESencrp.java:29: warning: BASE64Decoder is internal proprietary API and may be removed in a future release
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
^
AESencrp.java:35: error: cannot find symbol
Key key = new SecretKeySpec(keyValue, ALGO);
^
symbol: class SecretKeySpec
location: class AESencrp
1 error
2 warnings
I have the same error.
DeleteAnyone know how to fix it?
Very Useful .. Thanks a lot
ReplyDeleteworking
ReplyDeleteVery useful. Thank you.
ReplyDeleteIt's very useful for me........Thanks you
ReplyDeleteHey there my encrypted string breaks after 77 characters and rest of the encrypted string goes to 2nd line. I want whole string in a single line. Can you help me in that ?
ReplyDeleteRegards.
Hey my encrypted string breaks after 77 characters and rest of the encrypted string goes to 2nd line. I want whole encrypted code in single line. Can you help in that ?
ReplyDeleteRegards.
Спасибо )
ReplyDeleteAESencrp.java:21: warning: BASE64Encoder is internal proprietary API and may be removed in a future release
ReplyDeleteString encryptedValue = new BASE64Encoder().encode(encVal);
^
AESencrp.java:29: warning: BASE64Decoder is internal proprietary API and may be removed in a future release
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
^
AESencrp.java:35: error: cannot find symbol
Key key = new SecretKeySpec(keyValue, ALGO);
^
symbol: class SecretKeySpec
location: class AESencrp
1 error
2 warnings
Hi, Thank a lot, it is working and very clear about it.
ReplyDeletevery useful ........ But a question.Why this program don't use many characters for its output? after encrypting ,i can see only +=/0-9A-Za-z chars,its for AES algorithm or its programming
ReplyDeletewhat is that packege nomad which you have used is it made by u or it is already given
ReplyDeleteexcuse me please..
ReplyDeleteHow can I use this codes with cloud computing?
I need to encrypt the text before upload it to cloud.
regards;
Farah
It is a great help. Thank you for the post
ReplyDeleteAwesome article. After day having sex with AES, I found working code. Thanx a lot and kudos to you!
ReplyDeletelol. Thanks.
Deleteerror parsing file. how to resolve?
ReplyDeleteThis is a great article. It gave me a lot of useful information. thank you very much. web data extraction services
ReplyDeleteReally helped me. Thank You
ReplyDeletethank you relly helped me
ReplyDeletecan anyone help me how to decrypt cerber3 files?
Deleteis this code possible to securing files such as .doc .txt etc ?
ReplyDeletehello sir iam srikanth. iam doing project on encryption algorithm which can be implemented in a sensor platform. can we do this? is this feasible? can u help me out. please help me at srikanthmadireddy44@gmail.com
ReplyDeleteIoT Consulting
ReplyDeleteIoT Solutions
IoT Solution and Services
IoT Consulting
if i compile this then it can occur error can't find symbol and its propritary for future release
ReplyDeleteKey key = generateKey();
ReplyDeleteCipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;
how it will works explain please
Key key = generateKey();
ReplyDeleteCipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;
this code how it will works ? explain in detail
i m getting exception javax.crypto.BadPaddingException: Given final block not properly padded
ReplyDeletehey there I am having a trouble with package nomads please help me resolve it
ReplyDeleteWill this code work in netbeans?
ReplyDeletehey I am getting error for Key key = generateKey(); saying that non-static method generateKey() cannot be referenced from a static context. please help.I am doing it on netbeans
ReplyDelete