How to encrypt & decrypt the password in JAVA for Selenium Web Driver
package
org.processmining.plugins.security;
import
java.io.BufferedReader;
import
java.io.BufferedWriter;
import
java.io.DataInputStream;
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.FileWriter;
import
java.io.InputStreamReader;
import
java.security.Key;
import
javax.crypto.Cipher;
import
javax.crypto.spec.SecretKeySpec;
import
sun.misc.BASE64Decoder;
import
sun.misc.BASE64Encoder;
public class
AESencrp {
private static final String ALGO =
"AES";
private
static final byte[] keyValue = new
byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't','S', 'e', 'c', 'r','e', 't', 'K',
'e', 'y' };
public
static String encrypt(String Data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal =
c.doFinal(Data.getBytes());
String encryptedValue = new
BASE64Encoder().encode(encVal);
return encryptedValue;
}
public static String decrypt(String
encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new
BASE64Decoder().decodeBuffer(encryptedData);
byte[] decValue =
c.doFinal(decordedValue);
String decryptedValue = new
String(decValue);
return decryptedValue;
}
private static Key generateKey() throws
Exception {
Key key = new SecretKeySpec(keyValue,
ALGO);
return key;
}
public static void encodeFile() {
// writer
File selectedFileWrite = new
File("C:\\testSecEnc.txt");
// reader
File selectedFileRead = new
File("C:\\testSec.txt");
FileInputStream fstream = null;
try {
// writer
BufferedWriter bw = new
BufferedWriter(new FileWriter(selectedFileWrite, true));
// reader
fstream = new
FileInputStream(selectedFileRead);
DataInputStream in =
new DataInputStream(fstream);
BufferedReader br = new
BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine =
br.readLine()) != null) {
String strLineEnc =
AESencrp.encrypt(strLine);
System.out.println("Plain Text : " + strLine);
System.out.println("Encrypted Text : " + strLineEnc);
// write
bw.write(strLineEnc);
bw.newLine();
}
bw.close();
br.close();
System.out.println("done!");
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
throws Exception {
AESencrp.encodeFile();
// String password =
"mypassword";
// String passwordEnc =
AESencrp.encrypt(password);
// String passwordDec =
AESencrp.decrypt(passwordEnc);
//
// System.out.println("Plain Text :
" + password);
// System.out.println("Encrypted Text
: " + passwordEnc);
// System.out.println("Decrypted Text
: " + passwordDec);
}
}
Comments
Post a Comment