Created
August 28, 2017 14:08
-
-
Save mageddo/7286d1c51bdb8877b4124ddacb492ac3 to your computer and use it in GitHub Desktop.
Encrypt and Decrypt with Streams
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
| public static void main(String[] args) throws Exception { | |
| final Key key = generateSymmetricKey("SecretKey".getBytes()); | |
| // encrypting | |
| final Cipher cEncrypter = Cipher.getInstance("DESede/ECB/PKCS7Padding"); | |
| cEncrypter.init(Cipher.ENCRYPT_MODE, key); | |
| final ByteArrayOutputStream bos = new ByteArrayOutputStream(); | |
| try( | |
| CipherOutputStream encrypterStream = new CipherOutputStream(bos, cEncrypter); | |
| PrintWriter writer = new PrintWriter(new OutputStreamWriter(encrypterStream)) | |
| ){ | |
| writer.println("Encrypted messsage!"); | |
| } | |
| // decrypting | |
| final Cipher cDecrypter = Cipher.getInstance("DESede/ECB/PKCS7Padding"); | |
| cDecrypter.init(Cipher.DECRYPT_MODE, key); | |
| try( | |
| CipherInputStream decrypterStream = new CipherInputStream(new ByteArrayInputStream(bos.toByteArray()), cDecrypter); | |
| BufferedReader reader = new BufferedReader(new InputStreamReader(decrypterStream)) | |
| ){ | |
| System.out.println(reader.readLine()); | |
| } | |
| } | |
| private static Key generateSymmetricKey(byte[] password) throws Exception { | |
| final MessageDigest digester = MessageDigest.getInstance("SHA"); | |
| digester.update(password); | |
| return new SecretKeySpec(Arrays.copyOf(digester.digest(), 24), "DESede"); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment