2016-11-03 3 views
1

誰でも次のコードが常に同じハッシュを返さない理由を教えていただけますか?ハッシュは異なる可能性が唯一の方法は、ランダムな塩によるものですが、マニュアルに従って、私はあなたのバグがそのあなたという事実に関連している0sha-256がsaltを使わずに常に同じハッシュを返すとは限りません

public static void main(String[] args) { 
    char[] password = "test_pass".toCharArray(); 
    String str = encodePassword(password); 

    System.out.printf(
     "Byte digest '%s'\n", 
     String.valueOf(Hex.encodeHex(Base64.decodeBase64(str))) 
    ); 
} 

static StandardByteDigester digester = new StandardByteDigester(); 
{ 
    digester.setAlgorithm("SHA-256"); 
    digester.setIterations(100000); 
    digester.setSaltSizeBytes(0); 
    digester.initialize(); 
} 

public static String encodePassword(char[] rawPass) { 
    return new String(Base64.encodeBase64(digester.digest(toBytes(rawPass)))); 
} 

public static byte[] toBytes(char[] ch) { 
    Charset charset = Charset.defaultCharset(); 
    ByteBuffer buff = charset.encode(CharBuffer.wrap(ch)); 
    byte[] tmp = new byte[buff.limit()]; 
    buff.get(tmp); 
    return tmp;  
} 
+0

jasyptのどのバージョンをお使いですか? – Asoub

答えて

3

に塩のサイズを設定することにより、塩を無効にしています私の知る限りそれはランダムな塩でデフォルトの設定を使用していますので、終わりにあなたの静的フィールドStandardByteDigester digesterではなく、あなたのクラスのインスタンスを作成したことがないとして、それが呼び出されないよう静的初期化子圏インスタンス初期化子ブロックに初期化します。

このお試しください:

public static String encodePassword(String rawPass) { 
    return new String(
     Base64.encodeBase64(digester.digest(rawPass.getBytes(StandardCharsets.UTF_8))), 
     StandardCharsets.US_ASCII 
    ); 
} 
を:あなたは、単に次のようgetBytes(Charset)を呼び出すことができますよう、あなたの方法encodePasswordではなくchar配列のStringを取った場合あなたのコードを簡素化することができ

static { 
    digester.setAlgorithm("SHA-256"); 
    digester.setIterations(100000); 
    digester.setSaltSizeBytes(0); 
    digester.initialize(); 
} 

NB:プラットフォームのデフォルトの文字セットに依存するのは良い習慣ではありません。その場合、ここでコードはプラットフォームに依存するため、基数64文字がすべてUS_ASCIIに含まれているので、この文字セットを使用してデコードします。

+1

ありがとう、これは確かにそれを解決:) – user2817219

関連する問題