java - Java 中的 CRC32 哈希

标签 java android hash crc32

我正在尝试在 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 附加到字符串中,这是一种方法,我希望这就是您正在寻找的。

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/

相关文章:

java - 使用额外回调处理自定义登录

java - JSOUP 解析表格中的表单字段和标签

java - 寻找wordnet中同义词集之间的距离

arrays - Perl:匿名数组的模板?

c# - 序列化 HashSet

java - Vaadin 提供实时图表吗?

Android 应用程序在崩溃/强制关闭时重新启动

android - React Native 找不到 com.android.support :appcompat-v7:${supportVersion}

java - 如何在 android 的 firebase 数据库中跳过子项

perl - 在 Perl 中将整个文件读入散列