Crypto: Use pooled SHA256 instances in Noise lib

This commit is contained in:
zzz
2025-02-07 11:45:56 -05:00
parent b2e80fce3d
commit 8b9f61b1d4
2 changed files with 19 additions and 8 deletions

View File

@ -30,6 +30,9 @@ import java.util.Arrays;
import javax.crypto.BadPaddingException;
import net.i2p.crypto.SHA256Generator;
/**
* Utility functions for the Noise protocol library.
*/
@ -72,15 +75,8 @@ public final class Noise {
*/
public static MessageDigest createHash(String name) throws NoSuchAlgorithmException
{
// Look for a JCA/JCE provider first and if that doesn't work,
// use the fallback implementations in this library instead.
// The only algorithm that is required to be implemented by a
// JDK is "SHA-256", although "SHA-512" is fairly common as well.
if (name.equals("SHA256")) {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
}
return SHA256Generator.getInstance().acquire();
}
throw new NoSuchAlgorithmException("Unknown Noise hash algorithm name: " + name);
}
@ -88,6 +84,18 @@ public final class Noise {
// The rest of this class consists of internal utility functions
// that are not part of the public API.
/**
* I2P Release a hash object back to the pool.
*
* @since 0.9.66
*/
static void releaseHash(MessageDigest hash)
{
if (hash.getAlgorithm().equals("SHA-256")) {
SHA256Generator.getInstance().release(hash);
}
}
/**
* Destroys the contents of a byte array.
*

View File

@ -62,6 +62,7 @@ class SymmetricState implements Destroyable, Cloneable {
md.digest(INIT_HASH_N, 0, 32);
md.update(INIT_CK_XK_SSU2, 0, 32);
md.digest(INIT_HASH_XK_SSU2, 0, 32);
Noise.releaseHash(md);
} catch (Exception e) {
throw new IllegalStateException(e);
}
@ -87,6 +88,7 @@ class SymmetricState implements Destroyable, Cloneable {
MessageDigest hash = Noise.createHash("SHA256");
hash.update(protocolNameBytes, 0, protocolNameBytes.length);
hash.digest(rv, 0, 32);
Noise.releaseHash(hash);
} catch (Exception e) {
throw new IllegalStateException(e);
}
@ -403,6 +405,7 @@ class SymmetricState implements Destroyable, Cloneable {
public void destroy() {
cipher.destroy();
hash.reset();
Noise.releaseHash(hash);
Noise.destroy(ck);
Noise.destroy(h);
Noise.destroy(prev_h);