質問

I am trying to create a crc32 hash of a string in java. I was able to do that with java.util.zip.CRC32. But my requirement is to create the CRC32 hash of a string using a secret key. Can anyone tell me how to do this? Thanks in advance...

My existing code is given below...

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

String enc = Long.toHexString(crc.getValue());
System.out.println(enc);
役に立ちましたか?

解決 3

Using a salt ensures the hashed string doesn't have the same hash than with another salt or without salt.

It's usually done with a simple concatenation :

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

But it's a little surprising here : salting is usually done for security, and CRC32 isn't normally used for cryptography, it's a non secure hash used for redundancy check or indexing keys.

他のヒント

I figured you needed to append this key to your string before updating your crc32 class, this would be one way to do it, I hope this is what you're looking for.

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);

    }
}

You can do it like this:

public static String getCRC32(byte[] data){
        CRC32 fileCRC32 = new CRC32();
        fileCRC32.update(data);
        return String.format(Locale.US,"%08X", fileCRC32.getValue());
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top