forked from sudharsan13296/Cryptography-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAESEncryption.java
More file actions
50 lines (41 loc) · 1.75 KB
/
AESEncryption.java
File metadata and controls
50 lines (41 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.xml.bind.DatatypeConverter;
public class AESEncryption
{
public static void main(String[] args) throws Exception {
String plainText = "Hello World";
SecretKey secKey = getSecretEncryptionKey();
byte[] cipherText = encryptText(plainText, secKey);
String decryptedText = decryptText(cipherText, secKey);
System.out.println("Original Text:" + plainText);
System.out.println("AES Key (Hex Form):"+bytesToHex(secKey.getEncoded()));
System.out.println("Encrypted Text (Hex Form):"+bytesToHex(cipherText));
System.out.println("Descrypted Text:"+decryptedText);
}
public static SecretKey getSecretEncryptionKey() throws Exception{
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128);
SecretKey secKey = generator.generateKey();
return secKey;
}
public static byte[] encryptText(String plainText,SecretKey secKey) throws Exception
{
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
return byteCipherText;
}
public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws Exception
{
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.DECRYPT_MODE, secKey);
byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
return new String(bytePlainText);
}
private static String bytesToHex(byte[] hash)
{
return DatatypeConverter.printHexBinary(hash);
}
}