How to encrypt a stringbuilder message using AES algorithm in java -
i have stringbuilder message appended "||" symbol.(ex: hi||how||are||26 04 2016||finish) have encrypt message , send server using aes , decrypt same @ server side. can me out in solving this?
you can encrypt , decrypt this:
public class aes { public static byte[] encrypt(string key, string initvector, string value) { try { ivparameterspec vector = new ivparameterspec(initvector.getbytes("utf-8")); secretkeyspec secretkey = new secretkeyspec(key.getbytes("utf-8"), "aes"); cipher cipher = cipher.getinstance("aes/cbc/pkcs5padding"); cipher.init(cipher.encrypt_mode, secretkey, vector); byte[] encrypted = cipher.dofinal(value.getbytes()); system.out.println("encrypted string: "+ base64.encodebase64(encrypted)); return base64.encodebase64(encrypted); } catch (exception ex) { ex.printstacktrace(); } return null; } public static string decrypt(string key, string initvector, byte[] encrypted) { try { ivparameterspec vector = new ivparameterspec(initvector.getbytes("utf-8")); secretkeyspec secretkey = new secretkeyspec(key.getbytes("utf-8"), "aes"); cipher cipher = cipher.getinstance("aes/cbc/pkcs5padding"); cipher.init(cipher.decrypt_mode, secretkey, vector); byte[] original = cipher.dofinal(base64.decodebase64(encrypted)); return new string(original); } catch (exception ex) { ex.printstacktrace(); } return null; } public static void main(string[] args) { string key = "foo12345bar67890"; // 128 bit key string initvector = "randominitvector"; // 16 bytes iv stringbuilder sb = new stringbuilder("hi||how||are||26 04 2016||finish"); //your text here byte[] encryptedbytes = encrypt(key, initvector, sb.tostring()); system.out.println(decrypt(key, initvector,encryptedbytes)); } }
Comments
Post a Comment