前回の記事で暗号化したパスワードを復号化するサンプルです。
入力パスワードは16進数化されています。
private String decrypt(String passwd) throws Exception { //16進数から戻す byte[] cipherPass = toBytes(passwd);
//ソルト byte[] salt = {(byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c, (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99 }; // 繰り返し int num = 128; PBEParameterSpec pbeParam = new PBEParameterSpec(salt, num);
char[] pass = "passwordkey".toCharArray(); PBEKeySpec pbeKey = new PBEKeySpec(pass); SecretKeyFactory secKeys = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey secKey = secKeys.generateSecret(pbeKey);
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES"); cipher.init(Cipher.DECRYPT_MODE, secKey, pbeParam); //複号化 byte[] bytepass = cipher.doFinal(cipherPass); String decpass = new String(bytepass); return decpass; }
private 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; }
|