public class PasswordCipher{
public String encrypt(String password) throws Exception{
try{
//String-->byte[]
byte[] btePassword = password.getBytes("Shift_JIS");
// Salt
byte[] salt = {
(byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
(byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
};
// Iteration count
int count = 20;
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
char[] pass = "abcdefgh".toCharArray();
PBEKeySpec pbeKeySpec = new PBEKeySpec(pass);
SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
Cipher descipher = Cipher.getInstance("PBEWithMD5AndDES");
descipher.init(Cipher.ENCRYPT_MODE,pbeKey,pbeParamSpec);
//暗号化
byte[] cipherPassword = descipher.doFinal(btePassword);
//byte[]-->String
String strPassword = toHexString(cipherPassword);
return strPassword;
}catch(Exception exc){
//エラー処理
}
}
public String decript(String strPassword)throws Exception{
try{
//String-->byte[]
byte[] cipherPassword = toBytes(strPassword);
// Salt
byte[] salt = {
(byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
(byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
};
// Iteration count
int count = 20;
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
char[] pass = "abcdefgh".toCharArray();
PBEKeySpec pbeKeySpec = new PBEKeySpec(pass);
SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
Cipher descipher = Cipher.getInstance("PBEWithMD5AndDES");
descipher.init(Cipher.DECRYPT_MODE,pbeKey,pbeParamSpec);
//複号化
byte[] btePassword = descipher.doFinal(cipherPassword);
//byte[]-->String
String password = new String(cipherPassword,"Shift_JIS");
return password;
}catch(Exception exc){
//エラー処理
}
}
//byte[]-->String
public static String toHexString(byte[] bs) {
StringBuffer buffer = new StringBuffer(bs.length * 2);
for (int i = 0; i < bs.length; i++) {
if(bs[i] >= 0 && bs[i]<0x10){
buffer.append('0');
}
buffer.append(Integer.toHexString(0xff&bs[i]));
}
return buffer.toString();
}
//String-->byte[]
public static byte[] toBytes(String hexString) throws NumberFormatException{
if(hexString.length()%2==1){
hexString = '0' + hexString;
}
byte[] bytes = new byte[hexString.length()/2];
for (int i = bytes.length-1; i >= 0; i--) {
String b = hexString.substring(i*2,i*2+2);
bytes[i] = (byte)Integer.parseInt(b, 16);
}
return bytes;
}
}
|