package com.ericsson.dve.custom.authenticationplugin;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Scanner;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class Encyptor {
private Cipher c;
private static byte[] caay = {99, 61, 84, -69, 84, 56, -42, 114, -10, 124, 31, -48, -27, 3, 40, 56};
private SecretKey cay;
public Encyptor() throws NoSuchAlgorithmException, NoSuchPaddingException{
Security.addProvider(new com.sun.crypto.provider.SunJCE());
cay = new SecretKeySpec(caay, "AES");
c = Cipher.getInstance("AES");
}
/**
*
*
* @param str
* @return
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public String Encrytor(String str) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
c.init(Cipher.ENCRYPT_MODE, cay);
byte[] src = str.getBytes();
byte[] cipherByte = c.doFinal(src);
String base64Byte = new String(Base64.encodeBase64(cipherByte));
return base64Byte;
}
/**
* 对字符串解密
*
* @param buff
* @return
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws IOException
*/
public String Decryptor(String encpytedCode) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException, IOException {
c.init(Cipher.DECRYPT_MODE, cay);
byte[] base64Byte = Base64.decodeBase64(encpytedCode.getBytes());
byte[] cipherByte = c.doFinal(base64Byte);
return new String(cipherByte);
}
/**
* @param args
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws InvalidKeyException
*/
public static void main(String[] args) {
// String msg ="郭XX-搞笑相声全集";
// String msg ="secret";
// System.out.println("text:" + msg);
// String encypted;
//try {
//encypted = new Encyptor().Encrytor(msg);
//System.out.println("after encode: " + new Encyptor().Encrytor(msg));
// System.out.println("after decode: " + new Encyptor().Decryptor(encypted));
//} catch (Exception e) {
//e.printStackTrace();
//}
System.out.println("please input password, please input 'exit' to exit");
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String s = scan.next();
if("exit".equalsIgnoreCase(s)){
break;
}
try {
String encypted = new Encyptor().Encrytor(s);
System.out.println("after encode: " + new Encyptor().Encrytor(s));
System.out.println("after decode: " + new Encyptor().Decryptor(encypted));
} catch (Exception e) {
e.printStackTrace();
}
}
scan.close();
}
}