パスワードの暗号化サンプルです。
特にライブラリを追加する必要はありません。
最後に16進数化してます。データベースに入れる場合はその方が短くなりますしね。
private String encrypt(String passwd) throws Exception { byte[] bytepass = passwd.getBytes();
// ソルト 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.ENCRYPT_MODE, secKey, pbeParam); //暗号化 byte[] cipherPass = cipher.doFinal(bytepass); //16進数化 String encpass = toHexString(cipherPass); return encpass; }
private 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(); }
|