我正在尝试在 java 中创建字符串的 crc32 哈希。我可以使用 java.util.zip.CRC32 来做到这一点。但我的要求是使用 key 创建字符串的 CRC32 哈希值。谁能告诉我该怎么做?提前致谢...
我现有的代码如下...
String a = "abcdefgh";
CRC32 crc = new CRC32();
crc.update(a.getBytes());
String enc = Long.toHexString(crc.getValue());
System.out.println(enc);
最佳答案
我认为您需要在更新 crc32 类之前将此 key 附加到字符串中,这是一种方法,我希望这就是您正在寻找的。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);
}
}
关于java - Java 中的 CRC32 哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20605516/