2

これが私のクラスのコードです:

        public class Md5tester {
private String licenseMd5 = "?jZ2$??f???%?";

public Md5tester(){
    System.out.println(isLicensed());
}
public static void main(String[] args){
    new Md5tester();
}
public boolean isLicensed(){
    File f = new File("C:\\Some\\Random\\Path\\toHash.txt");
    if (!f.exists()) {
        return false;
    }
    try {
        BufferedReader read = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
        //get line from txt
        String line = read.readLine();
        //output what line is
        System.out.println("Line read: " + line);
        //get utf-8 bytes from line
        byte[] lineBytes = line.getBytes("UTF-8");
        //declare messagedigest for hashing
        MessageDigest md = MessageDigest.getInstance("MD5");
        //hash the bytes of the line read
        String hashed = new String(md.digest(lineBytes), "UTF-8");
        System.out.println("Hashed as string: " + hashed);
        System.out.println("LicenseMd5: " + licenseMd5);
        System.out.println("Hashed as bytes: " + hashed.getBytes("UTF-8"));
        System.out.println("LicenseMd5 as bytes: " + licenseMd5.getBytes("UTF-8"));
        if (hashed.equalsIgnoreCase(licenseMd5)){
            return true;
        }
        else{
            return false;
        }
    } catch (FileNotFoundException e) {
        return false;
    } catch (IOException e) {           
        return false;
    } catch (NoSuchAlgorithmException e) {  
        return false;
    }
} 

}

これが私が得る出力です:

行の読み取り: テスト

文字列としてハッシュ: ?jZ2$??f???%?

LicenseMd5: ?jZ2$??f???%?

バイトとしてハッシュ: [B@5fd1acd3

バイトとしての LicenseMd5: [B@3ea981ca

間違い

何が問題なのかわからないので、誰かがこれを解決してくれることを願っています。

4

3 に答える 3

2

byte[]MD5 変換によって返される は任意のであるため、一部のエンコーディングbyte[]では の有効な表現として扱うことはできません。String

特に、は、出力エンコーディングで表現できないバイト?に対応します。?jZ2$??f???%?これは、コンテンツlicenseMd5が既に破損していることを意味するため、MD5 ハッシュを比較することはできません。

byte[]さらに比較するためにasを表現したい場合はString、任意の s の適切な表現を選択する必要がありますbyte[]。たとえば、Base64または 16 進文字列を使用できます。

byte[]次のように16進文字列に変換できます。

public static String toHex(byte[] in) {
    StringBuilder out = new StringBuilder(in.length * 2);
    for (byte b: in) {
        out.append(String.format("%02X", (byte) b));
    }
    return out.toString();
}

byte[]のデフォルト実装を使用することにも注意してくださいtoString()。その結果( など[B@5fd1acd3)は の内容とは関係がないbyte[]ため、あなたの場合は無意味です。

于 2012-10-14T17:03:30.827 に答える
1

?印刷された表現の記号は、hashed文字通りの疑問符ではなく、印刷できない文字です。

于 2012-10-14T17:00:54.510 に答える
0

このエラーは、UTF-8を使用して文字列をエンコードしているときにJavaファイル形式がUTF-8エンコードでない場合に発生します。UTF-8を削除してみると、md5が別の結果を出力します。文字列にコピーして、結果がtrueになることを確認できます。別の方法は、ファイルエンコーディングをUTF-8に設定することです。文字列エンコーディングも異なります。

于 2012-10-14T17:08:40.273 に答える