diff --git a/common/src/main/java/org/tron/common/utils/StringUtil.java b/common/src/main/java/org/tron/common/utils/StringUtil.java
index d4958475394..2d19f1f62d6 100644
--- a/common/src/main/java/org/tron/common/utils/StringUtil.java
+++ b/common/src/main/java/org/tron/common/utils/StringUtil.java
@@ -44,17 +44,22 @@ public static ByteString hexString2ByteString(String hexString) {
return ByteString.copyFrom(ByteArray.fromHexString(hexString));
}
+ /**
+ * Checks for non-empty, even-length ASCII hex with an optional {@code 0x} prefix.
+ */
public static boolean isHexadecimal(String str) {
if (str == null || str.isEmpty()) {
return false;
}
- if (str.length() % 2 != 0) {
+ int start = str.startsWith("0x") ? 2 : 0;
+ if (str.length() == start || str.length() % 2 != 0) {
return false;
}
- for (int i = 0; i < str.length(); i++) {
+ for (int i = start; i < str.length(); i++) {
char c = str.charAt(i);
- if (Character.digit(c, 16) == -1) {
+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')
+ || (c >= 'A' && c <= 'F'))) {
return false;
}
}
diff --git a/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java b/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java
index d15ea5b2f56..127544f58ce 100644
--- a/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java
+++ b/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java
@@ -7,7 +7,7 @@
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Pack;
-public class Blake2bfMessageDigest extends BCMessageDigest implements Cloneable {
+public class Blake2bfMessageDigest extends BCMessageDigest {
public Blake2bfMessageDigest() {
super(new Blake2bfDigest());
@@ -148,10 +148,15 @@ public int doFinal(final byte[] out, final int offset) {
throw new IllegalStateException("The buffer must be filled with 213 bytes");
}
+ // Validate before compress() so a bad output buffer cannot leave the instance tainted.
+ if (out == null || offset < 0 || offset > out.length - DIGEST_LENGTH) {
+ throw new IllegalArgumentException("Output buffer too small for the digest");
+ }
+
compress();
for (int i = 0; i < h.length; i++) {
- System.arraycopy(Pack.longToLittleEndian(h[i]), 0, out, i * 8, 8);
+ System.arraycopy(Pack.longToLittleEndian(h[i]), 0, out, offset + i * 8, 8);
}
reset();
diff --git a/crypto/src/main/java/org/tron/common/crypto/ECKey.java b/crypto/src/main/java/org/tron/common/crypto/ECKey.java
index 4a6e1f00a0a..bc1cce6f363 100644
--- a/crypto/src/main/java/org/tron/common/crypto/ECKey.java
+++ b/crypto/src/main/java/org/tron/common/crypto/ECKey.java
@@ -17,7 +17,6 @@
* along with the ethereumJ library. If not, see .
*/
-import java.io.Serializable;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.KeyPair;
@@ -64,7 +63,7 @@
* low-S signatures.
*/
@Slf4j(topic = "crypto")
-public class ECKey implements Serializable, SignInterface {
+public class ECKey implements SignInterface {
/**
* The parameters of the secp256k1 curve.
@@ -88,7 +87,6 @@ public class ECKey implements Serializable, SignInterface {
private static final BigInteger SECP256K1N =
new BigInteger("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16);
private static final SecureRandom secureRandom;
- private static final long serialVersionUID = -728224901792295832L;
static {
// All clients must agree on the curve to use by agreement.
@@ -501,15 +499,15 @@ public static boolean isPubKeyCanonical(byte[] pubkey) {
/**
* Recovers the public key using SEC1v2 section 4.1.6.
*
- *
Replaces the three-argument overload; pass {@code false} for legacy recovery and rebuild
- * downstream callers.
- *
* @param recId recovery selector, from 0 to 3
* @param sig signature components
* @param messageHash hash of the signed data
- * @param strictValidation whether to enforce strict ECDSA validation; consensus callers use
- * the applicable proposal state
+ * @param strictValidation whether to enforce strict ECDSA validation
* @return encoded public key, or {@code null} if recovery is not possible
+ * @throws IllegalArgumentException if an argument is invalid or the candidate point is not on
+ * the curve
+ * @throws ArithmeticException if {@code r} is not invertible modulo the curve order when
+ * strict validation is disabled
*/
@Nullable
public static byte[] recoverPubBytesFromSignature(int recId,
@@ -816,7 +814,13 @@ public ECDSASignature sign(byte[] messageHash) {
int recId = -1;
byte[] thisKey = this.pub.getEncoded(/* compressed */ false);
for (int i = 0; i < 4; i++) {
- byte[] k = ECKey.recoverPubBytesFromSignature(i, sig, messageHash, true);
+ byte[] k;
+ try {
+ k = ECKey.recoverPubBytesFromSignature(i, sig, messageHash, true);
+ } catch (IllegalArgumentException e) {
+ // x = r + (i / 2) * n is not a valid curve point; try the next recId.
+ continue;
+ }
if (k != null && Arrays.equals(k, thisKey)) {
recId = i;
break;
@@ -826,6 +830,9 @@ public ECDSASignature sign(byte[] messageHash) {
throw new RuntimeException("Could not construct a recoverable key" +
". This should never happen.");
}
+ // recId 2 or 3 gives v = 29 or 30. It occurs only when n <= x(R) < p (probability about
+ // 2^-127.65) and is valid for transaction signatures; validateComponents restricts the
+ // precompile path to recIds 0 and 1.
sig.v = (byte) (recId + 27);
return sig;
}
@@ -927,6 +934,12 @@ public static ECDSASignature fromComponents(byte[] r, byte[] s, byte
return signature;
}
+ /**
+ * Validates signature components for the precompile path, which accepts only recovery ids 0
+ * and 1 (v = 27 or 28). Transaction signatures may also use recovery ids 2 and 3 (v = 29 or
+ * 30) and are validated through {@link ECKey#signatureToKeyBytes(byte[], ECDSASignature,
+ * boolean)}.
+ */
public static boolean validateComponents(BigInteger r, BigInteger s,
byte v) {
@@ -1007,6 +1020,9 @@ public boolean equals(Object o) {
ECDSASignature signature = (ECDSASignature) o;
+ if (v != signature.v) {
+ return false;
+ }
if (!r.equals(signature.r)) {
return false;
}
@@ -1017,12 +1033,13 @@ public boolean equals(Object o) {
public int hashCode() {
int result = r.hashCode();
result = 31 * result + s.hashCode();
+ result = 31 * result + (int) v;
return result;
}
}
@SuppressWarnings("serial")
- public static class MissingPrivateKeyException extends RuntimeException {
+ public static class MissingPrivateKeyException extends IllegalStateException {
}
diff --git a/crypto/src/main/java/org/tron/common/crypto/Hash.java b/crypto/src/main/java/org/tron/common/crypto/Hash.java
index 7af0f2c06fb..3c7b458a057 100644
--- a/crypto/src/main/java/org/tron/common/crypto/Hash.java
+++ b/crypto/src/main/java/org/tron/common/crypto/Hash.java
@@ -177,10 +177,24 @@ public static byte[] encodeElement(byte[] srcData) {
}
public static byte[] computeAddress(ECPoint pubPoint) {
+ if (pubPoint == null || pubPoint.isInfinity()) {
+ throw new IllegalArgumentException(
+ "Public key must not be null or the point at infinity");
+ }
return computeAddress(pubPoint.getEncoded(/* uncompressed */ false));
}
public static byte[] computeAddress(byte[] pubBytes) {
+ if (pubBytes == null) {
+ throw new IllegalArgumentException("Public key must not be null");
+ }
+ if (pubBytes.length == 1 && pubBytes[0] == 0) {
+ // Legacy signature recovery encodes the point at infinity as a single zero byte.
+ return sha3omit12(new byte[0]);
+ }
+ if (pubBytes.length != 65 || pubBytes[0] != 0x04) {
+ throw new IllegalArgumentException("Expected a 65-byte uncompressed public key");
+ }
return sha3omit12(
Arrays.copyOfRange(pubBytes, 1, pubBytes.length));
}
diff --git a/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java b/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java
index b13e1d14ea2..4444556e759 100644
--- a/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java
+++ b/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java
@@ -20,10 +20,12 @@
import java.security.DigestException;
import java.security.MessageDigest;
+import java.util.Arrays;
public abstract class DigestEngine extends MessageDigest implements Digest {
- private int digestLen, blockLen, inputLen;
+ private final int digestLen;
+ private int blockLen, inputLen;
private byte[] inputBuf;
private long blockCount;
@@ -45,6 +47,7 @@ public DigestEngine(String alg) {
* state.
*/
protected void engineReset() {
+ Arrays.fill(inputBuf, (byte) 0);
inputLen = 0;
blockCount = 0;
}
@@ -57,9 +60,7 @@ protected void engineReset() {
protected abstract void processBlock(byte[] data);
/**
- * Perform the final padding and store the result in the provided buffer. This method shall call
- * {@link #flush} and then {@link #update} with the appropriate padding data in order to getData
- * the full input data.
+ * Perform the final padding and store the resulting digest in the provided buffer.
*
* @param buf the output buffer
* @param off the output offset
@@ -67,23 +68,18 @@ protected void engineReset() {
protected abstract void doPadding(byte[] buf, int off);
/**
- * This function is called at object creation time; the implementation should use it to perform
- * initialization tasks. After this method is called, the implementation should be ready to
- * process data or meaningfully honour calls such as {@link #engineGetDigestLength}
+ * Called by the DigestEngine constructor before subclass initializers and constructor bodies run.
+ * Initialize any state required by {@link #engineGetDigestLength()} and
+ * {@link #getInternalBlockLength()}. After this method returns, both methods must return correct,
+ * fixed lengths without relying on later subclass initialization. The input buffer is allocated
+ * only after this method returns.
*/
protected abstract void doInit();
- private void adjustDigestLen() {
- if (digestLen == 0) {
- digestLen = engineGetDigestLength();
- }
- }
-
/**
* @see Digest
*/
public byte[] digest() {
- adjustDigestLen();
byte[] result = new byte[digestLen];
doPadding(result, 0);
reset();
@@ -108,7 +104,6 @@ public int digest(byte[] buf, int offset, int len) throws DigestException {
if (offset < 0 || len < 0 || offset > buf.length || len > buf.length - offset) {
throw new IllegalArgumentException("Invalid output buffer range");
}
- adjustDigestLen();
if (len < digestLen) {
throw new DigestException("Partial digests are not returned");
}
@@ -227,18 +222,22 @@ protected long getBlockCount() {
/**
* This function copies the internal buffering state to some other instance of a class extending
* {@code DigestEngine}. It returns a reference to the copy. This method is intended to be called
- * by the implementation of the {@link #copy} method.
+ * by the implementation of the {@link #copy} method. The destination must use the same algorithm,
+ * digest length and internal block length.
*
* @param dest the copy
* @return the value {@code dest}
+ * @throws IllegalArgumentException if the destination is null or incompatible
*/
protected Digest copyState(DigestEngine dest) {
+ if (dest == null || digestLen != dest.digestLen || blockLen != dest.blockLen
+ || !getAlgorithm().equals(dest.getAlgorithm())) {
+ throw new IllegalArgumentException("Incompatible digest destination");
+ }
dest.inputLen = inputLen;
dest.blockCount = blockCount;
System.arraycopy(inputBuf, 0, dest.inputBuf, 0,
inputBuf.length);
- adjustDigestLen();
- dest.adjustDigestLen();
return dest;
}
}
diff --git a/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java b/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java
index c8919f64904..1ba0612a2ce 100644
--- a/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java
+++ b/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java
@@ -18,6 +18,8 @@
package org.tron.common.crypto.cryptohash;
+import java.util.Arrays;
+
abstract class KeccakCore extends DigestEngine {
private static final long[] RC = {
@@ -529,6 +531,7 @@ public int getBlockLength() {
}
private final void doReset() {
+ Arrays.fill(tmpOut, (byte) 0);
for (int i = 0; i < 25; i++) {
A[i] = 0;
}
@@ -540,9 +543,14 @@ private final void doReset() {
A[20] = 0xFFFFFFFFFFFFFFFFL;
}
- protected Digest copyState(KeccakCore dst) {
- System.arraycopy(A, 0, dst.A, 0, 25);
- return super.copyState(dst);
+ @Override
+ protected Digest copyState(DigestEngine dst) {
+ if (!(dst instanceof KeccakCore)) {
+ throw new IllegalArgumentException("Destination must be a KeccakCore");
+ }
+ super.copyState(dst);
+ System.arraycopy(A, 0, ((KeccakCore) dst).A, 0, 25);
+ return dst;
}
public String toString() {
diff --git a/crypto/src/main/java/org/tron/common/crypto/jce/ECKeyPairGenerator.java b/crypto/src/main/java/org/tron/common/crypto/jce/ECKeyPairGenerator.java
index 61a5b90faec..cebce98cffa 100644
--- a/crypto/src/main/java/org/tron/common/crypto/jce/ECKeyPairGenerator.java
+++ b/crypto/src/main/java/org/tron/common/crypto/jce/ECKeyPairGenerator.java
@@ -82,7 +82,8 @@ private static class Holder {
static {
try {
- INSTANCE = KeyPairGenerator.getInstance(ALGORITHM);
+ // SunEC dropped secp256k1 in JDK 16, so never fall back to the default provider.
+ INSTANCE = KeyPairGenerator.getInstance(ALGORITHM, TronCastleProvider.getInstance());
INSTANCE.initialize(SECP256K1_CURVE);
} catch (NoSuchAlgorithmException ex) {
throw new AssertionError(algorithmAssertionMsg, ex);
diff --git a/crypto/src/main/java/org/tron/common/crypto/jce/ECSignatureFactory.java b/crypto/src/main/java/org/tron/common/crypto/jce/ECSignatureFactory.java
index 9953e0ebf70..1dafb64d91f 100644
--- a/crypto/src/main/java/org/tron/common/crypto/jce/ECSignatureFactory.java
+++ b/crypto/src/main/java/org/tron/common/crypto/jce/ECSignatureFactory.java
@@ -35,7 +35,8 @@ private ECSignatureFactory() {
public static Signature getRawInstance() {
try {
- return Signature.getInstance(RAW_ALGORITHM);
+ // SunEC dropped secp256k1 in JDK 16, so never fall back to the default provider.
+ return Signature.getInstance(RAW_ALGORITHM, TronCastleProvider.getInstance());
} catch (NoSuchAlgorithmException ex) {
throw new AssertionError(rawAlgorithmAssertionMsg, ex);
}
diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128.java
index 516b72e4831..a91c7fce5c9 100644
--- a/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128.java
+++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128.java
@@ -161,7 +161,11 @@ public BN128 add(BN128 o) {
public BN128 mul(BigInteger s) {
- if (s.compareTo(BigInteger.ZERO) == 0) // P * 0 = 0
+ if (s.signum() < 0) {
+ throw new IllegalArgumentException("Scalar must be non-negative");
+ }
+
+ if (s.signum() == 0) // P * 0 = 0
{
return zero();
}
diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/PairingCheck.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/PairingCheck.java
index 3e91e141739..ca0d6179395 100644
--- a/crypto/src/main/java/org/tron/common/crypto/zksnark/PairingCheck.java
+++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/PairingCheck.java
@@ -100,7 +100,7 @@ private static List calcEllCoeffs(BN128G2 base) {
List coeffs = new ArrayList<>();
- BN128G2 addend = base;
+ G2Homogeneous addend = G2Homogeneous.fromAffine(base);
// for each bit except most significant one
for (int i = LOOP_COUNT.bitLength() - 2; i >= 0; i--) {
@@ -132,7 +132,8 @@ private static List calcEllCoeffs(BN128G2 base) {
return coeffs;
}
- private static Precomputed flippedMillerLoopMixedAddition(BN128G2 base, BN128G2 addend) {
+ private static Precomputed flippedMillerLoopMixedAddition(BN128G2 base,
+ G2Homogeneous addend) {
Fp2 x1 = addend.x, y1 = addend.y, z1 = addend.z;
Fp2 x2 = base.x, y2 = base.y;
@@ -154,12 +155,12 @@ private static Precomputed flippedMillerLoopMixedAddition(BN128G2 base, BN128G2
Fp2 ellVW = d; // ell_VW = d
return Precomputed.of(
- new BN128G2(x3, y3, z3),
+ new G2Homogeneous(x3, y3, z3),
new EllCoeffs(ell0, ellVW, ellVV)
);
}
- private static Precomputed flippedMillerLoopDoubling(BN128G2 g2) {
+ private static Precomputed flippedMillerLoopDoubling(G2Homogeneous g2) {
Fp2 x = g2.x, y = g2.y, z = g2.z;
@@ -184,7 +185,7 @@ private static Precomputed flippedMillerLoopDoubling(BN128G2 g2) {
Fp2 ellVV = j.add(j).add(j); // ell_VV = 3 * j
return Precomputed.of(
- new BN128G2(rx, ry, rz),
+ new G2Homogeneous(rx, ry, rz),
new EllCoeffs(ell0, ellVW, ellVV)
);
}
@@ -257,19 +258,49 @@ public int result() {
static class Precomputed {
- BN128G2 g2;
+ G2Homogeneous g2;
EllCoeffs coeffs;
- Precomputed(BN128G2 g2, EllCoeffs coeffs) {
+ Precomputed(G2Homogeneous g2, EllCoeffs coeffs) {
this.g2 = g2;
this.coeffs = coeffs;
}
- static Precomputed of(BN128G2 g2, EllCoeffs coeffs) {
+ static Precomputed of(G2Homogeneous g2, EllCoeffs coeffs) {
return new Precomputed(g2, coeffs);
}
}
+ /**
+ * Running point of the flipped Miller loop, stored in homogeneous projective coordinates: the
+ * affine point it denotes is {@code (x / z, y / z)}. This differs from {@link BN128G2}, which is
+ * Jacobian ({@code (x / z^2, y / z^3)}), so the two must never be mixed. The type deliberately
+ * exposes no group operations.
+ */
+ static final class G2Homogeneous {
+
+ final Fp2 x;
+ final Fp2 y;
+ final Fp2 z;
+
+ private G2Homogeneous(Fp2 x, Fp2 y, Fp2 z) {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ }
+
+ /**
+ * Creates the running point from a curve point in affine coordinates, i.e. one with
+ * {@code z = 1}, where homogeneous and Jacobian coordinates agree.
+ */
+ static G2Homogeneous fromAffine(BN128G2 p) {
+ if (!Fp2._1.equals(p.z)) {
+ throw new IllegalArgumentException("expected an affine point (z = 1)");
+ }
+ return new G2Homogeneous(p.x, p.y, p.z);
+ }
+ }
+
static class Pair {
BN128G1 g1;
diff --git a/crypto/src/main/java/org/tron/keystore/Wallet.java b/crypto/src/main/java/org/tron/keystore/Wallet.java
index 6baa24a3cf7..b15722de20b 100644
--- a/crypto/src/main/java/org/tron/keystore/Wallet.java
+++ b/crypto/src/main/java/org/tron/keystore/Wallet.java
@@ -18,10 +18,13 @@
import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.bouncycastle.crypto.generators.SCrypt;
import org.bouncycastle.crypto.params.KeyParameter;
+import org.tron.common.crypto.ECKey;
import org.tron.common.crypto.Hash;
import org.tron.common.crypto.SignInterface;
import org.tron.common.crypto.SignUtils;
+import org.tron.common.utils.Base58;
import org.tron.common.utils.ByteArray;
+import org.tron.common.utils.DecodeUtil;
import org.tron.common.utils.StringUtil;
import org.tron.core.exception.CipherException;
@@ -30,20 +33,8 @@
* Web3 Secret Storage Definition or the
* Go Ethereum client implementation.
*
- *
Note: the Bouncy Castle Scrypt implementation {@link SCrypt}, fails to
- * comply
- * with the following Ethereum reference
- * Scrypt test vector:
- *
- *
- * {@code
- * // Only value of r that cost (as an int) could be exceeded for is 1
- * if (r == 1 && N_STANDARD > 65536)
- * {
- * throw new IllegalArgumentException("Cost parameter N_STANDARD must be > 1 and < 65536.");
- * }
- * }
- *
+ *
Scrypt parameters are checked against RFC 7914 and the supported resource limits
+ * before invoking {@link SCrypt}.
*/
public class Wallet {
@@ -76,11 +67,22 @@ public class Wallet {
private static final int SCRYPT_P_MAX = 8;
private static final long SCRYPT_MEMORY_MAX_BYTES = 1L << 30; // 128 * r * n cap = 1 GiB
private static final int KDF_DKLEN_MAX = 128;
+ private static final int KDF_SALT_MAX_BYTES = 1024;
private static final int PBKDF2_C_MAX = 1 << 20;
+ /**
+ * Creates a keystore. The caller must ensure the signing key's address matches its private key.
+ */
public static WalletFile create(String password, SignInterface sign, int n, int p)
throws CipherException {
+ if (!WalletUtils.passwordValid(password)) {
+ throw new CipherException("Password must be at least 6 characters");
+ }
+ if (sign == null) {
+ throw new CipherException("Missing signing key");
+ }
+
// Keep create() symmetric with validate()/decrypt(): reject KDF cost
// parameters that the decryption path would refuse, so create() can
// never produce a wallet file that only this class rejects.
@@ -89,15 +91,23 @@ public static WalletFile create(String password, SignInterface sign, int n, int
throw new CipherException(paramError);
}
+ byte[] privateKeyBytes = sign.getPrivateKey();
+ if (!ECKey.isValidPrivateKey(privateKeyBytes)) {
+ throw new CipherException("Invalid private key");
+ }
+
byte[] salt = generateRandomBytes(32);
- byte[] derivedKey = generateDerivedScryptKey(password.getBytes(UTF_8), salt, n, R, p, DKLEN);
+ byte[] derivedKey;
+ try {
+ derivedKey = generateDerivedScryptKey(password.getBytes(UTF_8), salt, n, R, p, DKLEN);
+ } catch (RuntimeException e) {
+ throw new CipherException("Scrypt key derivation failed", e);
+ }
byte[] encryptKey = Arrays.copyOfRange(derivedKey, 0, 16);
byte[] iv = generateRandomBytes(16);
- byte[] privateKeyBytes = sign.getPrivateKey();
-
byte[] cipherText = performCipherOperation(Cipher.ENCRYPT_MODE, iv, encryptKey,
privateKeyBytes);
@@ -155,7 +165,7 @@ private static byte[] generateDerivedScryptKey(
}
private static byte[] generateAes128CtrDerivedKey(
- byte[] password, byte[] salt, int c, String prf) throws CipherException {
+ byte[] password, byte[] salt, int c, String prf, int dklen) throws CipherException {
if (!"hmac-sha256".equals(prf)) {
throw new CipherException("Unsupported prf:" + prf);
@@ -166,7 +176,7 @@ private static byte[] generateAes128CtrDerivedKey(
PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
gen.init(password, salt, c);
- return ((KeyParameter) gen.generateDerivedParameters(256)).getKey();
+ return ((KeyParameter) gen.generateDerivedParameters(dklen * 8)).getKey();
}
private static byte[] performCipherOperation(
@@ -235,7 +245,8 @@ public static SignInterface decrypt(String password, WalletFile walletFile)
byte[] salt = ByteArray.fromHexString(aes128CtrKdfParams.getSalt());
try {
- derivedKey = generateAes128CtrDerivedKey(password.getBytes(UTF_8), salt, c, prf);
+ derivedKey = generateAes128CtrDerivedKey(password.getBytes(UTF_8), salt, c, prf,
+ aes128CtrKdfParams.getDklen());
} catch (RuntimeException e) {
throw new CipherException("Pbkdf2 key derivation failed", e);
}
@@ -290,8 +301,8 @@ public static SignInterface decrypt(String password, WalletFile walletFile)
/**
* Returns a description of the first schema violation found in
* {@code walletFile}, or {@code null} if the file matches the supported
- * V3 keystore shape (current version, known cipher, known KDF, and KDF
- * cost parameters within safe bounds).
+ * V3 keystore shape, including required fields, encodings, lengths, and KDF
+ * parameters within supported bounds. This does not verify the password or MAC.
*
*
KDF cost bounds are enforced here — the single chokepoint shared by
* {@link #validate(WalletFile)} (which throws the message) and
@@ -301,9 +312,17 @@ public static SignInterface decrypt(String password, WalletFile walletFile)
* exhaustion, or engine-level crashes before {@link #decrypt} runs.
*/
private static String validationError(WalletFile walletFile) {
+ if (walletFile == null) {
+ return "Missing wallet file";
+ }
if (walletFile.getVersion() != CURRENT_VERSION) {
return "Wallet version is not supported";
}
+ String address = walletFile.getAddress();
+ // An absent address remains supported for imported keystores.
+ if (address != null && !address.isEmpty() && !validAddress(address)) {
+ return "Invalid keystore address";
+ }
WalletFile.Crypto crypto = walletFile.getCrypto();
if (crypto == null) {
return "Missing crypto section";
@@ -312,30 +331,80 @@ private static String validationError(WalletFile walletFile) {
if (cipher == null || !cipher.equals(CIPHER)) {
return "Wallet cipher is not supported";
}
+ if (crypto.getCipherparams() == null) {
+ return "Missing cipherparams";
+ }
+ String iv = crypto.getCipherparams().getIv();
+ if (iv == null || iv.length() > 34 || !StringUtil.isHexadecimal(iv)
+ || ByteArray.fromHexString(iv).length != 16) {
+ return "IV must be 16 bytes of hex";
+ }
+ String ciphertext = crypto.getCiphertext();
+ // Allow the private-key encodings accepted by ECKey; validate the scalar after decryption.
+ if (ciphertext == null
+ || ciphertext.length() > 68
+ || !StringUtil.isHexadecimal(ciphertext)
+ || ByteArray.fromHexString(ciphertext).length > 33) {
+ return "Ciphertext must be 1 to 33 bytes of hex";
+ }
+ String mac = crypto.getMac();
+ if (mac == null || mac.length() > 66 || !StringUtil.isHexadecimal(mac)
+ || ByteArray.fromHexString(mac).length != 32) {
+ return "MAC must be 32 bytes of hex";
+ }
String kdf = crypto.getKdf();
if (kdf == null || (!kdf.equals(PBKDF2) && !kdf.equals(SCRYPT))) {
return "KDF type is not supported";
}
WalletFile.KdfParams kdfParams = crypto.getKdfparams();
if (kdfParams == null) {
- // Structural stubs (e.g. tooling fixtures) may omit kdfparams entirely;
- // there are no cost parameters to bound. Real keystores always carry them.
- return null;
+ return "Missing kdfparams";
+ }
+ String salt = kdfParams.getSalt();
+ if (salt != null
+ && salt.length() > 2 * KDF_SALT_MAX_BYTES + (salt.startsWith("0x") ? 2 : 0)) {
+ return "KDF salt exceeds " + KDF_SALT_MAX_BYTES + " bytes";
}
if (SCRYPT.equals(kdf)) {
if (!(kdfParams instanceof WalletFile.ScryptKdfParams)) {
return "Scrypt KDF params are missing or malformed";
}
WalletFile.ScryptKdfParams params = (WalletFile.ScryptKdfParams) kdfParams;
+ if (!StringUtil.isHexadecimal(params.getSalt())) {
+ return "Scrypt salt must be non-empty hex";
+ }
return scryptKdfParamsError(params.getDklen(), params.getN(), params.getR(), params.getP());
}
if (!(kdfParams instanceof WalletFile.Aes128CtrKdfParams)) {
return "Pbkdf2 KDF params are missing or malformed";
}
WalletFile.Aes128CtrKdfParams params = (WalletFile.Aes128CtrKdfParams) kdfParams;
+ if (!StringUtil.isHexadecimal(params.getSalt())) {
+ return "Pbkdf2 salt must be non-empty hex";
+ }
+ if (!"hmac-sha256".equals(params.getPrf())) {
+ return "Unsupported prf: " + params.getPrf();
+ }
return pbkdf2KdfParamsError(params.getDklen(), params.getC());
}
+ private static boolean validAddress(String address) {
+ // Bound Base58 decoding before allocating or doing quadratic conversion work.
+ if (address.length() > 34) {
+ return false;
+ }
+ try {
+ byte[] decoded = Base58.decode(address);
+ if (decoded.length != 25) {
+ return false;
+ }
+ byte[] payload = Arrays.copyOf(decoded, 21);
+ return DecodeUtil.addressValid(payload) && StringUtil.encode58Check(payload).equals(address);
+ } catch (IllegalArgumentException e) {
+ return false;
+ }
+ }
+
private static String scryptKdfParamsError(int dklen, int n, int r, int p) {
// dklen must yield at least 32 bytes: generateMac copies derivedKey[16..32)
// and AES-128 needs bytes [0..16); smaller keys throw raw ArrayIndexOutOfBoundsException.
@@ -349,6 +418,10 @@ private static String scryptKdfParamsError(int dklen, int n, int r, int p) {
if (r < 1 || r > SCRYPT_R_MAX) {
return "Scrypt r is out of range [1, " + SCRYPT_R_MAX + "]: " + r;
}
+ // RFC 7914 requires n < 2^(16*r); for r >= 2 the n cap already ensures this.
+ if (r == 1 && n >= (1 << 16)) {
+ return "Scrypt n must be less than 65536 when r is 1";
+ }
if (p < 1 || p > SCRYPT_P_MAX) {
return "Scrypt p is out of range [1, " + SCRYPT_P_MAX + "]: " + p;
}
@@ -362,8 +435,8 @@ private static String scryptKdfParamsError(int dklen, int n, int r, int p) {
}
private static String pbkdf2KdfParamsError(int dklen, int c) {
- if (dklen < 1 || dklen > KDF_DKLEN_MAX) {
- return "Pbkdf2 dklen is out of range [1, " + KDF_DKLEN_MAX + "]: " + dklen;
+ if (dklen < 32 || dklen > KDF_DKLEN_MAX) {
+ return "Pbkdf2 dklen is out of range [32, " + KDF_DKLEN_MAX + "]: " + dklen;
}
if (c < 1 || c > PBKDF2_C_MAX) {
return "Pbkdf2 iteration count c is out of range [1, " + PBKDF2_C_MAX + "]: " + c;
@@ -379,15 +452,15 @@ static void validate(WalletFile walletFile) throws CipherException {
}
/**
- * Returns {@code true} iff {@code walletFile} has the shape of a
- * decryptable V3 keystore: non-null address, supported version, non-null
- * crypto section with a supported cipher and KDF. Intended for
- * discovery-style filtering (e.g. listing or duplicate detection) where
- * we want to skip JSON stubs that would later fail {@link #validate}.
+ * Returns {@code true} iff {@code walletFile} has a non-empty address and passes
+ * the same structural checks as {@link #validate}. Intended for discovery-style
+ * filtering (e.g. listing or duplicate detection). Password correctness, MAC
+ * authenticity and address/private-key consistency are checked only by decrypt.
*/
public static boolean isValidKeystoreFile(WalletFile walletFile) {
return walletFile != null
&& walletFile.getAddress() != null
+ && !walletFile.getAddress().isEmpty()
&& validationError(walletFile) == null;
}
diff --git a/crypto/src/main/java/org/tron/keystore/WalletUtils.java b/crypto/src/main/java/org/tron/keystore/WalletUtils.java
index 7c15ab8207b..a28f36a5729 100644
--- a/crypto/src/main/java/org/tron/keystore/WalletUtils.java
+++ b/crypto/src/main/java/org/tron/keystore/WalletUtils.java
@@ -1,27 +1,38 @@
package org.tron.keystore;
+import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.Console;
import java.io.File;
import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.ByteBuffer;
+import java.nio.channels.Channels;
+import java.nio.channels.FileChannel;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
+import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
+import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.Set;
+import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.tron.common.crypto.SignInterface;
@@ -67,18 +78,14 @@ public static String generateWalletFile(
* Write a WalletFile to the given destination path with owner-only (0600)
* permissions, using a temp file + atomic rename.
*
- *
On POSIX filesystems, the temp file is created atomically with 0600
- * permissions via {@link Files#createTempFile(Path, String, String,
- * java.nio.file.attribute.FileAttribute[])}, avoiding any window where the
- * file is world-readable.
+ *
The temporary file is atomically created with 0600 permissions and written
+ * through the same channel, without reopening its path. Filesystems that cannot
+ * atomically set these permissions are not supported.
*
- *
On non-POSIX filesystems (e.g. Windows) the fallback uses
- * {@link File#setReadable(boolean, boolean)} /
- * {@link File#setWritable(boolean, boolean)} which is best-effort — these
- * methods manipulate only DOS-style attributes on Windows and may not update
- * file ACLs. The sensitive keystore JSON is written only after the narrowing
- * calls, so no confidential data is exposed during the window, but callers
- * on Windows should not infer strict owner-only ACL enforcement from this.
+ *
The destination must be in a trusted directory hierarchy. Keeping the channel
+ * open prevents a replaced temporary path from redirecting the wallet bytes, but
+ * users able to modify directory entries can still replace or remove the file
+ * before or after the move.
*
* @param walletFile the keystore to serialize
* @param destination the final target file (existing file will be replaced)
@@ -88,22 +95,19 @@ public static void writeWalletFile(WalletFile walletFile, File destination)
Path dir = destination.getAbsoluteFile().getParentFile().toPath();
Files.createDirectories(dir);
- Path tmp;
- try {
- tmp = Files.createTempFile(dir, "keystore-", ".tmp",
- PosixFilePermissions.asFileAttribute(OWNER_ONLY));
- } catch (UnsupportedOperationException e) {
- // Windows / non-POSIX fallback — best-effort narrowing only (see JavaDoc)
- tmp = Files.createTempFile(dir, "keystore-", ".tmp");
- File tf = tmp.toFile();
- tf.setReadable(false, false);
- tf.setReadable(true, true);
- tf.setWritable(false, false);
- tf.setWritable(true, true);
- }
+ Path tmp = dir.resolve("keystore-" + UUID.randomUUID() + ".tmp");
+ // Open before entering cleanup: a CREATE_NEW collision must not delete an existing file.
+ FileChannel channel = FileChannel.open(tmp,
+ EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE),
+ PosixFilePermissions.asFileAttribute(OWNER_ONLY));
try {
- objectMapper.writeValue(tmp.toFile(), walletFile);
+ try (FileChannel output = channel) {
+ // Keep the creating channel open until all serialized bytes have been synced.
+ objectMapper.writer().without(JsonGenerator.Feature.AUTO_CLOSE_TARGET)
+ .writeValue(Channels.newOutputStream(output), walletFile);
+ output.force(true);
+ }
try {
Files.move(tmp, destination.toPath(),
StandardCopyOption.REPLACE_EXISTING,
@@ -153,7 +157,7 @@ private static void warnIfSymbolicLink(File source) {
}
}
- public static String getWalletFileName(WalletFile walletFile) {
+ private static String getWalletFileName(WalletFile walletFile) {
DateTimeFormatter format = DateTimeFormatter.ofPattern(
"'UTC--'yyyy-MM-dd'T'HH-mm-ss.nVV'--'");
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
@@ -220,18 +224,84 @@ static synchronized void resetSharedStdinScanner() {
private static synchronized Scanner getSharedStdinScanner() {
if (sharedStdinScanner == null) {
- sharedStdinScanner = new Scanner(System.in);
+ // CharsetDecoder defaults to REPORT: never replace malformed password bytes.
+ sharedStdinScanner = new Scanner(new InputStreamReader(System.in,
+ StandardCharsets.UTF_8.newDecoder()));
}
return sharedStdinScanner;
}
+ /**
+ * Decode a UTF-8 password file without silently replacing malformed bytes.
+ */
+ public static String decodePassword(byte[] bytes) throws IOException {
+ try {
+ return StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString();
+ } catch (CharacterCodingException e) {
+ throw new IOException("Password input must be valid UTF-8", e);
+ }
+ }
+
+ /**
+ * Read with echo disabled, rejecting potentially corrupted console input.
+ * The caller must clear the returned array; EOF is returned as {@code null}.
+ */
+ public static char[] readConsolePassword(Console console, String prompt) throws IOException {
+ char[] password = console.readPassword("%s", prompt);
+ if (password == null) {
+ return null;
+ }
+ try {
+ validateConsolePassword(password, consoleCharset(console));
+ return password;
+ } catch (IOException e) {
+ Arrays.fill(password, '\0');
+ throw e;
+ }
+ }
+
+ private static Charset consoleCharset(Console console) throws IOException {
+ try {
+ // Console.charset() was added in JDK 17; keep the JDK 8 build compatible.
+ return (Charset) Console.class.getMethod("charset").invoke(console);
+ } catch (NoSuchMethodException e) {
+ // On supported JDK 8 Linux/macOS runtimes Console uses the default charset.
+ try {
+ String os = System.getProperty("os.name");
+ if ("Linux".equals(os) || "Mac OS X".equals(os)) {
+ return Charset.defaultCharset();
+ }
+ return null;
+ } catch (SecurityException ex) {
+ throw new IOException("Cannot determine console encoding; use UTF-8 password input", ex);
+ }
+ } catch (ReflectiveOperationException | SecurityException e) {
+ throw new IOException("Cannot determine console encoding; use UTF-8 password input", e);
+ }
+ }
+
+ static void validateConsolePassword(char[] password, Charset charset) throws IOException {
+ for (char c : password) {
+ // Console decoders replace malformed bytes; the original input cannot be recovered.
+ if (c == '\uFFFD' || (c > 0x7f && !StandardCharsets.UTF_8.equals(charset))) {
+ throw new IOException("Password may be corrupted by the console encoding; "
+ + "use a UTF-8 terminal or UTF-8 password file/stdin");
+ }
+ }
+ }
+
public static String inputPassword() {
String password;
Console cons = System.console();
Scanner in = cons == null ? getSharedStdinScanner() : null;
while (true) {
if (cons != null) {
- char[] pwd = cons.readPassword("password: ");
+ char[] pwd;
+ try {
+ pwd = readConsolePassword(cons, "password: ");
+ } catch (IOException e) {
+ throw new TronError(e.getMessage(), e, TronError.ErrCode.WITNESS_KEYSTORE_LOAD);
+ }
// Console EOF (e.g. Ctrl+D) returns null; fail fast instead of
// crashing with a raw NullPointerException.
if (pwd == null) {
@@ -240,7 +310,11 @@ public static String inputPassword() {
+ "restart with --password or provide an interactive TTY",
TronError.ErrCode.WITNESS_KEYSTORE_LOAD);
}
- password = String.valueOf(pwd);
+ try {
+ password = String.valueOf(pwd);
+ } finally {
+ Arrays.fill(pwd, '\0');
+ }
} else {
// Preserve the full password including embedded whitespace.
// The previous implementation applied trim() + split("\\s+")[0]
@@ -252,6 +326,9 @@ public static String inputPassword() {
try {
line = in.nextLine();
} catch (NoSuchElementException e) {
+ if (in.ioException() != null) {
+ throw passwordInputError(in.ioException());
+ }
// Piped stdin reached EOF before a password line was available;
// fail fast instead of leaking a raw NoSuchElementException.
throw new TronError(
@@ -259,6 +336,10 @@ public static String inputPassword() {
+ "line; restart with --password or provide an interactive TTY",
e, TronError.ErrCode.WITNESS_KEYSTORE_LOAD);
}
+ // Scanner treats reader failures as EOF and can return a partial line.
+ if (in.ioException() != null) {
+ throw passwordInputError(in.ioException());
+ }
password = stripPasswordLine(line);
}
if (passwordValid(password)) {
@@ -268,4 +349,9 @@ public static String inputPassword() {
}
}
+ private static TronError passwordInputError(IOException cause) {
+ return new TronError("Cannot read password input; stdin must contain valid UTF-8", cause,
+ TronError.ErrCode.WITNESS_KEYSTORE_LOAD);
+ }
+
}
diff --git a/framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java b/framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java
new file mode 100644
index 00000000000..ea76a214a16
--- /dev/null
+++ b/framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java
@@ -0,0 +1,69 @@
+package org.tron.common.crypto;
+
+import java.security.MessageDigest;
+import java.util.Arrays;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class Blake2bfMessageDigestTest {
+
+ @Test
+ public void testFailedDigestDoesNotTaintState() throws Exception {
+ byte[] input = new byte[Blake2bfMessageDigest.Blake2bfDigest.MESSAGE_LENGTH_BYTES];
+ input[3] = 12; // rounds
+ input[212] = 1; // final block flag
+
+ byte[] expected = digest(input);
+
+ MessageDigest digest = new Blake2bfMessageDigest();
+ digest.update(input);
+ try {
+ digest.digest(new byte[32], -32, 64);
+ Assert.fail("Expected the undersized output buffer to be rejected");
+ } catch (IllegalArgumentException expectedFailure) {
+ // the output buffer is too small, so digesting must fail before touching the state
+ }
+
+ Assert.assertArrayEquals(expected, digest.digest());
+ }
+
+ @Test
+ public void testDigestHonorsOutputOffset() throws Exception {
+ byte[] input = new byte[Blake2bfMessageDigest.Blake2bfDigest.MESSAGE_LENGTH_BYTES];
+ input[3] = 12; // rounds
+ input[212] = 1; // final block flag
+ byte[] expected = digest(input);
+
+ int offset = 16;
+ byte[] out = new byte[offset + expected.length + 8];
+ Arrays.fill(out, (byte) 0x5A);
+
+ MessageDigest digest = new Blake2bfMessageDigest();
+ digest.update(input);
+
+ Assert.assertEquals(64, digest.digest(out, offset, 64));
+ Assert.assertArrayEquals(expected, Arrays.copyOfRange(out, offset, offset + 64));
+ for (int i = 0; i < out.length; i++) {
+ if (i < offset || i >= offset + 64) {
+ Assert.assertEquals(0x5A, out[i] & 0xFF);
+ }
+ }
+ }
+
+ @Test
+ public void testCloneIsNotSupported() throws Exception {
+ MessageDigest digest = new Blake2bfMessageDigest();
+ try {
+ digest.clone();
+ Assert.fail("Expected cloning to be unsupported");
+ } catch (CloneNotSupportedException expectedFailure) {
+ // the digest deliberately does not implement Cloneable
+ }
+ }
+
+ private byte[] digest(byte[] input) {
+ MessageDigest digest = new Blake2bfMessageDigest();
+ digest.update(input);
+ return digest.digest();
+ }
+}
diff --git a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java
index 984e3bc7e18..90479e7a833 100644
--- a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java
+++ b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java
@@ -17,6 +17,7 @@
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.asn1.sec.SECNamedCurves;
+import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.BigIntegers;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.encoders.Hex;
@@ -468,4 +469,57 @@ public void testNodeId() {
assertEquals(key, ECKey.fromNodeId(key.getNodeId()));
}
+
+ @Test
+ public void testComputeAddressRejectsMalformedPublicKey() {
+ assertThrows(IllegalArgumentException.class, () -> Hash.computeAddress(new byte[33]));
+ assertThrows(IllegalArgumentException.class, () -> Hash.computeAddress(new byte[65]));
+
+ ECKey key = ECKey.fromPrivate(privateKey);
+ assertArrayEquals(key.getAddress(), Hash.computeAddress(key.getPubKey()));
+ }
+
+ @Test
+ public void testLegacyPointAtInfinityAddressUnchanged() {
+ // The address derived from the Keccak-256 hash of the empty input, as documented before the
+ // change: legacy recovery encoded the point at infinity as the single byte 0x00.
+ byte[] expected = Hex.decode("41dcc703c0e500b653ca82273b7bfad8045d85a470");
+
+ assertArrayEquals(expected, Hash.computeAddress(new byte[]{0}));
+ assertArrayEquals(expected, Hash.sha3omit12(new byte[0]));
+ }
+
+ @Test
+ public void testComputeAddressRejectsPointAtInfinity() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Hash.computeAddress(ECKey.CURVE.getCurve().getInfinity()));
+ assertThrows(IllegalArgumentException.class, () -> Hash.computeAddress((ECPoint) null));
+ }
+
+ @Test
+ public void testECKeyIsNotSerializable() {
+ ECKey key = ECKey.fromPrivate(privateKey);
+ assertFalse(key instanceof java.io.Serializable);
+ }
+
+ @Test
+ public void testMissingPrivateKeyIsIllegalStateException() {
+ ECKey publicOnly = ECKey.fromPublicOnly(pubKey);
+
+ assertThrows(IllegalStateException.class, publicOnly::getPrivKey);
+ assertThrows(IllegalStateException.class, () -> publicOnly.sign(new byte[32]));
+ }
+
+ @Test
+ public void testSignatureEqualityIncludesRecoveryId() {
+ byte[] r = BigInteger.ONE.toByteArray();
+ byte[] s = BigInteger.valueOf(2).toByteArray();
+
+ ECDSASignature low = new ECDSASignature(r, s, (byte) 27);
+ ECDSASignature high = new ECDSASignature(r, s, (byte) 28);
+
+ assertEquals(low, new ECDSASignature(r, s, (byte) 27));
+ assertEquals(low.hashCode(), new ECDSASignature(r, s, (byte) 27).hashCode());
+ assertNotEquals(low, high);
+ }
}
diff --git a/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java b/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java
index c3d1a96ba2e..e5861113e3a 100644
--- a/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java
+++ b/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java
@@ -2,7 +2,9 @@
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
+import static org.mockito.Mockito.mock;
import java.nio.ByteBuffer;
import java.security.DigestException;
@@ -13,6 +15,7 @@
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
+import org.springframework.test.util.ReflectionTestUtils;
import org.tron.common.crypto.jce.TronCastleProvider;
@RunWith(Parameterized.class)
@@ -29,6 +32,22 @@ public static Collection