From b661f6a2db6b4358dfe02cd40fd531d801cdd1e0 Mon Sep 17 00:00:00 2001 From: Bert Massop Date: Mon, 12 May 2025 22:50:35 +0200 Subject: [PATCH] Do not synchronize on global variable in CryptoKey.fingerprint Unlikely to lead to any real-world performance gains as this code is seldom used, but more the reason to just get a fresh digest when needed. --- src/freenet/crypt/CryptoKey.java | 21 +++++---------------- src/freenet/crypt/DSAPublicKey.java | 11 ++++++----- 2 files changed, 11 insertions(+), 21 deletions(-) diff --git a/src/freenet/crypt/CryptoKey.java b/src/freenet/crypt/CryptoKey.java index 03bf306c5f..272a4787d7 100644 --- a/src/freenet/crypt/CryptoKey.java +++ b/src/freenet/crypt/CryptoKey.java @@ -10,7 +10,6 @@ import java.lang.reflect.Method; import java.math.BigInteger; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import freenet.support.HexUtil; import freenet.support.Logger; @@ -18,15 +17,6 @@ public abstract class CryptoKey implements CryptoElement, Serializable { private static final long serialVersionUID = 1L; - protected static final MessageDigest shactx; - static { - try { - shactx = MessageDigest.getInstance("SHA1", Util.mdProviders.get("SHA1")); - } catch(NoSuchAlgorithmException e) { - // impossible - throw new Error(e); - } - } CryptoKey() { } @@ -57,13 +47,12 @@ public static CryptoKey read(InputStream i) throws IOException, CryptFormatExcep public abstract byte[] asBytes(); protected byte[] fingerprint(BigInteger[] quantities) { - synchronized (shactx) { - for (BigInteger quantity: quantities) { - byte[] mpi = Util.MPIbytes(quantity); - shactx.update(mpi, 0, mpi.length); - } - return shactx.digest(); + MessageDigest shactx = HashType.SHA1.get(); + for (BigInteger quantity: quantities) { + byte[] mpi = Util.MPIbytes(quantity); + shactx.update(mpi, 0, mpi.length); } + return shactx.digest(); } public String verboseToString() { diff --git a/src/freenet/crypt/DSAPublicKey.java b/src/freenet/crypt/DSAPublicKey.java index ec751a430d..c978c6fb82 100644 --- a/src/freenet/crypt/DSAPublicKey.java +++ b/src/freenet/crypt/DSAPublicKey.java @@ -22,7 +22,7 @@ public class DSAPublicKey extends CryptoKey implements StorableBlock { public static final int HASH_LENGTH = 32; /** Null means use Global.DSAgroupBigA. This makes persistence simpler. */ private final DSAGroup group; - private byte[] fingerprint = null; + private volatile byte[] fingerprint; public DSAPublicKey(DSAGroup g, BigInteger y) { if(y.signum() != 1) @@ -151,11 +151,12 @@ public byte[] asPaddedBytes() { @Override public byte[] fingerprint() { - synchronized(this) { - if(fingerprint == null) - fingerprint = fingerprint(new BigInteger[]{y}); - return fingerprint; + byte[] fingerprint = this.fingerprint; + if (fingerprint == null) { + fingerprint = fingerprint(new BigInteger[]{y}); + this.fingerprint = fingerprint; } + return fingerprint; } public boolean equals(DSAPublicKey o) {