パスワードの暗号化・Javaの小技、サンプル、ニュースなどを紹介していきます。みんなで参考にしてください。

Ads by Google


上記の広告は1ヶ月以上更新のないブログに表示されています。
新しい記事を書く事で広告が消せます。

パスワードの暗号化


パスワードの暗号化サンプルです。
特にライブラリを追加する必要はありません。
最後に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();
}

Copyright © Javaテクニカルサンプル集 All Rights Reserved.
FC2ブログ 一戸建て
相互リンクRANGER