Skip to content

Instantly share code, notes, and snippets.

@osgix
Created May 10, 2017 08:29
Show Gist options
  • Save osgix/8636019824305e929b9fdf8d56176857 to your computer and use it in GitHub Desktop.
Save osgix/8636019824305e929b9fdf8d56176857 to your computer and use it in GitHub Desktop.
How to use (AES) symmetric key cryptography with java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class AesDemo {
private static final String ENC_FILE = "encryptedtext.txt";
private static final String SECRET_KEY_FILE = "secretkey.txt";
public static void main(String[] args) throws Exception{
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SECRET_KEY_FILE));
oos.writeObject(secretKey);
oos.close();
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherTextBytes1 = cipher.doFinal("My name is yogesh".getBytes());
try {
FileWriter fw = new FileWriter(ENC_FILE);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(Base64.getEncoder().encodeToString(cipherTextBytes1));
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
byte[] cipherTextBytes2 = null;
try {
FileReader fr = new FileReader(ENC_FILE);
BufferedReader br = new BufferedReader(fr);
cipherTextBytes2 = Base64.getDecoder().decode(br.readLine());
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] bytePlainText = cipher.doFinal(cipherTextBytes2);
System.out.println(new String(bytePlainText));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment