简单示例哈希只有一个字节的数组:
import java.security.MessageDigest;
import java.util.Arrays;
import org.bouncycastle.jcajce.provider.digest.Keccak;
public class Program {
public static void main(String[ ] args) {
// MessageDigest:
byte[] state = { (byte) 1};
try {
MessageDigest md5 = MessageDigest.getInstance("SHA-384");
byte[] digest = md5.digest(state);
System.out.println("A: " + Arrays.toString(digest));
} catch (Exception e) {}
// BouncyCastle Keccak:
Keccak.Digest384 keccak = new Keccak.Digest384();
keccak.update(state);
try {
byte[] digest = new byte[48];
keccak.digest(digest, 0, 48);
System.out.println("B: " + Arrays.toString(digest));
} catch (Exception e) {}
}
}
该程序的输出如下:
A:[ - 115,44,-24,125,-122,-11,95,-49,-85,119,10,4,123,9,13,-94,50,112, - 6,32,104,50,-33,-22,126,12,-108,111,-1,69,31,-127,-102,-35,36,35,116,-66,85, 27,13,99,24,-19,108,125,65,-40]
B:[45,-11,56,-101,-127,15,27,78,83,13,3,-41,58,-24,82,-74,37,-120, - 70,20,26,16,66,76,2,104,-22,-24,-58,79,-81,58,-71,1,-14,-115,-27,85,73, -70,-8,113,-67,-93,-19,62,-15,65]
它们不应该是相同的还是我错过了什么?
使用的BouncyCastle版本: https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on/1.58
Java:jdk1.8.0_121
答案 0 :(得分:3)
“SHA-384”是SHA2系列的散列函数,具有384位输出。你想要“SHA3-384”。这里有一些示例代码使用您的示例和Bobulous'示例。
for (int i = 0; i < 2; i++){
x1[i] = (i>0) ? starting_x + x2[i-1] : starting_x;
...
if (i>0) {
drawLine(...)
}
}
,输出为:
import org.bouncycastle.jcajce.provider.digest.SHA3;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.MessageDigest;
import java.security.Security;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
MessageDigest md5 = MessageDigest.getInstance("SHA-384");
byte[] state = new byte[]{1};
byte[] digest = md5.digest(state);
System.out.println("A: " + Arrays.toString(digest));
md5 = MessageDigest.getInstance("SHA3-384");
digest = md5.digest(state);
System.out.println("B: " + Arrays.toString(digest));
SHA3.DigestSHA3 sha3 = new SHA3.DigestSHA3(384);
digest = sha3.digest(state);
System.out.println("C: " + Arrays.toString(digest));
}
}
答案 1 :(得分:2)
我相信您现有的代码正在使用Bouncy Castle来创建Keccak哈希函数。 Keccak是SHA-3摘要函数的超集,SHA-3需要在Keccak函数上配置特定设置,因此使用不同的Keccak配置会给SHA-3带来不同的结果。
如果您打电话给Bouncy Castle,请尝试以下方式:
import org.bouncycastle.jcajce.provider.digest.SHA3.DigestSHA3;
import org.bouncycastle.jcajce.provider.digest.SHA3.Digest384;
public class Program {
public static void main(String[ ] args) {
/* EARLIER CODE OMITTED */
SHA3.DigestSHA3 sha3 = new SHA3.DigestSHA3(384);
sha3.update(state);
System.out.println("B: " + Arrays.toString(md.digest()));
}
}
我目前没有安装Bouncy Castle,但我相信这会让Bouncy Castle使用SHA-3(384)哈希函数。