Skip to content

Instantly share code, notes, and snippets.

@sandipchitale
Created July 20, 2019 19:17
Show Gist options
  • Save sandipchitale/499ed23f0913790be9d64ce521f4a2bf to your computer and use it in GitHub Desktop.
Save sandipchitale/499ed23f0913790be9d64ce521f4a2bf to your computer and use it in GitHub Desktop.
Encrypt and decrypt with secret in Java
try {
byte[] secretBytes = "secretsecretsecr".getBytes();
Cipher c = Cipher.getInstance("AES");
SecretKeySpec k =
new SecretKeySpec(secretBytes, "AES");
c.init(Cipher.ENCRYPT_MODE, k);
byte[] encryptedData = c.doFinal("I am carl sagan.".getBytes());
encryptedData[3] = 7;
c.init(Cipher.DECRYPT_MODE, k);
byte[] data = c.doFinal(encryptedData);
System.out.println(new String(data));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment