Last active
May 12, 2020 09:13
-
-
Save Soontao/fca1b8e3ad4d7ed02caa818b84fb5c5f to your computer and use it in GitHub Desktop.
AES Cipher Check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // please run with jjs | |
| var Cipher = javax.crypto.Cipher; | |
| var KeyGenerator = javax.crypto.KeyGenerator; | |
| var String = java.lang.String; | |
| var Arrays = java.util.Arrays; | |
| var SecureRandom = java.security.SecureRandom; | |
| var SecretKeySpec = javax.crypto.spec.SecretKeySpec; | |
| var share_secret_seed = "share_secret_seed"; | |
| var raw_text = "no man is an island"; | |
| var raw_bytes = raw_text.getBytes("UTF-8"); | |
| function get_key(seed) { | |
| // https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html#SecureRandomImp | |
| // you must set the algorithm as 'SHA1PRNG', because the different platform have different impl | |
| var random = SecureRandom.getInstance("SHA1PRNG"); | |
| random.setSeed(seed.getBytes()); | |
| var keyGenerator = KeyGenerator.getInstance("AES"); | |
| keyGenerator.init(256, random); | |
| var hashed_key = keyGenerator.generateKey().getEncoded() | |
| return new SecretKeySpec(hashed_key, "AES"); | |
| } | |
| function encrypt(bytes, secret) { | |
| var cipher = Cipher.getInstance("AES"); | |
| var key = get_key(secret) | |
| cipher.init(Cipher.ENCRYPT_MODE, key); | |
| return cipher.doFinal(bytes); | |
| } | |
| function decrypt(bytes, secret) { | |
| var cipher = Cipher.getInstance("AES"); | |
| var key = get_key(secret) | |
| cipher.init(Cipher.DECRYPT_MODE, key); | |
| return cipher.doFinal(bytes); | |
| } | |
| var encrypted_bytes = encrypt(raw_bytes, share_secret_seed) | |
| var decrypted_bytes = decrypt(encrypted_bytes, share_secret_seed) | |
| print("raw text:\t" + Arrays.toString(raw_bytes)); | |
| print("encrypted:\t" + Arrays.toString(encrypted_bytes)); | |
| print("decrypted:\t" + Arrays.toString(decrypted_bytes)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment