2013-12-16 35 views
0

我正尝试在java中创建一个字符串的crc32散列。我可以用java.util.zip.CRC32来做到这一点。但我的要求是使用密钥创建一个字符串的CRC32哈希。谁能告诉我如何做到这一点?在此先感谢...Java中的CRC32散列

我现有的代码如下......

String a = "abcdefgh"; 
CRC32 crc = new CRC32(); 
crc.update(a.getBytes()); 

String enc = Long.toHexString(crc.getValue()); 
System.out.println(enc); 
+0

你的意思是使用盐? –

+0

是的......我需要用盐.. – akh

+0

为什么? CRC32不适用于密码学。 –

回答

0

使用盐确保散列串不具有相同的哈希比其他盐或不放盐。

它通常用一个简单的拼接完成:

String a = "your string you want to hash" + "the salt"; 

但它在这里有点令人惊讶:腌制通常为了安全完成,CRC32通常不用于加密,它是用于非安全散列冗余检查或索引键。

+0

感谢您的回答......其实这将完成我的工作:) – akh

+0

切勿将盐放在字符串末尾;至少对于像CRC32这样的不安全散列算法来说。盐应该始终在字符串的开头。[见这里](http://www.skrenta.com/2007/08/md5_tutorial.html#comment-10072)。 – Flimzy

+0

@Flimzy正如我在评论中所说,CRC32不适合加密。当目的是crytptography时,您使用正确的散列算法,并且无论盐是否结束都没关系。 –

0

我想你需要在更新你的crc32类之前将这个键附加到你的字符串,这将是一种方法,我希望这是你正在寻找的。

import java.nio.ByteBuffer; 
import java.security.SecureRandom; 
import java.util.zip.CRC32; 

public class example { 

public void main(){ 

    ///this is user supplied string 
    String a = "ABCDEFGHI"; 
    int mySaltSizeInBytes = 32; 
    //SecureRandom class provides strong random numbers 
    SecureRandom random = new SecureRandom(); 

    //salt mitigates dictionary/rainbow attacks 
    byte salt[] = new byte[mySaltSizeInBytes]; 

    //random fill salt buffer with random bytes 
    random.nextBytes(salt); 

    //concatenates string a and salt 
    //into one big bytebuffer ready to be digested 
    //this is just one way to do it 
    //there might be better ways 

    ByteBuffer bbuffer = ByteBuffer.allocate(mySaltSizeInBytes+a.length()); 
    bbuffer.put(salt); 
    bbuffer.put(a.getBytes()); 

    //your crc class 
    CRC32 crc = new CRC32(); 
    crc.update(bbuffer.array()); 
    String enc = Long.toHexString(crc.getValue()); 
    System.out.println(enc); 

    } 
} 
0

你可以这样说:

public static String getCRC32(byte[] data){ 
     CRC32 fileCRC32 = new CRC32(); 
     fileCRC32.update(data); 
     return String.format(Locale.US,"%08X", fileCRC32.getValue()); 
    }