我正在尝试在java中创建字符串的crc32哈希。我能够用java.util.zip.CRC32做到这一点。但我的要求是使用密钥创建字符串的CRC32哈希值。谁能告诉我怎么做?提前谢谢......
我现有的代码如下......
String a = "abcdefgh";
CRC32 crc = new CRC32();
crc.update(a.getBytes());
String enc = Long.toHexString(crc.getValue());
System.out.println(enc);
答案 0 :(得分:0)
使用salt可确保散列字符串与另一个盐或没有盐的哈希值相同。
通常使用简单的连接来完成:
String a = "your string you want to hash" + "the salt";
但这里有点令人惊讶:salting通常用于安全性,CRC32通常不用于加密,它是用于冗余检查或索引键的非安全散列。
答案 1 :(得分:0)
我认为你需要在更新你的crc32类之前将这个键附加到你的字符串,这将是一种方法,我希望这是你正在寻找的。 p>
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);
}
}
答案 2 :(得分:0)
你可以这样做:
public static String getCRC32(byte[] data){
CRC32 fileCRC32 = new CRC32();
fileCRC32.update(data);
return String.format(Locale.US,"%08X", fileCRC32.getValue());
}