java - AES encryption returning different values on different machines -
my aes encryption program returning different encrypted values on different machines. can please on finding out needs done ensure same encrypted value returned on machine program run..
private static secretkeyspec secret; private static string seed; private static string text; private static string salt = "salt123"; private static int pswditerations = 65536; private static int keysize = 256; /** * * @param myseed */ public static void setseed(string myseed) { try { byte[] saltbytes = salt.getbytes("utf-8"); pbekeyspec spec = new pbekeyspec(myseed.tochararray(), saltbytes, pswditerations, keysize); secretkeyfactory factory = secretkeyfactory .getinstance("pbkdf2withhmacsha1"); secretkey secretkey = factory.generatesecret(spec); secret = new secretkeyspec(secretkey.getencoded(), "aes"); } catch (nosuchalgorithmexception e) { e.printstacktrace(); } catch (unsupportedencodingexception e) { e.printstacktrace(); } catch (invalidkeyspecexception e) { e.printstacktrace(); } } public static string getencryptedstringfor(string text) { try { cipher cipher = cipher.getinstance("aes/ecb/pkcs5padding"); cipher.init(cipher.encrypt_mode, secret); byte[] encrypteddata = cipher.dofinal(text.getbytes("utf-8")); return new string(base64.encodebase64(encrypteddata)); } catch (exception e) { system.out.println("error while encrypting: " + e.tostring()); } return null; } public static string getdecryptedstringfor(string text) { try { cipher cipher = cipher.getinstance("aes/ecb/pkcs5padding"); cipher.init(cipher.decrypt_mode, secret); return (new string(cipher.dofinal(base64 .decodebase64(text.getbytes("utf-8"))))); } catch (exception e) { system.out.println("error while decrypting: " + e.tostring()); } return null; }
some sample values
- seed : seed123
- text : #text!
encrypted value : rove3ksjzn0nnxcnsnprpg==
seed : seed!!
- text : #text123!
- encrypted value :x6pfukcvxxraeyqkko/kfq==
the thing can see in code following line:
return (new string(cipher.dofinal(base64.decodebase64(text.getbytes("utf-8")))));
now looks returning string after decoding utf-8. doesn't: uses platform default:
return (new string( cipher.dofinal( base64.decodebase64( text.getbytes("utf-8") ) ) ));
of course, first (
superfluous anyway, try this:
byte[] ciphertext = base64.decodebase64(text.getbytes("utf-8")); byte[] plaintext = cipher.dofinal(ciphertext); return new string(plaintext, "utf-8");
note can use import static java.nio.charsets.standardcharsets.utf_8
nowadays, lets away exception well. wish same standardciphers.aes_cbc_pkcs7padding :)
Comments
Post a Comment