From b51aeea6988462d8607de4e9512f688f9ea177be Mon Sep 17 00:00:00 2001 From: federico Date: Fri, 20 Mar 2026 15:38:50 +0800 Subject: [PATCH] refactor(crypto): remove SM2/SM3 crypto algorithm support --- .../org/tron/core/utils/TransactionUtil.java | 10 +- .../tron/core/vm/PrecompiledContracts.java | 27 +- .../program/invoke/ProgramInvokeMockImpl.java | 6 +- .../tron/common/overlay/message/Message.java | 5 +- .../java/org/tron/common/utils/Commons.java | 7 +- .../org/tron/common/utils/LocalWitnesses.java | 6 +- .../org/tron/core/capsule/BlockCapsule.java | 11 +- .../org/tron/core/capsule/CodeCapsule.java | 3 +- .../tron/core/capsule/StorageRowCapsule.java | 3 +- .../tron/core/capsule/TransactionCapsule.java | 30 +- .../tron/core/capsule/utils/MerkleTree.java | 2 +- .../tron/core/service/RewardViCalService.java | 3 +- .../common/parameter/CommonParameter.java | 8 - .../org/tron/common/utils/MerkleRoot.java | 2 +- .../org/tron/common/utils/Sha256Hash.java | 95 +- .../org/tron/common/utils/StringUtil.java | 5 +- .../org/tron/consensus/dpos/DposTask.java | 3 +- .../pbft/message/PbftBaseMessage.java | 2 +- .../consensus/pbft/message/PbftMessage.java | 4 +- .../org/tron/common/crypto/SignUtils.java | 42 +- .../java/org/tron/common/crypto/sm2/SM2.java | 1144 ----------------- .../org/tron/common/crypto/sm2/SM2Signer.java | 262 ---- .../tron/common/backup/message/Message.java | 2 +- .../src/main/java/org/tron/core/Wallet.java | 24 +- .../java/org/tron/core/config/args/Args.java | 3 - .../org/tron/core/config/args/ConfigKey.java | 3 - .../core/config/args/WitnessInitializer.java | 9 +- .../tron/core/consensus/ConsensusService.java | 5 +- .../main/java/org/tron/core/db/Manager.java | 3 +- .../messagehandler/PbftDataSyncHandler.java | 2 +- .../core/net/service/relay/RelayService.java | 12 +- .../org/tron/core/services/RpcApiService.java | 3 +- .../org/tron/core/services/http/Util.java | 5 +- .../RpcApiServiceOnSolidity.java | 3 +- .../core/services/jsonrpc/JsonRpcApiUtil.java | 8 +- .../services/jsonrpc/types/BlockResult.java | 3 +- .../zen/ShieldedTRC20ParametersBuilder.java | 2 +- .../java/org/tron/keystore/Credentials.java | 6 - .../main/java/org/tron/keystore/Wallet.java | 2 +- .../java/org/tron/keystore/WalletUtils.java | 6 +- .../org/tron/program/KeystoreFactory.java | 6 +- framework/src/main/resources/config.conf | 5 - .../test/java/org/tron/common/BaseTest.java | 3 +- .../java/org/tron/common/ParameterTest.java | 2 - .../tron/common/crypto/BouncyCastleTest.java | 68 +- .../org/tron/common/crypto/SM2KeyTest.java | 284 ---- .../common/crypto/SignatureInterfaceTest.java | 39 +- .../vm/ValidateMultiSignContractTest.java | 6 +- .../org/tron/common/utils/PublicMethod.java | 33 - .../org/tron/common/utils/Sha256HashTest.java | 37 +- .../common/utils/client/WalletClient.java | 21 +- .../common/utils/client/utils/Base58.java | 10 +- .../utils/client/utils/Sha256Sm3Hash.java | 342 ----- .../utils/client/utils/TransactionUtils.java | 9 +- .../tron/core/capsule/BlockCapsuleTest.java | 2 +- .../core/capsule/utils/MerkleTreeTest.java | 10 +- .../org/tron/core/config/args/ArgsTest.java | 2 +- .../core/config/args/LocalWitnessTest.java | 4 +- .../java/org/tron/core/db/BlockGenerate.java | 3 +- .../org/tron/core/db/KhaosDatabaseTest.java | 22 +- .../java/org/tron/core/db/ManagerTest.java | 2 +- .../tron/core/db/TransactionExpireTest.java | 2 +- .../org/tron/core/db2/CheckpointV2Test.java | 4 +- .../messagehandler/PbftMsgHandlerTest.java | 5 +- .../core/net/services/RelayServiceTest.java | 7 +- .../core/services/RpcApiServicesTest.java | 3 +- .../core/zksnark/MerkleContainerTest.java | 12 +- .../tron/core/zksnark/SendCoinShieldTest.java | 3 +- .../core/zksnark/ShieldedReceiveTest.java | 5 +- .../org/tron/keystore/CredentialsTest.java | 19 +- .../org/tron/keystore/WalletFileTest.java | 4 +- .../java/common/org/tron/plugins/DbRoot.java | 3 +- .../org/tron/plugins/utils/DBUtils.java | 3 +- .../org/tron/plugins/utils/MerkleRoot.java | 2 +- .../org/tron/plugins/utils/Sha256Hash.java | 40 +- 75 files changed, 207 insertions(+), 2596 deletions(-) delete mode 100644 crypto/src/main/java/org/tron/common/crypto/sm2/SM2.java delete mode 100644 crypto/src/main/java/org/tron/common/crypto/sm2/SM2Signer.java delete mode 100644 framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java delete mode 100644 framework/src/test/java/org/tron/common/utils/client/utils/Sha256Sm3Hash.java diff --git a/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java b/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java index 53d6caf5691..aea6541eb17 100644 --- a/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java @@ -37,7 +37,6 @@ import org.tron.api.GrpcAPI.TransactionExtention; import org.tron.api.GrpcAPI.TransactionSignWeight; import org.tron.api.GrpcAPI.TransactionSignWeight.Result; -import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.Sha256Hash; import org.tron.core.ChainBaseManager; import org.tron.core.capsule.AccountCapsule; @@ -117,8 +116,7 @@ private static boolean validReadableBytes(byte[] bytes, int maxLength) { } public static Sha256Hash getTransactionId(Transaction transaction) { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()); + return Sha256Hash.of(transaction.getRawData().toByteArray()); } @@ -187,8 +185,7 @@ public TransactionSignWeight getTransactionSignWeight(Transaction trx) { TransactionSignWeight.Builder tswBuilder = TransactionSignWeight.newBuilder(); TransactionExtention.Builder trxExBuilder = TransactionExtention.newBuilder(); trxExBuilder.setTransaction(trx); - trxExBuilder.setTxid(ByteString.copyFrom(Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()))); + trxExBuilder.setTxid(ByteString.copyFrom(Sha256Hash.hash(trx.getRawData().toByteArray()))); Return.Builder retBuilder = Return.newBuilder(); retBuilder.setResult(true).setCode(response_code.SUCCESS); trxExBuilder.setResult(retBuilder); @@ -224,8 +221,7 @@ public TransactionSignWeight getTransactionSignWeight(Transaction trx) { if (trx.getSignatureCount() > 0) { List approveList = new ArrayList<>(); long currentWeight = TransactionCapsule.checkWeight(permission, trx.getSignatureList(), - Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), trx.getRawData().toByteArray()), approveList); + Sha256Hash.hash(trx.getRawData().toByteArray()), approveList); tswBuilder.addAllApprovedList(approveList); tswBuilder.setCurrentWeight(currentWeight); } diff --git a/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java b/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java index 654a76db33b..796818920c3 100644 --- a/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java +++ b/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java @@ -360,11 +360,9 @@ private static byte[] recoverAddrBySign(byte[] sign, byte[] hash) { } try { Rsv rsv = Rsv.fromSignature(sign); - SignatureInterface signature = SignUtils.fromComponents(rsv.getR(), rsv.getS(), rsv.getV(), - CommonParameter.getInstance().isECKeyCryptoEngine()); + SignatureInterface signature = SignUtils.fromComponents(rsv.getR(), rsv.getS(), rsv.getV()); if (signature.validateComponents()) { - out = SignUtils.signatureToAddress(hash, signature, - CommonParameter.getInstance().isECKeyCryptoEngine()); + out = SignUtils.signatureToAddress(hash, signature); } } catch (Throwable any) { logger.info("ECRecover error", any.getMessage()); @@ -518,11 +516,9 @@ public long getEnergyForData(byte[] data) { public Pair execute(byte[] data) { if (data == null) { - return Pair.of(true, Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), EMPTY_BYTE_ARRAY)); + return Pair.of(true, Sha256Hash.hash(EMPTY_BYTE_ARRAY)); } - return Pair.of(true, Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), data)); + return Pair.of(true, Sha256Hash.hash(data)); } } @@ -548,11 +544,9 @@ public Pair execute(byte[] data) { data = EMPTY_BYTE_ARRAY; } - byte[] orig = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), data); + byte[] orig = Sha256Hash.hash(data); System.arraycopy(orig, 0, target, 0, 20); - return Pair.of(true, Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), target)); + return Pair.of(true, Sha256Hash.hash(target)); } } @@ -590,11 +584,9 @@ public Pair execute(byte[] data) { int sLength = data.length < 128 ? data.length - 96 : 32; System.arraycopy(data, 96, s, 0, sLength); - SignatureInterface signature = SignUtils.fromComponents(r, s, v[31] - , CommonParameter.getInstance().isECKeyCryptoEngine()); + SignatureInterface signature = SignUtils.fromComponents(r, s, v[31]); if (validateV(v) && signature.validateComponents()) { - out = new DataWord(SignUtils.signatureToAddress(h, signature - , CommonParameter.getInstance().isECKeyCryptoEngine())); + out = new DataWord(SignUtils.signatureToAddress(h, signature)); } } catch (Throwable any) { } @@ -948,8 +940,7 @@ public Pair execute(byte[] rawData) { byte[] data = words[2].getData(); byte[] combine = ByteUtil.merge(address, ByteArray.fromInt(permissionId), data); - byte[] hash = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), combine); + byte[] hash = Sha256Hash.hash(combine); if (VMConfig.allowTvmSelfdestructRestriction()) { int sigArraySize = words[words[3].intValueSafe() / WORD_SIZE].intValueSafe(); diff --git a/actuator/src/main/java/org/tron/core/vm/program/invoke/ProgramInvokeMockImpl.java b/actuator/src/main/java/org/tron/core/vm/program/invoke/ProgramInvokeMockImpl.java index 567ac72931a..aaef003b0aa 100644 --- a/actuator/src/main/java/org/tron/core/vm/program/invoke/ProgramInvokeMockImpl.java +++ b/actuator/src/main/java/org/tron/core/vm/program/invoke/ProgramInvokeMockImpl.java @@ -79,8 +79,7 @@ public DataWord getBalance() { public DataWord getOriginAddress() { byte[] cowPrivKey = Hash.sha3("horse".getBytes()); - byte[] addr = SignUtils.fromPrivate(cowPrivKey - , CommonParameter.getInstance().isECKeyCryptoEngine()).getAddress(); + byte[] addr = SignUtils.fromPrivate(cowPrivKey).getAddress(); return new DataWord(addr); } @@ -89,8 +88,7 @@ public DataWord getOriginAddress() { public DataWord getCallerAddress() { byte[] cowPrivKey = Hash.sha3("monkey".getBytes()); - byte[] addr = SignUtils.fromPrivate(cowPrivKey - , CommonParameter.getInstance().isECKeyCryptoEngine()).getAddress(); + byte[] addr = SignUtils.fromPrivate(cowPrivKey).getAddress(); return new DataWord(addr); } diff --git a/chainbase/src/main/java/org/tron/common/overlay/message/Message.java b/chainbase/src/main/java/org/tron/common/overlay/message/Message.java index 84c3f695686..5da9ab0abfb 100644 --- a/chainbase/src/main/java/org/tron/common/overlay/message/Message.java +++ b/chainbase/src/main/java/org/tron/common/overlay/message/Message.java @@ -74,8 +74,7 @@ public byte[] getSendBytes() { } public Sha256Hash getMessageId() { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - getData()); + return Sha256Hash.of(getData()); } public byte[] getData() { @@ -110,4 +109,4 @@ public boolean equals(Object o) { return Arrays.equals(data, message.data); } -} \ No newline at end of file +} diff --git a/chainbase/src/main/java/org/tron/common/utils/Commons.java b/chainbase/src/main/java/org/tron/common/utils/Commons.java index b121e84ecfe..b1bdf4bb7e4 100644 --- a/chainbase/src/main/java/org/tron/common/utils/Commons.java +++ b/chainbase/src/main/java/org/tron/common/utils/Commons.java @@ -5,7 +5,6 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; -import org.tron.common.parameter.CommonParameter; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ExchangeCapsule; import org.tron.core.exception.BalanceInsufficientException; @@ -28,10 +27,8 @@ public static byte[] decode58Check(String input) { } byte[] decodeData = new byte[decodeCheck.length - 4]; System.arraycopy(decodeCheck, 0, decodeData, 0, decodeData.length); - byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - decodeData); - byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - hash0); + byte[] hash0 = Sha256Hash.hash(decodeData); + byte[] hash1 = Sha256Hash.hash(hash0); if (hash1[0] == decodeCheck[decodeData.length] && hash1[1] == decodeCheck[decodeData.length + 1] && hash1[2] == decodeCheck[decodeData.length + 2] && diff --git a/chainbase/src/main/java/org/tron/common/utils/LocalWitnesses.java b/chainbase/src/main/java/org/tron/common/utils/LocalWitnesses.java index 7179045ea7e..7d42907e254 100644 --- a/chainbase/src/main/java/org/tron/common/utils/LocalWitnesses.java +++ b/chainbase/src/main/java/org/tron/common/utils/LocalWitnesses.java @@ -47,14 +47,12 @@ public LocalWitnesses(List privateKeys) { setPrivateKeys(privateKeys); } - public void initWitnessAccountAddress(final byte[] witnessAddress, - boolean isECKeyCryptoEngine) { + public void initWitnessAccountAddress(final byte[] witnessAddress) { if (witnessAddress != null) { this.witnessAccountAddress = witnessAddress; } else if (!CollectionUtils.isEmpty(privateKeys)) { byte[] privateKey = ByteArray.fromHexString(getPrivateKey()); - final SignInterface ecKey = SignUtils.fromPrivate(privateKey, - isECKeyCryptoEngine); + final SignInterface ecKey = SignUtils.fromPrivate(privateKey); this.witnessAccountAddress = ecKey.getAddress(); } } diff --git a/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java index 01ff7fb5365..5378c239517 100755 --- a/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java @@ -161,8 +161,7 @@ private void initTxs() { // TODO add unit test for sig2.getbytes public void sign(byte[] privateKey) { - SignInterface ecKeyEngine = SignUtils - .fromPrivate(privateKey, CommonParameter.getInstance().isECKeyCryptoEngine()); + SignInterface ecKeyEngine = SignUtils.fromPrivate(privateKey); ByteString sig = ByteString.copyFrom(ecKeyEngine.Base64toBytes(ecKeyEngine.signHash(getRawHash() .getBytes()))); @@ -174,8 +173,7 @@ public void sign(byte[] privateKey) { } private Sha256Hash getRawHash() { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - this.block.getBlockHeader().getRawData().toByteArray()); + return Sha256Hash.of(this.block.getBlockHeader().getRawData().toByteArray()); } public boolean validateSignature(DynamicPropertiesStore dynamicPropertiesStore, @@ -183,8 +181,7 @@ public boolean validateSignature(DynamicPropertiesStore dynamicPropertiesStore, try { byte[] sigAddress = SignUtils.signatureToAddress(getRawHash().getBytes(), TransactionCapsule.getBase64FromByteString( - block.getBlockHeader().getWitnessSignature()), - CommonParameter.getInstance().isECKeyCryptoEngine()); + block.getBlockHeader().getWitnessSignature())); byte[] witnessAccountAddress = block.getBlockHeader().getRawData().getWitnessAddress() .toByteArray(); @@ -204,7 +201,7 @@ public boolean validateSignature(DynamicPropertiesStore dynamicPropertiesStore, public BlockId getBlockId() { if (blockId.equals(Sha256Hash.ZERO_HASH)) { blockId = - new BlockId(Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), + new BlockId(Sha256Hash.of( this.block.getBlockHeader().getRawData().toByteArray()), getNum()); } return blockId; diff --git a/chainbase/src/main/java/org/tron/core/capsule/CodeCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/CodeCapsule.java index 188a2bc061c..ccd02c98840 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/CodeCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/CodeCapsule.java @@ -30,8 +30,7 @@ public CodeCapsule(byte[] code) { } public Sha256Hash getCodeHash() { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - this.code); + return Sha256Hash.of(this.code); } @Override diff --git a/chainbase/src/main/java/org/tron/core/capsule/StorageRowCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/StorageRowCapsule.java index 82221058ff1..b067dc16277 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/StorageRowCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/StorageRowCapsule.java @@ -56,8 +56,7 @@ private void markDirty() { } public Sha256Hash getHash() { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - this.rowValue); + return Sha256Hash.of(this.rowValue); } public byte[] getValue() { diff --git a/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java index b11c6b1e0a4..350dfac9253 100755 --- a/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java @@ -91,8 +91,8 @@ public class TransactionCapsule implements ProtoCapsule { private static final String esName = "valid-contract-proto"; private static final ExecutorService executorService = ExecutorServiceManager - .newFixedThreadPool(esName, CommonParameter.getInstance() - .getValidContractProtoThreadNum()); + .newFixedThreadPool(esName, + CommonParameter.getInstance().getValidContractProtoThreadNum()); private static final String OWNER_ADDRESS = "ownerAddress_"; private Transaction transaction; @@ -242,8 +242,7 @@ public static long checkWeight(Permission permission, List sigs, byt "Signature size is " + sig.size()); } String base64 = TransactionCapsule.getBase64FromByteString(sig); - byte[] address = SignUtils - .signatureToAddress(hash, base64, CommonParameter.getInstance().isECKeyCryptoEngine()); + byte[] address = SignUtils.signatureToAddress(hash, base64); long weight = getWeight(permission, address); if (weight == 0) { throw new PermissionException( @@ -311,11 +310,10 @@ public static byte[] hashShieldTransaction(Transaction tx, String tokenId) Transaction transaction = tx.toBuilder().clearRawData() .setRawData(rawBuilder).build(); - byte[] mergedByte = Bytes.concat(Sha256Hash - .of(CommonParameter.getInstance().isECKeyCryptoEngine(), tokenId.getBytes()).getBytes(), + byte[] mergedByte = Bytes.concat( + Sha256Hash.of(tokenId.getBytes()).getBytes(), transaction.getRawData().toByteArray()); - return Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), mergedByte).getBytes(); + return Sha256Hash.of(mergedByte).getBytes(); } // todo mv this static function to capsule util @@ -563,18 +561,15 @@ public void createTransaction(com.google.protobuf.Message message, ContractType public Sha256Hash getMerkleHash() { byte[] transBytes = this.transaction.toByteArray(); - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - transBytes); + return Sha256Hash.of(transBytes); } private Sha256Hash getRawHash() { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - this.transaction.getRawData().toByteArray()); + return Sha256Hash.of(this.transaction.getRawData().toByteArray()); } public void sign(byte[] privateKey) { - SignInterface cryptoEngine = SignUtils - .fromPrivate(privateKey, CommonParameter.getInstance().isECKeyCryptoEngine()); + SignInterface cryptoEngine = SignUtils.fromPrivate(privateKey); ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine .signHash(getTransactionId().getBytes()))); this.transaction = this.transaction.toBuilder().addSignature(sig).build(); @@ -595,8 +590,7 @@ public void addSign(byte[] privateKey, AccountStore accountStore) } checkPermission(permissionId, permission, contract); List approveList = new ArrayList<>(); - SignInterface cryptoEngine = SignUtils - .fromPrivate(privateKey, CommonParameter.getInstance().isECKeyCryptoEngine()); + SignInterface cryptoEngine = SignUtils.fromPrivate(privateKey); byte[] address = cryptoEngine.getAddress(); if (this.transaction.getSignatureCount() > 0) { checkWeight(permission, this.transaction.getSignatureList(), @@ -617,7 +611,7 @@ public void addSign(byte[] privateKey, AccountStore accountStore) .signHash(getTransactionId().getBytes()))); this.transaction = this.transaction.toBuilder().addSignature(sig).build(); } - + private static void checkPermission(int permissionId, Permission permission, Transaction.Contract contract) throws PermissionException { if (permissionId != 0) { if (permission.getType() != PermissionType.Active) { @@ -684,7 +678,7 @@ public boolean validateSignature(AccountStore accountStore, } } isVerified = true; - } + } return true; } diff --git a/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java b/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java index 94d22f4b474..29e51c5f8bb 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java +++ b/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java @@ -83,7 +83,7 @@ private Leaf createLeaf(Sha256Hash hash) { } private Sha256Hash computeHash(Sha256Hash leftHash, Sha256Hash rightHash) { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), + return Sha256Hash.of( leftHash.getByteString().concat(rightHash.getByteString()).toByteArray()); } diff --git a/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java b/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java index f88fd02c539..f9873da5eb7 100644 --- a/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java +++ b/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java @@ -191,8 +191,7 @@ private void calcMerkleRoot() { } private Sha256Hash getHash(Map.Entry entry) { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - Bytes.concat(entry.getKey(), entry.getValue())); + return Sha256Hash.of(Bytes.concat(entry.getKey(), entry.getValue())); } private void startRewardCal() { diff --git a/common/src/main/java/org/tron/common/parameter/CommonParameter.java b/common/src/main/java/org/tron/common/parameter/CommonParameter.java index fbb39a13288..874010fb0bb 100644 --- a/common/src/main/java/org/tron/common/parameter/CommonParameter.java +++ b/common/src/main/java/org/tron/common/parameter/CommonParameter.java @@ -419,10 +419,6 @@ public class CommonParameter { public EventPluginConfig eventPluginConfig; @Getter public FilterQuery eventFilter; - @Getter - @Setter - public String cryptoEngine = Constant.ECKey_ENGINE; - @Getter @Setter public boolean rpcEnable = true; @@ -652,10 +648,6 @@ public static void reset() { PARAMETER = new CommonParameter(); } - public boolean isECKeyCryptoEngine() { - return cryptoEngine.equalsIgnoreCase(Constant.ECKey_ENGINE); - } - public boolean isJsonRpcFilterEnabled() { return jsonRpcHttpFullNodeEnable || jsonRpcHttpSolidityNodeEnable; diff --git a/common/src/main/java/org/tron/common/utils/MerkleRoot.java b/common/src/main/java/org/tron/common/utils/MerkleRoot.java index ccd8905b6c5..df4ddc7a6f6 100644 --- a/common/src/main/java/org/tron/common/utils/MerkleRoot.java +++ b/common/src/main/java/org/tron/common/utils/MerkleRoot.java @@ -56,7 +56,7 @@ private static Leaf createLeaf(Sha256Hash hash) { } private static Sha256Hash computeHash(Sha256Hash leftHash, Sha256Hash rightHash) { - return Sha256Hash.of(true, + return Sha256Hash.of( leftHash.getByteString().concat(rightHash.getByteString()).toByteArray()); } diff --git a/common/src/main/java/org/tron/common/utils/Sha256Hash.java b/common/src/main/java/org/tron/common/utils/Sha256Hash.java index 68225ccba63..e7ac185249a 100644 --- a/common/src/main/java/org/tron/common/utils/Sha256Hash.java +++ b/common/src/main/java/org/tron/common/utils/Sha256Hash.java @@ -31,7 +31,6 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; -import org.bouncycastle.crypto.digests.SM3Digest; /** @@ -87,8 +86,8 @@ public static Sha256Hash wrap(ByteString rawHashByteString) { * Use {@link #of(byte[])} instead: this old name is ambiguous. */ @Deprecated - public static Sha256Hash create(boolean isSha256, byte[] contents) { - return of(isSha256, contents); + public static Sha256Hash create(byte[] contents) { + return of(contents); } /** @@ -97,8 +96,8 @@ public static Sha256Hash create(boolean isSha256, byte[] contents) { * @param contents the bytes on which the hash value is calculated * @return a new instance containing the calculated (one-time) hash */ - public static Sha256Hash of(boolean isSha256, byte[] contents) { - return wrap(hash(isSha256, contents)); + public static Sha256Hash of(byte[] contents) { + return wrap(hash(contents)); } /** @@ -110,10 +109,10 @@ public static Sha256Hash of(boolean isSha256, byte[] contents) { * @return a new instance containing the calculated (one-time) hash * @throws IOException if an error occurs while reading the file */ - public static Sha256Hash of(boolean isSha256, File file) throws IOException { + public static Sha256Hash of(File file) throws IOException { try (FileInputStream in = new FileInputStream(file)) { - return of(isSha256, ByteStreams.toByteArray(in)); + return of(ByteStreams.toByteArray(in)); } } @@ -121,8 +120,8 @@ public static Sha256Hash of(boolean isSha256, File file) throws IOException { * Use {@link #twiceOf(byte[])} instead: this old name is ambiguous. */ @Deprecated - public static Sha256Hash createDouble(boolean isSha256, byte[] contents) { - return twiceOf(isSha256, contents); + public static Sha256Hash createDouble(byte[] contents) { + return twiceOf(contents); } /** @@ -131,8 +130,8 @@ public static Sha256Hash createDouble(boolean isSha256, byte[] contents) { * @param contents the bytes on which the hash value is calculated * @return a new instance containing the calculated (two-time) hash */ - public static Sha256Hash twiceOf(boolean isSha256, byte[] contents) { - return wrap(hashTwice(isSha256, contents)); + public static Sha256Hash twiceOf(byte[] contents) { + return wrap(hashTwice(contents)); } /** @@ -149,24 +148,14 @@ public static MessageDigest newDigest() { } } - /** - * Returns a new SM3 MessageDigest instance. This is a convenience method which wraps the checked - * exception that can never occur with a RuntimeException. - * - * @return a new SM3 MessageDigest instance - */ - public static SM3Digest newSM3Digest() { - return new SM3Digest(); - } - /** * Calculates the SHA-256 hash of the given bytes. * * @param input the bytes to hash * @return the hash (in big-endian order) */ - public static byte[] hash(boolean isSha256, byte[] input) { - return hash(isSha256, input, 0, input.length); + public static byte[] hash(byte[] input) { + return hash(input, 0, input.length); } /** @@ -177,19 +166,10 @@ public static byte[] hash(boolean isSha256, byte[] input) { * @param length the number of bytes to hash * @return the hash (in big-endian order) */ - public static byte[] hash(boolean isSha256, byte[] input, int offset, int length) { - if (isSha256) { - MessageDigest digest = newDigest(); - digest.update(input, offset, length); - return digest.digest(); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input, offset, length); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - return eHash; - } - + public static byte[] hash(byte[] input, int offset, int length) { + MessageDigest digest = newDigest(); + digest.update(input, offset, length); + return digest.digest(); } /** @@ -198,8 +178,8 @@ public static byte[] hash(boolean isSha256, byte[] input, int offset, int length * @param input the bytes to hash * @return the double-hash (in big-endian order) */ - public static byte[] hashTwice(boolean isSha256, byte[] input) { - return hashTwice(isSha256, input, 0, input.length); + public static byte[] hashTwice(byte[] input) { + return hashTwice(input, 0, input.length); } /** @@ -210,43 +190,22 @@ public static byte[] hashTwice(boolean isSha256, byte[] input) { * @param length the number of bytes to hash * @return the double-hash (in big-endian order) */ - public static byte[] hashTwice(boolean isSha256, byte[] input, int offset, int length) { - if (isSha256) { - MessageDigest digest = newDigest(); - digest.update(input, offset, length); - return digest.digest(digest.digest()); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input, offset, length); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - digest.reset(); - digest.update(eHash, 0, eHash.length); - digest.doFinal(eHash, 0); - return eHash; - } - + public static byte[] hashTwice(byte[] input, int offset, int length) { + MessageDigest digest = newDigest(); + digest.update(input, offset, length); + return digest.digest(digest.digest()); } /** * Calculates the hash of hash on the given byte ranges. This is equivalent to concatenating the * two ranges and then passing the result to {@link #hashTwice(byte[])}. */ - public static byte[] hashTwice(boolean isSha256, byte[] input1, int offset1, int length1, + public static byte[] hashTwice(byte[] input1, int offset1, int length1, byte[] input2, int offset2, int length2) { - if (isSha256) { - MessageDigest digest = newDigest(); - digest.update(input1, offset1, length1); - digest.update(input2, offset2, length2); - return digest.digest(digest.digest()); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input1, offset1, length1); - digest.update(input2, offset2, length2); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - return eHash; - } + MessageDigest digest = newDigest(); + digest.update(input1, offset1, length1); + digest.update(input2, offset2, length2); + return digest.digest(digest.digest()); } private byte[] generateBlockId(long blockNum, Sha256Hash blockHash) { 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 412a70d7f9c..d4958475394 100644 --- a/common/src/main/java/org/tron/common/utils/StringUtil.java +++ b/common/src/main/java/org/tron/common/utils/StringUtil.java @@ -16,7 +16,6 @@ package org.tron.common.utils; import com.google.protobuf.ByteString; -import org.tron.common.parameter.CommonParameter; public class StringUtil { @@ -29,8 +28,8 @@ public static String createReadableString(byte[] bytes) { } public static String encode58Check(byte[] input) { - byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), input); - byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), hash0); + byte[] hash0 = Sha256Hash.hash(input); + byte[] hash1 = Sha256Hash.hash(hash0); byte[] inputCheck = new byte[input.length + 4]; System.arraycopy(input, 0, inputCheck, 0, input.length); System.arraycopy(hash1, 0, inputCheck, input.length, 4); diff --git a/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java b/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java index 9e42552c80f..d5de7c70522 100644 --- a/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java +++ b/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java @@ -125,8 +125,7 @@ private State produceBlock() { raw.getNumber(), new DateTime(raw.getTimestamp()), ByteArray.toHexString(raw.getWitnessAddress().toByteArray()), - new Sha256Hash(raw.getNumber(), Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), raw.toByteArray())), + new Sha256Hash(raw.getNumber(), Sha256Hash.of(raw.toByteArray())), ByteArray.toHexString(raw.getParentHash().toByteArray())); } } finally { diff --git a/consensus/src/main/java/org/tron/consensus/pbft/message/PbftBaseMessage.java b/consensus/src/main/java/org/tron/consensus/pbft/message/PbftBaseMessage.java index 4eb61f3e22e..dd8a78a28d6 100644 --- a/consensus/src/main/java/org/tron/consensus/pbft/message/PbftBaseMessage.java +++ b/consensus/src/main/java/org/tron/consensus/pbft/message/PbftBaseMessage.java @@ -95,7 +95,7 @@ public DataType getDataType() { public abstract String getNo(); public void analyzeSignature() throws SignatureException { - byte[] hash = Sha256Hash.hash(true, getPbftMessage().getRawData().toByteArray()); + byte[] hash = Sha256Hash.hash(getPbftMessage().getRawData().toByteArray()); publicKey = ECKey.signatureToAddress(hash, TransactionCapsule .getBase64FromByteString(getPbftMessage().getSignature())); } diff --git a/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java b/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java index b6de49ee878..dbb49bcacb5 100644 --- a/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java +++ b/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java @@ -62,7 +62,7 @@ private static PbftMessage buildCommon(DataType dataType, ByteString data, Block rawBuilder.setViewN(viewN).setEpoch(epoch).setDataType(dataType) .setMsgType(MsgType.PREPREPARE).setData(data); Raw raw = rawBuilder.build(); - byte[] hash = Sha256Hash.hash(true, raw.toByteArray()); + byte[] hash = Sha256Hash.hash(raw.toByteArray()); ECDSASignature signature = ecKey.sign(hash); builder.setRawData(raw).setSignature(ByteString.copyFrom(signature.toByteArray())); PBFTMessage message = builder.build(); @@ -104,7 +104,7 @@ private PbftMessage buildMessageCapsule(MsgType type, Miner miner) { .setMsgType(type).setEpoch(getPbftMessage().getRawData().getEpoch()) .setData(getPbftMessage().getRawData().getData()); Raw raw = rawBuilder.build(); - byte[] hash = Sha256Hash.hash(true, raw.toByteArray()); + byte[] hash = Sha256Hash.hash(raw.toByteArray()); ECDSASignature signature = ecKey.sign(hash); builder.setRawData(raw).setSignature(ByteString.copyFrom(signature.toByteArray())); PBFTMessage message = builder.build(); diff --git a/crypto/src/main/java/org/tron/common/crypto/SignUtils.java b/crypto/src/main/java/org/tron/common/crypto/SignUtils.java index b921d548e8b..cd2ccf14767 100644 --- a/crypto/src/main/java/org/tron/common/crypto/SignUtils.java +++ b/crypto/src/main/java/org/tron/common/crypto/SignUtils.java @@ -2,54 +2,32 @@ import java.security.SecureRandom; import java.security.SignatureException; -import org.tron.common.crypto.ECKey.ECDSASignature; -import org.tron.common.crypto.sm2.SM2; -import org.tron.common.crypto.sm2.SM2.SM2Signature; public class SignUtils { - public static SignInterface getGeneratedRandomSign( - SecureRandom secureRandom, boolean isECKeyCryptoEngine) { - if (isECKeyCryptoEngine) { - return new ECKey(secureRandom); - } - return new SM2(secureRandom); + public static SignInterface getGeneratedRandomSign(SecureRandom secureRandom) { + return new ECKey(secureRandom); } - public static SignInterface fromPrivate(byte[] privKeyBytes, boolean isECKeyCryptoEngine) { - if (isECKeyCryptoEngine) { - return ECKey.fromPrivate(privKeyBytes); - } - return SM2.fromPrivate(privKeyBytes); + public static SignInterface fromPrivate(byte[] privKeyBytes) { + return ECKey.fromPrivate(privKeyBytes); } - public static byte[] signatureToAddress( - byte[] messageHash, String signatureBase64, boolean isECKeyCryptoEngine) + public static byte[] signatureToAddress(byte[] messageHash, String signatureBase64) throws SignatureException { try { - if (isECKeyCryptoEngine) { - return ECKey.signatureToAddress(messageHash, signatureBase64); - } - return SM2.signatureToAddress(messageHash, signatureBase64); + return ECKey.signatureToAddress(messageHash, signatureBase64); } catch (Exception e) { throw new SignatureException(e); } } - public static SignatureInterface fromComponents( - byte[] r, byte[] s, byte v, boolean isECKeyCryptoEngine) { - if (isECKeyCryptoEngine) { - return ECKey.ECDSASignature.fromComponents(r, s, v); - } - return SM2.SM2Signature.fromComponents(r, s, v); + public static SignatureInterface fromComponents(byte[] r, byte[] s, byte v) { + return ECKey.ECDSASignature.fromComponents(r, s, v); } - public static byte[] signatureToAddress( - byte[] messageHash, SignatureInterface signatureInterface, boolean isECKeyCryptoEngine) + public static byte[] signatureToAddress(byte[] messageHash, SignatureInterface signatureInterface) throws SignatureException { - if (isECKeyCryptoEngine) { - return ECKey.signatureToAddress(messageHash, (ECDSASignature) signatureInterface); - } - return SM2.signatureToAddress(messageHash, (SM2Signature) signatureInterface); + return ECKey.signatureToAddress(messageHash, (ECKey.ECDSASignature) signatureInterface); } } diff --git a/crypto/src/main/java/org/tron/common/crypto/sm2/SM2.java b/crypto/src/main/java/org/tron/common/crypto/sm2/SM2.java deleted file mode 100644 index b1d349efad3..00000000000 --- a/crypto/src/main/java/org/tron/common/crypto/sm2/SM2.java +++ /dev/null @@ -1,1144 +0,0 @@ -package org.tron.common.crypto.sm2; - -import static org.tron.common.crypto.Hash.computeAddress; -import static org.tron.common.utils.BIUtil.isLessThan; -import static org.tron.common.utils.ByteUtil.bigIntegerToBytes; - -import java.io.IOException; -import java.io.Serializable; -import java.math.BigInteger; -import java.nio.charset.Charset; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.InvalidKeySpecException; -import java.util.Arrays; -import java.util.Objects; -import javax.annotation.Nullable; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.DLSequence; -import org.bouncycastle.asn1.x9.X9IntegerConverter; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.generators.ECKeyPairGenerator; -import org.bouncycastle.crypto.params.ECDomainParameters; -import org.bouncycastle.crypto.params.ECKeyGenerationParameters; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey; -import org.bouncycastle.jce.spec.ECParameterSpec; -import org.bouncycastle.jce.spec.ECPrivateKeySpec; -import org.bouncycastle.math.ec.ECAlgorithms; -import org.bouncycastle.math.ec.ECCurve; -import org.bouncycastle.math.ec.ECPoint; -import org.bouncycastle.util.encoders.Base64; -import org.bouncycastle.util.encoders.Hex; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.SignInterface; -import org.tron.common.crypto.SignatureInterface; -import org.tron.common.crypto.jce.ECKeyFactory; -import org.tron.common.crypto.jce.TronCastleProvider; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; - -/** - * Implement Chinese Commercial Cryptographic Standard of SM2 - */ -@Slf4j(topic = "crypto") -public class SM2 implements Serializable, SignInterface { - - private static BigInteger SM2_N = new BigInteger( - "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16); - private static BigInteger SM2_P = new BigInteger( - "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16); - private static BigInteger SM2_A = new BigInteger( - "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", 16); - private static BigInteger SM2_B = new BigInteger( - "28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16); - private static BigInteger SM2_GX = new BigInteger( - "32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", 16); - private static BigInteger SM2_GY = new BigInteger( - "BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", 16); - - private static ECDomainParameters ecc_param; - private static ECParameterSpec ecc_spec; - private static ECCurve.Fp curve; - private static ECPoint ecc_point_g; - - private static final SecureRandom secureRandom; - - - static { - secureRandom = new SecureRandom(); - curve = new ECCurve.Fp(SM2_P, SM2_A, SM2_B, null, null); - ecc_point_g = curve.createPoint(SM2_GX, SM2_GY); - ecc_param = new ECDomainParameters(curve, ecc_point_g, SM2_N); - ecc_spec = new ECParameterSpec(curve, ecc_point_g, SM2_N); - } - - protected final ECPoint pub; - - private final PrivateKey privKey; - - - // Transient because it's calculated on demand. - private transient byte[] pubKeyHash; - private transient byte[] nodeId; - - - public SM2() { - this(secureRandom); - } - /** - * Generates an entirely new keypair. - * - *

BouncyCastle will be used as the Java Security Provider - */ - - - /** - * Generate a new keypair using the given Java Security Provider. - * - *

All private key operations will use the provider. - */ - public SM2(SecureRandom secureRandom) { - - ECKeyGenerationParameters ecKeyGenerationParameters = new ECKeyGenerationParameters(ecc_param, - secureRandom); - ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator(); - keyPairGenerator.init(ecKeyGenerationParameters); - AsymmetricCipherKeyPair kp = keyPairGenerator.generateKeyPair(); - ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) kp.getPrivate(); - ECPublicKeyParameters ecpub = (ECPublicKeyParameters) kp.getPublic(); - - BigInteger privateKey = ecpriv.getD(); - this.privKey = privateKeyFromBigInteger(privateKey); - this.pub = ecpub.getQ(); - } - - public SM2(byte[] key, boolean isPrivateKey) { - if (isPrivateKey) { - BigInteger pk = new BigInteger(1, key); - this.privKey = privateKeyFromBigInteger(pk); - this.pub = ecc_param.getG().multiply(pk); - } else { - this.privKey = null; - this.pub = ecc_param.getCurve().decodePoint(key); - } - } - - - /** - * Pair a private key with a public EC point. - * - *

All private key operations will use the provider. - */ - - public SM2(@Nullable PrivateKey privKey, ECPoint pub) { - - if (privKey == null || isECPrivateKey(privKey)) { - this.privKey = privKey; - } else { - throw new IllegalArgumentException( - "Expected EC private key, given a private key object with" + - " class " - + privKey.getClass().toString() + - " and algorithm " - + privKey.getAlgorithm()); - } - - if (pub == null) { - throw new IllegalArgumentException("Public key may not be null"); - } else { - this.pub = pub; - } - } - - /** - * Pair a private key integer with a public EC point - */ - public SM2(@Nullable BigInteger priv, ECPoint pub) { - this( - privateKeyFromBigInteger(priv), - pub - ); - } - - /** - * Convert a BigInteger into a PrivateKey object - */ - private static PrivateKey privateKeyFromBigInteger(BigInteger priv) { - if (priv == null) { - return null; - } else { - try { - return ECKeyFactory - .getInstance(TronCastleProvider.getInstance()) - .generatePrivate(new ECPrivateKeySpec(priv, - ecc_spec)); - } catch (InvalidKeySpecException ex) { - throw new AssertionError("Assumed correct key spec statically"); - } - } - } - - /* Test if a generic private key is an EC private key - * - * it is not sufficient to check that privKey is a subtype of ECPrivateKey - * as the SunPKCS11 Provider will return a generic PrivateKey instance - * a fallback that covers this case is to check the key algorithm - */ - private static boolean isECPrivateKey(PrivateKey privKey) { - return privKey instanceof ECPrivateKey || privKey.getAlgorithm() - .equals("EC"); - } - - /* Convert a Java JCE ECPublicKey into a BouncyCastle ECPoint - */ - private static ECPoint extractPublicKey(final ECPublicKey ecPublicKey) { - final java.security.spec.ECPoint publicPointW = ecPublicKey.getW(); - final BigInteger xCoord = publicPointW.getAffineX(); - final BigInteger yCoord = publicPointW.getAffineY(); - - return ecc_param.getCurve().createPoint(xCoord, yCoord); - } - - - /** - * Utility for compressing an elliptic curve point. Returns the same point if it's already - * compressed. See the ECKey class docs for a discussion of point compression. - * - * @param uncompressed - - * @return - - * @deprecated per-point compression property will be removed in Bouncy Castle - */ - public static ECPoint compressPoint(ECPoint uncompressed) { - return ecc_param.getCurve().decodePoint(uncompressed.getEncoded(true)); - } - - /** - * Utility for decompressing an elliptic curve point. Returns the same point if it's already - * compressed. See the ECKey class docs for a discussion of point compression. - * - * @param compressed - - * @return - - * @deprecated per-point compression property will be removed in Bouncy Castle - */ - public static ECPoint decompressPoint(ECPoint compressed) { - return ecc_param.getCurve().decodePoint(compressed.getEncoded(false)); - } - - /** - * Creates an SM2 given the private key only. - * - * @param privKey - - * @return - - */ - public static SM2 fromPrivate(BigInteger privKey) { - return new SM2(privKey, ecc_param.getG().multiply(privKey)); - } - - /** - * Creates an SM2 given the private key only. - * - * @param privKeyBytes - - * @return - - */ - public static SM2 fromPrivate(byte[] privKeyBytes) { - if (ByteArray.isEmpty(privKeyBytes)) { - return null; - } - return fromPrivate(new BigInteger(1, privKeyBytes)); - } - - /** - * Creates an SM2 that simply trusts the caller to ensure that point is really the result of - * multiplying the generator point by the private key. This is used to speed things up when you - * know you have the right values already. The compression state of pub will be preserved. - * - * @param priv - - * @param pub - - * @return - - */ - public static SM2 fromPrivateAndPrecalculatedPublic(BigInteger priv, - ECPoint pub) { - return new SM2(priv, pub); - } - - /** - * Creates an SM2 that simply trusts the caller to ensure that point is really the result of - * multiplying the generator point by the private key. This is used to speed things up when you - * know you have the right values already. The compression state of the point will be preserved. - * - * @param priv - - * @param pub - - * @return - - */ - public static SM2 fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] - pub) { - check(priv != null, "Private key must not be null"); - check(pub != null, "Public key must not be null"); - return new SM2(new BigInteger(1, priv), ecc_param.getCurve() - .decodePoint(pub)); - } - - /** - * Creates an SM2 that cannot be used for signing, only verifying signatures, from the given - * point. The compression state of pub will be preserved. - * - * @param pub - - * @return - - */ - public static SM2 fromPublicOnly(ECPoint pub) { - return new SM2((PrivateKey) null, pub); - } - - /** - * Creates an SM2 that cannot be used for signing, only verifying signatures, from the given - * encoded point. The compression state of pub will be preserved. - * - * @param pub - - * @return - - */ - public static SM2 fromPublicOnly(byte[] pub) { - return new SM2((PrivateKey) null, ecc_param.getCurve().decodePoint(pub)); - } - - /** - * Returns public key bytes from the given private key. To convert a byte array into a BigInteger, - * use new BigInteger(1, bytes); - * - * @param privKey - - * @param compressed - - * @return - - */ - public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean - compressed) { - ECPoint point = ecc_param.getG().multiply(privKey); - return point.getEncoded(compressed); - } - - /** - * Compute the encoded X, Y coordinates of a public point.

This is the encoded public key - * without the leading byte. - * - * @param pubPoint a public point - * @return 64-byte X,Y point pair - */ - public static byte[] pubBytesWithoutFormat(ECPoint pubPoint) { - final byte[] pubBytes = pubPoint.getEncoded(/* uncompressed */ false); - return Arrays.copyOfRange(pubBytes, 1, pubBytes.length); - } - - /** - * Recover the public key from an encoded node id. - * - * @param nodeId a 64-byte X,Y point pair - */ - public static SM2 fromNodeId(byte[] nodeId) { - check(nodeId.length == 64, "Expected a 64 byte node id"); - byte[] pubBytes = new byte[65]; - System.arraycopy(nodeId, 0, pubBytes, 1, nodeId.length); - pubBytes[0] = 0x04; // uncompressed - return SM2.fromPublicOnly(pubBytes); - } - - public static byte[] signatureToKeyBytes(byte[] messageHash, String - signatureBase64) throws SignatureException { - byte[] signatureEncoded; - try { - signatureEncoded = Base64.decode(signatureBase64); - } catch (RuntimeException e) { - // This is what you getData back from Bouncy Castle if base64 doesn't - // decode :( - throw new SignatureException("Could not decode base64", e); - } - // Parse the signature bytes into r/s and the selector value. - if (signatureEncoded.length < 65) { - throw new SignatureException("Signature truncated, expected 65 " + - "bytes and got " + signatureEncoded.length); - } - - return signatureToKeyBytes( - messageHash, - SM2Signature.fromComponents( - Arrays.copyOfRange(signatureEncoded, 1, 33), - Arrays.copyOfRange(signatureEncoded, 33, 65), - (byte) (signatureEncoded[0] & 0xFF))); - } - - public static byte[] signatureToKeyBytes(byte[] messageHash, - SM2Signature sig) throws - SignatureException { - check(messageHash.length == 32, "messageHash argument has length " + - messageHash.length); - int header = sig.v; - // The header byte: 0x1B = first key with even y, 0x1C = first key - // with odd y, - // 0x1D = second key with even y, 0x1E = second key - // with odd y - if (header < 27 || header > 34) { - throw new SignatureException("Header byte out of range: " + header); - } - if (header >= 31) { - header -= 4; - } - int recId = header - 27; - byte[] key = recoverPubBytesFromSignature(recId, sig, - messageHash); - if (key == null) { - throw new SignatureException("Could not recover public key from " + - "signature"); - } - return key; - } - - - public byte[] hash(byte[] message) { - SM2Signer signer = this.getSM2SignerForHash(); - return signer.generateSM3Hash(message); - } - - @Override - public byte[] getPrivateKey() { - return getPrivKeyBytes(); - } - - /** - * Gets the encoded public key value. - * - * @return 65-byte encoded public key - */ - @Override - public byte[] getPubKey() { - return pub.getEncoded(/* compressed */ false); - } - - /** - * Gets the address form of the public key. - * - * @return 21-byte address - */ - @Override - public byte[] getAddress() { - if (pubKeyHash == null) { - pubKeyHash = computeAddress(this.pub); - } - return pubKeyHash; - } - - - /** - * Compute the address of the key that signed the given signature. - * - * @param messageHash 32-byte hash of message - * @param signatureBase64 Base-64 encoded signature - * @return 20-byte address - */ - public static byte[] signatureToAddress(byte[] messageHash, String - signatureBase64) throws SignatureException { - return computeAddress(signatureToKeyBytes(messageHash, - signatureBase64)); - } - - /** - * Compute the address of the key that signed the given signature. - * - * @param messageHash 32-byte hash of message - * @param sig - - * @return 20-byte address - */ - public static byte[] signatureToAddress(byte[] messageHash, - SM2Signature sig) throws - SignatureException { - return computeAddress(signatureToKeyBytes(messageHash, sig)); - } - - /** - * Compute the key that signed the given signature. - * - * @param messageHash 32-byte hash of message - * @param signatureBase64 Base-64 encoded signature - * @return ECKey - */ - public static SM2 signatureToKey(byte[] messageHash, String - signatureBase64) throws SignatureException { - final byte[] keyBytes = signatureToKeyBytes(messageHash, - signatureBase64); - return fromPublicOnly(keyBytes); - } - - /** - * Compute the key that signed the given signature. - * - * @param messageHash 32-byte hash of message - * @param sig - - * @return ECKey - */ - public static SM2 signatureToKey(byte[] messageHash, SM2Signature - sig) throws SignatureException { - final byte[] keyBytes = signatureToKeyBytes(messageHash, sig); - return fromPublicOnly(keyBytes); - } - - /** - * Takes the SM3 hash (32 bytes) of data and returns the SM2 signature which including the v - * - * @param messageHash - - * @return - - * @throws IllegalStateException if this ECKey does not have the private part. - */ - public SM2Signature sign(byte[] messageHash) { - if (messageHash.length != 32) { - throw new IllegalArgumentException("Expected 32 byte input to " + - "SM2 signature, not " + messageHash.length); - } - // No decryption of private key required. - SM2Signer signer = getSigner(); - BigInteger[] componets = signer.generateHashSignature(messageHash); - - SM2Signature sig = new SM2Signature(componets[0], componets[1]); - // Now we have to work backwards to figure out the recId needed to - // recover the signature. - int recId = -1; - byte[] thisKey = this.pub.getEncoded(/* compressed */ false); - for (int i = 0; i < 4; i++) { - byte[] k = recoverPubBytesFromSignature(i, sig, messageHash); - if (k != null && Arrays.equals(k, thisKey)) { - recId = i; - break; - } - } - if (recId == -1) { - throw new RuntimeException("Could not construct a recoverable key" + - ". This should never happen."); - } - sig.v = (byte) (recId + 27); - return sig; - } - - /** - * Signs the given hash and returns the R and S components as BigIntegers and putData them in - * SM2Signature - * - * @param input to sign - * @return SM2Signature signature that contains the R and S components - */ - public String signHash(byte[] input) { - return sign(input).toBase64(); - } - - public byte[] Base64toBytes(String signature) { - byte[] signData = Base64.decode(signature); - byte first = (byte) (signData[0] - 27); - byte[] temp = Arrays.copyOfRange(signData, 1, 65); - return ByteUtil.appendByte(temp, first); - } - - /** - * Takes the message of data and returns the SM2 signature - * - * @param message - - * @return - - * @throws IllegalStateException if this ECKey does not have the private part. - */ - public SM2Signature signMessage(byte[] message, @Nullable String userID) { - SM2Signature sig = signMsg(message, userID); - // Now we have to work backwards to figure out the recId needed to - // recover the signature. - int recId = -1; - byte[] thisKey = this.pub.getEncoded(/* compressed */ false); - - SM2Signer signer = getSigner(); - byte[] messageHash = signer.generateSM3Hash(message); - for (int i = 0; i < 4; i++) { - byte[] k = recoverPubBytesFromSignature(i, sig, messageHash); - if (k != null && Arrays.equals(k, thisKey)) { - recId = i; - break; - } - } - if (recId == -1) { - throw new RuntimeException("Could not construct a recoverable key" + - ". This should never happen."); - } - sig.v = (byte) (recId + 27); - return sig; - } - - /** - * Signs the given hash and returns the R and S components as BigIntegers and putData them in - * SM2Signature - * - * @param msg to sign - * @return SM2Signature signature that contains the R and S components - */ - public SM2Signature signMsg(byte[] msg, @Nullable String userID) { - if (null == msg) { - throw new IllegalArgumentException("Expected signature message of " + - "SM2 is null"); - } - // No decryption of private key required. - SM2Signer signer = getSigner(); - BigInteger[] componets = signer.generateSignature(msg); - return new SM2Signature(componets[0], componets[1]); - } - - private SM2Signer getSigner() { - SM2Signer signer = new SM2Signer(); - BigInteger d = getPrivKey(); - ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(d, ecc_param); - signer.init(true, privateKeyParameters); - return signer; - } - - /** - * used to generate the SM3 hash for SM2 signature generation or verification - */ - public SM2Signer getSM2SignerForHash() { - SM2Signer signer = new SM2Signer(); - ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pub, ecc_param); - signer.init(false, publicKeyParameters); - return signer; - } - - - /** - *

Given the components of a signature and a selector value, recover and return the public key - * that generated the signature - */ - @Nullable - public static byte[] recoverPubBytesFromSignature(int recId, - SM2Signature sig, - byte[] messageHash) { - check(recId >= 0, "recId must be positive"); - check(sig.r.signum() >= 0, "r must be positive"); - check(sig.s.signum() >= 0, "s must be positive"); - check(messageHash != null, "messageHash must not be null"); - // 1.0 For j from 0 to h (h == recId here and the loop is outside - // this function) - // 1.1 Let x = r + jn - BigInteger n = ecc_param.getN(); // Curve order. - BigInteger prime = curve.getQ(); - BigInteger i = BigInteger.valueOf((long) recId / 2); - - BigInteger e = new BigInteger(1, messageHash); - BigInteger x = sig.r.subtract(e).mod(n); // r = (x + e) mod n - x = x.add(i.multiply(n)); - // 1.2. Convert the integer x to an octet string X of length mlen - // using the conversion routine - // specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or - // mlen = ⌈m/8⌉. - // 1.3. Convert the octet string (16 set binary digits)||X to an - // elliptic curve point R using the - // conversion routine specified in Section 2.3.4. If this - // conversion routine outputs “invalid”, then - // do another iteration of Step 1. - // - // More concisely, what these points mean is to use X as a compressed - // public key. - ECCurve.Fp curve = (ECCurve.Fp) ecc_param.getCurve(); - // Bouncy Castle is not consistent - // about the letter it uses for the prime. - if (x.compareTo(prime) >= 0) { - // Cannot have point co-ordinates larger than this as everything - // takes place modulo Q. - return null; - } - // Compressed allKeys require you to know an extra bit of data about the - // y-coord as there are two possibilities. - // So it's encoded in the recId. - ECPoint R = decompressKey(x, (recId & 1) == 1); - // 1.4. If nR != point at infinity, then do another iteration of - // Step 1 (callers responsibility). - if (!R.multiply(n).isInfinity()) { - return null; - } - - // recover Q from the formula: s*G + (s+r)*Q = R => Q = (s+r)^(-1) (R-s*G) - BigInteger srInv = sig.s.add(sig.r).modInverse(n); - BigInteger sNeg = BigInteger.ZERO.subtract(sig.s).mod(n); - BigInteger coeff = srInv.multiply(sNeg).mod(n); - - ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(ecc_param - .getG(), coeff, R, srInv); - return q.getEncoded(/* compressed */ false); - } - - /** - * Decompress a compressed public key (x co-ord and low-bit of y-coord). - * - * @param xBN - - * @param yBit - - * @return - - */ - - private static ECPoint decompressKey(BigInteger xBN, boolean yBit) { - X9IntegerConverter x9 = new X9IntegerConverter(); - byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(ecc_param - .getCurve())); - compEnc[0] = (byte) (yBit ? 0x03 : 0x02); - return ecc_param.getCurve().decodePoint(compEnc); - } - - private static void check(boolean test, String message) { - if (!test) { - throw new IllegalArgumentException(message); - } - } - - /** - *

Verifies the given SM2 signature against the message bytes using the public key bytes.

- *

When using native SM2 verification, data must be 32 bytes, and no element may be - * larger than 520 bytes.

- * - * @param data Hash of the data to verify. - * @param signature signature. - * @param pub The public key bytes to use. - * @return - - */ - public static boolean verify(byte[] data, SM2Signature signature, - byte[] pub) { - SM2Signer signer = new SM2Signer(); - ECPublicKeyParameters params = new ECPublicKeyParameters(ecc_param - .getCurve().decodePoint(pub), ecc_param); - signer.init(false, params); - try { - return signer.verifyHashSignature(data, signature.r, signature.s); - } catch (NullPointerException npe) { - // Bouncy Castle contains a bug that can cause NPEs given - // specially crafted signatures. - // Those signatures are inherently invalid/attack sigs so we just - // fail them here rather than crash the thread. - logger.error("Caught NPE inside bouncy castle", npe); - return false; - } - } - - /** - * Verifies the given ASN.1 encoded SM2 signature against a hash using the public key. - * - * @param data Hash of the data to verify. - * @param signature signature. - * @param pub The public key bytes to use. - * @return - - */ - public static boolean verify(byte[] data, byte[] signature, byte[] pub) { - return verify(data, SM2Signature.decodeFromDER(signature), pub); - } - - /** - *

Verifies the given SM2 signature against the message bytes using the public key bytes. - * - * @param msg the message data to verify. - * @param signature signature. - * @param pub The public key bytes to use. - * @return - - */ - public static boolean verifyMessage(byte[] msg, SM2Signature signature, - byte[] pub, @Nullable String userID) { - SM2Signer signer = new SM2Signer(); - ECPublicKeyParameters params = new ECPublicKeyParameters(ecc_param - .getCurve().decodePoint(pub), ecc_param); - signer.init(false, params); - try { - return signer.verifySignature(msg, signature.r, signature.s, userID); - } catch (NullPointerException npe) { - // Bouncy Castle contains a bug that can cause NPEs given - // specially crafted signatures. - // Those signatures are inherently invalid/attack sigs so we just - // fail them here rather than crash the thread. - logger.error("Caught NPE inside bouncy castle", npe); - return false; - } - } - - /** - * Verifies the given ASN.1 encoded SM2 signature against a hash using the public key. - * - * @param msg the message data to verify. - * @param signature signature. - * @param pub The public key bytes to use. - * @return - - */ - public static boolean verifyMessage(byte[] msg, byte[] signature, byte[] pub, - @Nullable String userID) { - return verifyMessage(msg, SM2Signature.decodeFromDER(signature), pub, userID); - } - - - /** - * Returns true if the given pubkey is canonical, i.e. the correct length taking into account - * compression. - * - * @param pubkey - - * @return - - */ - public static boolean isPubKeyCanonical(byte[] pubkey) { - if (pubkey[0] == 0x04) { - // Uncompressed pubkey - return pubkey.length == 65; - } else if (pubkey[0] == 0x02 || pubkey[0] == 0x03) { - // Compressed pubkey - return pubkey.length == 33; - } else { - return false; - } - } - - /** - * @param recId Which possible key to recover. - * @param sig the R and S components of the signature, wrapped. - * @param messageHash Hash of the data that was signed. - * @return 20-byte address - */ - @Nullable - public static byte[] recoverAddressFromSignature(int recId, - SM2Signature sig, - byte[] messageHash) { - final byte[] pubBytes = recoverPubBytesFromSignature(recId, sig, - messageHash); - if (pubBytes == null) { - return null; - } else { - return computeAddress(pubBytes); - } - } - - /** - * @param recId Which possible key to recover. - * @param sig the R and S components of the signature, wrapped. - * @param messageHash Hash of the data that was signed. - * @return ECKey - */ - @Nullable - public static SM2 recoverFromSignature(int recId, SM2Signature sig, - byte[] messageHash) { - final byte[] pubBytes = recoverPubBytesFromSignature(recId, sig, - messageHash); - if (pubBytes == null) { - return null; - } else { - return fromPublicOnly(pubBytes); - } - } - - /** - * Returns true if this key doesn't have access to private key bytes. This may be because it was - * never given any private key bytes to begin with (a watching key). - * - * @return - - */ - public boolean isPubKeyOnly() { - return privKey == null; - } - - /** - * Returns true if this key has access to private key bytes. Does the opposite of {@link - * #isPubKeyOnly()}. - * - * @return - - */ - public boolean hasPrivKey() { - return privKey != null; - } - - - /** - * Generates the NodeID based on this key, that is the public key without first format byte - */ - public byte[] getNodeId() { - if (nodeId == null) { - nodeId = pubBytesWithoutFormat(this.pub); - } - return nodeId; - } - - - /** - * Gets the public key in the form of an elliptic curve point object from Bouncy Castle. - * - * @return - - */ - public ECPoint getPubKeyPoint() { - return pub; - } - - /** - * Gets the private key in the form of an integer field element. The public key is derived by - * performing EC point addition this number of times (i.e. point multiplying). - * - * @return - - * @throws IllegalStateException if the private key bytes are not available. - */ - public BigInteger getPrivKey() { - if (privKey == null) { - throw new ECKey.MissingPrivateKeyException(); - } else if (privKey instanceof BCECPrivateKey) { - return ((BCECPrivateKey) privKey).getD(); - } else { - throw new ECKey.MissingPrivateKeyException(); - } - } - - public String toString() { - StringBuilder b = new StringBuilder(); - b.append("pub:").append(Hex.toHexString(pub.getEncoded(false))); - return b.toString(); - } - - /** - * Produce a string rendering of the ECKey INCLUDING the private key. Unless you absolutely need - * the private key it is better for security reasons to just use toString(). - * - * @return - - */ - public String toStringWithPrivate() { - StringBuilder b = new StringBuilder(); - b.append(toString()); - if (privKey != null && privKey instanceof BCECPrivateKey) { - b.append(" priv:").append(Hex.toHexString(((BCECPrivateKey) - privKey).getD().toByteArray())); - } - return b.toString(); - } - - /** - * Verifies the given ASN.1 encoded SM2 signature against a hash using the public key. - * - * @param data Hash of the data to verify. - * @param signature signature. - * @return - - */ - public boolean verify(byte[] data, byte[] signature) { - return SM2.verify(data, signature, getPubKey()); - } - - /** - * Verifies the given R/S pair (signature) against a hash using the public key. - * - * @param sigHash - - * @param signature - - * @return - - */ - public boolean verify(byte[] sigHash, SM2Signature signature) { - return SM2.verify(sigHash, signature, getPubKey()); - } - - /** - * Returns true if this pubkey is canonical, i.e. the correct length taking into account - * compression. - * - * @return - - */ - public boolean isPubKeyCanonical() { - return isPubKeyCanonical(pub.getEncoded(/* uncompressed */ false)); - } - - /** - * Returns a 32 byte array containing the private key, or null if the key is encrypted or public - * only - * - * @return - - */ - @Nullable - public byte[] getPrivKeyBytes() { - if (privKey == null) { - return null; - } else if (privKey instanceof BCECPrivateKey) { - return bigIntegerToBytes(((BCECPrivateKey) privKey).getD(), 32); - } else { - return null; - } - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - SM2 ecKey = (SM2) o; - - if (privKey != null && !privKey.equals(ecKey.privKey)) { - return false; - } - return pub == null || pub.equals(ecKey.pub); - } - - @Override - public int hashCode() { - return Arrays.hashCode(getPubKey()); - } - - - public static class SM2Signature implements SignatureInterface { - - /** - * The two components of the signature. - */ - public final BigInteger r, s; - public byte v; - - /** - * Constructs a signature with the given components. Does NOT automatically canonicalise the - * signature. - * - * @param r - - * @param s - - */ - public SM2Signature(BigInteger r, BigInteger s) { - this.r = r; - this.s = s; - } - - public SM2Signature(byte[] r, byte[] s, byte v) { - this.r = new BigInteger(1, r); - this.s = new BigInteger(1, s); - this.v = v; - } - - /** - * t - * - * @return - - */ - private static SM2Signature fromComponents(byte[] r, byte[] s) { - return new SM2Signature(new BigInteger(1, r), new BigInteger(1, - s)); - } - - /** - * @param r - - * @param s - - * @param v - - * @return - - */ - public static SM2Signature fromComponents(byte[] r, byte[] s, byte - v) { - SM2Signature signature = fromComponents(r, s); - signature.v = v; - return signature; - } - - public static boolean validateComponents(BigInteger r, BigInteger s, - byte v) { - - if (v != 27 && v != 28) { - return false; - } - - if (isLessThan(r, BigInteger.ONE)) { - return false; - } - if (isLessThan(s, BigInteger.ONE)) { - return false; - } - - if (!isLessThan(r, SM2.SM2_N)) { - return false; - } - return isLessThan(s, SM2.SM2_N); - } - - public static SM2Signature decodeFromDER(byte[] bytes) { - ASN1InputStream decoder = null; - try { - decoder = new ASN1InputStream(bytes); - DLSequence seq = (DLSequence) decoder.readObject(); - if (seq == null) { - throw new RuntimeException("Reached past end of ASN.1 " - + "stream."); - } - ASN1Integer r, s; - try { - r = (ASN1Integer) seq.getObjectAt(0); - s = (ASN1Integer) seq.getObjectAt(1); - } catch (ClassCastException e) { - throw new IllegalArgumentException(e); - } - // OpenSSL deviates from the DER spec by interpreting these - // values as unsigned, though they should not be - // Thus, we always use the positive versions. See: - // http://r6.ca/blog/20111119T211504Z.html - return new SM2Signature(r.getPositiveValue(), s - .getPositiveValue()); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - if (decoder != null) { - try { - decoder.close(); - } catch (IOException x) { - - } - } - } - } - - public boolean validateComponents() { - return validateComponents(r, s, v); - } - - - /** - * @return - - */ - public String toBase64() { - byte[] sigData = new byte[65]; // 1 header + 32 bytes for R + 32 - // bytes for S - sigData[0] = v; - System.arraycopy(bigIntegerToBytes(this.r, 32), 0, sigData, 1, 32); - System.arraycopy(bigIntegerToBytes(this.s, 32), 0, sigData, 33, 32); - return new String(Base64.encode(sigData), Charset.forName("UTF-8")); - } - - - public byte[] toByteArray() { - final byte fixedV = this.v >= 27 - ? (byte) (this.v - 27) - : this.v; - - return ByteUtil.merge( - ByteUtil.bigIntegerToBytes(this.r, 32), - ByteUtil.bigIntegerToBytes(this.s, 32), - new byte[]{fixedV}); - } - - public String toHex() { - return Hex.toHexString(toByteArray()); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - SM2Signature signature = (SM2Signature) o; - - if (!r.equals(signature.r)) { - return false; - } - return s.equals(signature.s); - } - - @Override - public int hashCode() { - int result = r.hashCode(); - result = 31 * result + s.hashCode(); - return result; - } - } - -} diff --git a/crypto/src/main/java/org/tron/common/crypto/sm2/SM2Signer.java b/crypto/src/main/java/org/tron/common/crypto/sm2/SM2Signer.java deleted file mode 100644 index 817b909de58..00000000000 --- a/crypto/src/main/java/org/tron/common/crypto/sm2/SM2Signer.java +++ /dev/null @@ -1,262 +0,0 @@ -package org.tron.common.crypto.sm2; - -import java.math.BigInteger; -import java.security.SecureRandom; -import javax.annotation.Nullable; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.Digest; -import org.bouncycastle.crypto.digests.SM3Digest; -import org.bouncycastle.crypto.params.ECDomainParameters; -import org.bouncycastle.crypto.params.ECKeyParameters; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.bouncycastle.crypto.params.ParametersWithID; -import org.bouncycastle.crypto.params.ParametersWithRandom; -import org.bouncycastle.crypto.signers.DSAKCalculator; -import org.bouncycastle.crypto.signers.RandomDSAKCalculator; -import org.bouncycastle.math.ec.ECConstants; -import org.bouncycastle.math.ec.ECFieldElement; -import org.bouncycastle.math.ec.ECMultiplier; -import org.bouncycastle.math.ec.ECPoint; -import org.bouncycastle.math.ec.FixedPointCombMultiplier; -import org.bouncycastle.util.BigIntegers; - -public class SM2Signer - implements ECConstants { - - private final DSAKCalculator kCalculator = new RandomDSAKCalculator(); - - private byte[] userID; - - private int curveLength; - private ECDomainParameters ecParams; - private ECPoint pubPoint; - private ECKeyParameters ecKey; - - private SecureRandom random; - - public void init(boolean forSigning, CipherParameters param) { - CipherParameters baseParam; - - if (param instanceof ParametersWithID) { - baseParam = ((ParametersWithID) param).getParameters(); - userID = ((ParametersWithID) param).getID(); - } else { - baseParam = param; - userID = new byte[0]; - } - - if (forSigning) { - if (baseParam instanceof ParametersWithRandom) { - ParametersWithRandom rParam = (ParametersWithRandom) baseParam; - - ecKey = (ECKeyParameters) rParam.getParameters(); - ecParams = ecKey.getParameters(); - kCalculator.init(ecParams.getN(), rParam.getRandom()); - } else { - ecKey = (ECKeyParameters) baseParam; - ecParams = ecKey.getParameters(); - kCalculator.init(ecParams.getN(), new SecureRandom()); - } - pubPoint = ecParams.getG().multiply(((ECPrivateKeyParameters) ecKey).getD()).normalize(); - } else { - ecKey = (ECKeyParameters) baseParam; - ecParams = ecKey.getParameters(); - pubPoint = ((ECPublicKeyParameters) ecKey).getQ(); - } - - curveLength = (ecParams.getCurve().getFieldSize() + 7) / 8; - } - - - /** - * generate the signature for the message - * - * @param message plaintext - */ - public BigInteger[] generateSignature(byte[] message) { - byte[] eHash = generateSM3Hash(message); - return generateHashSignature(eHash); - } - - /** - * generate the signature for the message - */ - - public byte[] generateSM3Hash(byte[] message) { - //byte[] msg = message.getBytes(); - - SM3Digest digest = new SM3Digest(); - byte[] z = getZ(digest); - - digest.update(z, 0, z.length); - digest.update(message, 0, message.length); - - byte[] eHash = new byte[digest.getDigestSize()]; - - digest.doFinal(eHash, 0); - return eHash; - } - - /** - * generate the signature from the 32 byte hash - */ - public BigInteger[] generateHashSignature(byte[] hash) { - if (hash.length != 32) { - throw new IllegalArgumentException("Expected 32 byte input to " + - "ECDSA signature, not " + hash.length); - } - BigInteger n = ecParams.getN(); - BigInteger e = calculateE(hash); - BigInteger d = ((ECPrivateKeyParameters) ecKey).getD(); - - BigInteger r, s; - - ECMultiplier basePointMultiplier = createBasePointMultiplier(); - - // 5.2.1 Draft RFC: SM2 Public Key Algorithms - do // generate s - { - BigInteger k; - do // generate r - { - // A3 - k = kCalculator.nextK(); - // A4 - ECPoint p = basePointMultiplier.multiply(ecParams.getG(), k).normalize(); - - // A5 - r = e.add(p.getAffineXCoord().toBigInteger()).mod(n); - } - while (r.equals(ZERO) || r.add(k).equals(n)); - - // A6 - BigInteger dPlus1ModN = d.add(ONE).modInverse(n); - - s = k.subtract(r.multiply(d)).mod(n); - s = dPlus1ModN.multiply(s).mod(n); - } - while (s.equals(ZERO)); - - // A7 - return new BigInteger[]{r, s}; - } - - /** - * verify the message signature - */ - public boolean verifySignature(byte[] message, BigInteger r, BigInteger s, - @Nullable String userID) { - BigInteger n = ecParams.getN(); - - // 5.3.1 Draft RFC: SM2 Public Key Algorithms - // B1 - if (r.compareTo(ONE) < 0 || r.compareTo(n) >= 0) { - return false; - } - - // B2 - if (s.compareTo(ONE) < 0 || s.compareTo(n) >= 0) { - return false; - } - - ECPoint q = ((ECPublicKeyParameters) ecKey).getQ(); - - if (userID != null) { - this.userID = userID.getBytes(); - } - byte[] eHash = generateSM3Hash(message); - - // B4 - BigInteger e = calculateE(eHash); - - // B5 - BigInteger t = r.add(s).mod(n); - if (t.equals(ZERO)) { - return false; - } else { - // B6 - ECPoint x1y1 = ecParams.getG().multiply(s); - x1y1 = x1y1.add(q.multiply(t)).normalize(); - - // B7 - return r.equals(e.add(x1y1.getAffineXCoord().toBigInteger()).mod(n)); - } - } - - /** - * verify the hash signature - */ - public boolean verifyHashSignature(byte[] hash, BigInteger r, BigInteger s) { - BigInteger n = ecParams.getN(); - - // 5.3.1 Draft RFC: SM2 Public Key Algorithms - // B1 - if (r.compareTo(ONE) < 0 || r.compareTo(n) >= 0) { - return false; - } - - // B2 - if (s.compareTo(ONE) < 0 || s.compareTo(n) >= 0) { - return false; - } - - ECPoint q = ((ECPublicKeyParameters) ecKey).getQ(); - - // B4 - BigInteger e = calculateE(hash); - - // B5 - BigInteger t = r.add(s).mod(n); - if (t.equals(ZERO)) { - return false; - } else { - // B6 - ECPoint x1y1 = ecParams.getG().multiply(s); - x1y1 = x1y1.add(q.multiply(t)).normalize(); - - // B7 - return r.equals(e.add(x1y1.getAffineXCoord().toBigInteger()).mod(n)); - } - } - - private byte[] getZ(Digest digest) { - - //addUserID(digest, userID); - - addFieldElement(digest, ecParams.getCurve().getA()); - addFieldElement(digest, ecParams.getCurve().getB()); - addFieldElement(digest, ecParams.getG().getAffineXCoord()); - addFieldElement(digest, ecParams.getG().getAffineYCoord()); - addFieldElement(digest, pubPoint.getAffineXCoord()); - addFieldElement(digest, pubPoint.getAffineYCoord()); - - byte[] rv = new byte[digest.getDigestSize()]; - - digest.doFinal(rv, 0); - - return rv; - } - - private void addUserID(Digest digest, byte[] userID) { - int len = userID.length * 8; - digest.update((byte) (len >> 8 & 0xFF)); - digest.update((byte) (len & 0xFF)); - digest.update(userID, 0, userID.length); - } - - private void addFieldElement(Digest digest, ECFieldElement v) { - byte[] p = BigIntegers.asUnsignedByteArray(curveLength, v.toBigInteger()); - digest.update(p, 0, p.length); - } - - protected ECMultiplier createBasePointMultiplier() { - return new FixedPointCombMultiplier(); - } - - protected BigInteger calculateE(byte[] message) { - return new BigInteger(1, message); - } - -} - diff --git a/framework/src/main/java/org/tron/common/backup/message/Message.java b/framework/src/main/java/org/tron/common/backup/message/Message.java index cd1a2669427..8b624637952 100644 --- a/framework/src/main/java/org/tron/common/backup/message/Message.java +++ b/framework/src/main/java/org/tron/common/backup/message/Message.java @@ -49,7 +49,7 @@ public byte[] getSendData() { } public Sha256Hash getMessageId() { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), getData()); + return Sha256Hash.of(getData()); } public abstract Node getFrom(); diff --git a/framework/src/main/java/org/tron/core/Wallet.java b/framework/src/main/java/org/tron/core/Wallet.java index 8c86f2f66ac..49addc3ef9f 100755 --- a/framework/src/main/java/org/tron/core/Wallet.java +++ b/framework/src/main/java/org/tron/core/Wallet.java @@ -302,8 +302,7 @@ public class Wallet { * Creates a new Wallet with a random ECKey. */ public Wallet() { - this.cryptoEngine = SignUtils.getGeneratedRandomSign(Utils.getRandom(), - CommonParameter.getInstance().isECKeyCryptoEngine()); + this.cryptoEngine = SignUtils.getGeneratedRandomSign(Utils.getRandom()); } /** @@ -625,8 +624,7 @@ public TransactionApprovedList getTransactionApprovedList(Transaction trx) { TransactionApprovedList.Builder tswBuilder = TransactionApprovedList.newBuilder(); TransactionExtention.Builder trxExBuilder = TransactionExtention.newBuilder(); trxExBuilder.setTransaction(trx); - trxExBuilder.setTxid(ByteString.copyFrom(Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()))); + trxExBuilder.setTxid(ByteString.copyFrom(Sha256Hash.hash(trx.getRawData().toByteArray()))); Return.Builder retBuilder = Return.newBuilder(); retBuilder.setResult(true).setCode(response_code.SUCCESS); trxExBuilder.setResult(retBuilder); @@ -648,16 +646,14 @@ public TransactionApprovedList getTransactionApprovedList(Transaction trx) { if (trx.getSignatureCount() > 0) { List approveList = new ArrayList(); - byte[] hash = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()); + byte[] hash = Sha256Hash.hash(trx.getRawData().toByteArray()); for (ByteString sig : trx.getSignatureList()) { if (sig.size() < 65) { throw new SignatureFormatException( "Signature size is " + sig.size()); } String base64 = TransactionCapsule.getBase64FromByteString(sig); - byte[] address = SignUtils.signatureToAddress(hash, base64, Args.getInstance() - .isECKeyCryptoEngine()); + byte[] address = SignUtils.signatureToAddress(hash, base64); approveList.add(ByteString.copyFrom(address)); //out put approve list. } tswBuilder.addAllApprovedList(approveList); @@ -780,7 +776,7 @@ public WitnessList getPaginatedNowWitnessList(long offset, long limit) throws if (limit > WITNESS_COUNT_LIMIT_MAX) { limit = WITNESS_COUNT_LIMIT_MAX; } - + /* In the maintenance period, the VoteStores will be cleared. To avoid the race condition of VoteStores deleted but Witness vote counts not updated, @@ -1502,8 +1498,8 @@ public Protocol.ChainParameters getChainParameters() { builder.addChainParameter(Protocol.ChainParameters.ChainParameter.newBuilder() .setKey("getAllowTvmSelfdestructRestriction") .setValue(dbManager.getDynamicPropertiesStore().getAllowTvmSelfdestructRestriction()) - .build()); - + .build()); + builder.addChainParameter(Protocol.ChainParameters.ChainParameter.newBuilder() .setKey("getProposalExpireTime") .setValue(dbManager.getDynamicPropertiesStore().getProposalExpireTime()) @@ -4479,8 +4475,7 @@ public String getCoinbase() { List localWitnessAddresses = new ArrayList<>(); for (String privateKey : localPrivateKeys) { localWitnessAddresses.add(Hex.toHexString(SignUtils - .fromPrivate(ByteArray.fromHexString(privateKey), - CommonParameter.getInstance().isECKeyCryptoEngine()).getAddress())); + .fromPrivate(ByteArray.fromHexString(privateKey)).getAddress())); } // get all witnesses @@ -4510,8 +4505,7 @@ public boolean isMining() { List localWitnessAddresses = new ArrayList<>(); for (String privateKey : localPrivateKeys) { localWitnessAddresses.add(Hex.toHexString(SignUtils - .fromPrivate(ByteArray.fromHexString(privateKey), - CommonParameter.getInstance().isECKeyCryptoEngine()).getAddress())); + .fromPrivate(ByteArray.fromHexString(privateKey)).getAddress())); } // get active witnesses diff --git a/framework/src/main/java/org/tron/core/config/args/Args.java b/framework/src/main/java/org/tron/core/config/args/Args.java index 0e71294d786..7d47f88bd93 100644 --- a/framework/src/main/java/org/tron/core/config/args/Args.java +++ b/framework/src/main/java/org/tron/core/config/args/Args.java @@ -143,9 +143,6 @@ public static void applyConfigParams( Wallet.setAddressPreFixByte(ADD_PRE_FIX_BYTE_MAINNET); Wallet.setAddressPreFixString(Constant.ADD_PRE_FIX_STRING_MAINNET); - PARAMETER.cryptoEngine = config.hasPath(ConfigKey.CRYPTO_ENGINE) ? config - .getString(ConfigKey.CRYPTO_ENGINE) : Constant.ECKey_ENGINE; - if (config.hasPath(ConfigKey.VM_SUPPORT_CONSTANT)) { PARAMETER.supportConstant = config.getBoolean(ConfigKey.VM_SUPPORT_CONSTANT); } diff --git a/framework/src/main/java/org/tron/core/config/args/ConfigKey.java b/framework/src/main/java/org/tron/core/config/args/ConfigKey.java index dbb872febce..b90001739f0 100644 --- a/framework/src/main/java/org/tron/core/config/args/ConfigKey.java +++ b/framework/src/main/java/org/tron/core/config/args/ConfigKey.java @@ -14,9 +14,6 @@ private ConfigKey() { public static final String LOCAL_WITNESS_ACCOUNT_ADDRESS = "localWitnessAccountAddress"; public static final String LOCAL_WITNESS_KEYSTORE = "localwitnesskeystore"; - // crypto - public static final String CRYPTO_ENGINE = "crypto.engine"; - // vm public static final String VM_SUPPORT_CONSTANT = "vm.supportConstant"; public static final String VM_MAX_ENERGY_LIMIT_FOR_CONSTANT = "vm.maxEnergyLimitForConstant"; diff --git a/framework/src/main/java/org/tron/core/config/args/WitnessInitializer.java b/framework/src/main/java/org/tron/core/config/args/WitnessInitializer.java index 30711eb6190..e4ac054a4ec 100644 --- a/framework/src/main/java/org/tron/core/config/args/WitnessInitializer.java +++ b/framework/src/main/java/org/tron/core/config/args/WitnessInitializer.java @@ -36,8 +36,7 @@ public static LocalWitnesses initFromCLIPrivateKey( logger.debug("Got localWitnessAccountAddress from cmd"); } - witnesses.initWitnessAccountAddress( - address, Args.getInstance().isECKeyCryptoEngine()); + witnesses.initWitnessAccountAddress(address); logger.debug("Got privateKey from cmd"); return witnesses; } @@ -52,8 +51,7 @@ public static LocalWitnesses initFromCFGPrivateKey( logger.debug("Got privateKey from config.conf"); byte[] address = resolveWitnessAddress(witnesses, witnessAccountAddress); - witnesses.initWitnessAccountAddress( - address, Args.getInstance().isECKeyCryptoEngine()); + witnesses.initWitnessAccountAddress(address); return witnesses; } @@ -91,8 +89,7 @@ public static LocalWitnesses initFromKeystore( LocalWitnesses witnesses = new LocalWitnesses(); witnesses.setPrivateKeys(privateKeys); byte[] address = resolveWitnessAddress(witnesses, witnessAccountAddress); - witnesses.initWitnessAccountAddress( - address, Args.getInstance().isECKeyCryptoEngine()); + witnesses.initWitnessAccountAddress(address); logger.debug("Got privateKey from keystore"); return witnesses; } diff --git a/framework/src/main/java/org/tron/core/consensus/ConsensusService.java b/framework/src/main/java/org/tron/core/consensus/ConsensusService.java index ef8f30ef498..cd7db5fd133 100644 --- a/framework/src/main/java/org/tron/core/consensus/ConsensusService.java +++ b/framework/src/main/java/org/tron/core/consensus/ConsensusService.java @@ -50,7 +50,7 @@ public void start() { for (String key : privateKeys) { byte[] privateKey = fromHexString(key); byte[] privateKeyAddress = SignUtils - .fromPrivate(privateKey, Args.getInstance().isECKeyCryptoEngine()).getAddress(); + .fromPrivate(privateKey).getAddress(); WitnessCapsule witnessCapsule = witnessStore.get(privateKeyAddress); if (null == witnessCapsule) { logger.warn("Witness {} is not in witnessStore.", Hex.toHexString(privateKeyAddress)); @@ -64,8 +64,7 @@ public void start() { } else if (privateKeys.size() == 1) { byte[] privateKey = fromHexString(Args.getLocalWitnesses().getPrivateKey()); - byte[] privateKeyAddress = SignUtils.fromPrivate(privateKey, - Args.getInstance().isECKeyCryptoEngine()).getAddress(); + byte[] privateKeyAddress = SignUtils.fromPrivate(privateKey).getAddress(); byte[] witnessAddress = Args.getLocalWitnesses().getWitnessAccountAddress(); WitnessCapsule witnessCapsule = witnessStore.get(witnessAddress); if (null == witnessCapsule) { diff --git a/framework/src/main/java/org/tron/core/db/Manager.java b/framework/src/main/java/org/tron/core/db/Manager.java index cd1a61c01fe..08a0d0e2cb7 100644 --- a/framework/src/main/java/org/tron/core/db/Manager.java +++ b/framework/src/main/java/org/tron/core/db/Manager.java @@ -2529,8 +2529,7 @@ public TransactionInfoList getTransactionInfoByBlockNum(long blockNum) { List listTransaction = block.getTransactionsList(); for (Transaction transaction : listTransaction) { TransactionInfoCapsule transactionInfoCapsule = getTransactionHistoryStore() - .get(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); + .get(Sha256Hash.hash(transaction.getRawData().toByteArray())); if (transactionInfoCapsule != null) { transactionInfoList.addTransactionInfo(transactionInfoCapsule.getInstance()); diff --git a/framework/src/main/java/org/tron/core/net/messagehandler/PbftDataSyncHandler.java b/framework/src/main/java/org/tron/core/net/messagehandler/PbftDataSyncHandler.java index d66fa6d41f7..d7cbeacc796 100644 --- a/framework/src/main/java/org/tron/core/net/messagehandler/PbftDataSyncHandler.java +++ b/framework/src/main/java/org/tron/core/net/messagehandler/PbftDataSyncHandler.java @@ -130,7 +130,7 @@ private boolean validPbftSign(Raw raw, List srSignList, Param.getInstance().getAgreeNodeCount()); return false; } - byte[] dataHash = Sha256Hash.hash(true, raw.toByteArray()); + byte[] dataHash = Sha256Hash.hash(raw.toByteArray()); Set srSet = Sets.newHashSet(currentSrList); List> futureList = new ArrayList<>(); for (ByteString sign : srSignList) { diff --git a/framework/src/main/java/org/tron/core/net/service/relay/RelayService.java b/framework/src/main/java/org/tron/core/net/service/relay/RelayService.java index 61ae6326e9f..ff6b85fe5c7 100644 --- a/framework/src/main/java/org/tron/core/net/service/relay/RelayService.java +++ b/framework/src/main/java/org/tron/core/net/service/relay/RelayService.java @@ -109,12 +109,10 @@ public void fillHelloMessage(HelloMessage message, Channel channel) { fastForwardNodes.forEach(address -> { if (address.getAddress().equals(channel.getInetAddress())) { SignInterface cryptoEngine = SignUtils - .fromPrivate(ByteArray.fromHexString(Args.getLocalWitnesses().getPrivateKey()), - Args.getInstance().isECKeyCryptoEngine()); + .fromPrivate(ByteArray.fromHexString(Args.getLocalWitnesses().getPrivateKey())); ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine - .signHash(Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), ByteArray.fromLong(message + .signHash(Sha256Hash.of(ByteArray.fromLong(message .getTimestamp())).getBytes()))); message.setHelloMessage(message.getHelloMessage().toBuilder() .setAddress(witnessAddress).setSignature(sig).build()); @@ -152,12 +150,10 @@ public boolean checkHelloMessage(HelloMessage message, Channel channel) { boolean flag; try { - Sha256Hash hash = Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), ByteArray.fromLong(msg.getTimestamp())); + Sha256Hash hash = Sha256Hash.of(ByteArray.fromLong(msg.getTimestamp())); String sig = TransactionCapsule.getBase64FromByteString(msg.getSignature()); - byte[] sigAddress = SignUtils.signatureToAddress(hash.getBytes(), sig, - Args.getInstance().isECKeyCryptoEngine()); + byte[] sigAddress = SignUtils.signatureToAddress(hash.getBytes(), sig); if (manager.getDynamicPropertiesStore().getAllowMultiSign() != 1) { flag = Arrays.equals(sigAddress, msg.getAddress().toByteArray()); } else { diff --git a/framework/src/main/java/org/tron/core/services/RpcApiService.java b/framework/src/main/java/org/tron/core/services/RpcApiService.java index 63e7ba03fc7..3fe52054f59 100755 --- a/framework/src/main/java/org/tron/core/services/RpcApiService.java +++ b/framework/src/main/java/org/tron/core/services/RpcApiService.java @@ -262,8 +262,7 @@ private TransactionExtention transaction2Extention(Transaction transaction) { TransactionExtention.Builder trxExtBuilder = TransactionExtention.newBuilder(); Return.Builder retBuilder = Return.newBuilder(); trxExtBuilder.setTransaction(transaction); - trxExtBuilder.setTxid(Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getByteString()); + trxExtBuilder.setTxid(Sha256Hash.of(transaction.getRawData().toByteArray()).getByteString()); retBuilder.setResult(true).setCode(response_code.SUCCESS); trxExtBuilder.setResult(retBuilder); return trxExtBuilder.build(); diff --git a/framework/src/main/java/org/tron/core/services/http/Util.java b/framework/src/main/java/org/tron/core/services/http/Util.java index 2b6b929d8a0..ddfffc49bae 100644 --- a/framework/src/main/java/org/tron/core/services/http/Util.java +++ b/framework/src/main/java/org/tron/core/services/http/Util.java @@ -202,7 +202,7 @@ public static String printTransactionApprovedList(TransactionApprovedList transa public static byte[] generateContractAddress(Transaction trx, byte[] ownerAddress) { // get tx hash byte[] txRawDataHash = Sha256Hash - .of(CommonParameter.getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()) + .of(trx.getRawData().toByteArray()) .getBytes(); // combine @@ -261,8 +261,7 @@ public static JSONObject printTransactionToJSON(Transaction transaction, boolean String rawDataHex = ByteArray.toHexString(transaction.getRawData().toByteArray()); jsonTransaction.put("raw_data_hex", rawDataHex); String txID = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(transaction.getRawData().toByteArray())); jsonTransaction.put("txID", txID); return jsonTransaction; } diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java index 315d70df8d6..489946cf6db 100755 --- a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java @@ -85,8 +85,7 @@ private TransactionExtention transaction2Extention(Transaction transaction) { TransactionExtention.Builder trxExtBuilder = TransactionExtention.newBuilder(); Return.Builder retBuilder = Return.newBuilder(); trxExtBuilder.setTransaction(transaction); - trxExtBuilder.setTxid(Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()).getByteString()); + trxExtBuilder.setTxid(Sha256Hash.of(transaction.getRawData().toByteArray()).getByteString()); retBuilder.setResult(true).setCode(response_code.SUCCESS); trxExtBuilder.setResult(retBuilder); return trxExtBuilder.build(); diff --git a/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java b/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java index 4a60f14b534..3a6d6bad3e1 100644 --- a/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java +++ b/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java @@ -104,7 +104,7 @@ public static TriggerSmartContract triggerCallContract(byte[] address, byte[] co public static String getBlockID(Block block) { long blockNum = block.getBlockHeader().getRawData().getNumber(); - byte[] blockHash = Sha256Hash.of(true, block.getBlockHeader().getRawData().toByteArray()) + byte[] blockHash = Sha256Hash.of(block.getBlockHeader().getRawData().toByteArray()) .getByteString().toByteArray(); byte[] numBytes = Longs.toByteArray(blockNum); byte[] hash = new byte[blockHash.length]; @@ -206,7 +206,7 @@ public static List getTo(Transaction transaction) { } public static String getTxID(Transaction transaction) { - return ByteArray.toHexString(Sha256Hash.hash(true, transaction.getRawData().toByteArray())); + return ByteArray.toHexString(Sha256Hash.hash(transaction.getRawData().toByteArray())); } public static long getTransactionAmount(Transaction.Contract contract, String hash, @@ -456,9 +456,7 @@ public static long parseQuantityValue(String value) throws JsonRpcInvalidParamsE public static long getEnergyUsageTotal(Transaction transaction, Wallet wallet) { long energyUsageTotal = 0; - byte[] txHash = Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()); + byte[] txHash = Sha256Hash.hash(transaction.getRawData().toByteArray()); TransactionInfo transactionInfo = wallet .getTransactionInfoById(ByteString.copyFrom(txHash)); if (transactionInfo != null) { diff --git a/framework/src/main/java/org/tron/core/services/jsonrpc/types/BlockResult.java b/framework/src/main/java/org/tron/core/services/jsonrpc/types/BlockResult.java index f5f8fb7fdef..b5101acc195 100644 --- a/framework/src/main/java/org/tron/core/services/jsonrpc/types/BlockResult.java +++ b/framework/src/main/java/org/tron/core/services/jsonrpc/types/BlockResult.java @@ -142,8 +142,7 @@ public BlockResult(Block block, boolean fullTx, Wallet wallet) { gasUsedInBlock += getEnergyUsageTotal(transactionInfoList, i, blockCapsule.getNum()); byte[] txHash = Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transactionsList.get(i).getRawData().toByteArray()); + .hash(transactionsList.get(i).getRawData().toByteArray()); txes.add(ByteArray.toJsonHex(txHash)); } } diff --git a/framework/src/main/java/org/tron/core/zen/ShieldedTRC20ParametersBuilder.java b/framework/src/main/java/org/tron/core/zen/ShieldedTRC20ParametersBuilder.java index 95e4eeb0ccd..9b39a726ea7 100644 --- a/framework/src/main/java/org/tron/core/zen/ShieldedTRC20ParametersBuilder.java +++ b/framework/src/main/java/org/tron/core/zen/ShieldedTRC20ParametersBuilder.java @@ -309,7 +309,7 @@ public ShieldedTRC20Parameters build(boolean withAsk) throws ZksnarkException { throw new ZksnarkException("unknown parameters type"); } - dataHashToBeSigned = Sha256Hash.of(true, mergedBytes).getBytes(); + dataHashToBeSigned = Sha256Hash.of(mergedBytes).getBytes(); if (dataHashToBeSigned == null) { throw new ZksnarkException("calculate transaction hash failed"); } diff --git a/framework/src/main/java/org/tron/keystore/Credentials.java b/framework/src/main/java/org/tron/keystore/Credentials.java index 1c44b21a80c..be6e6ce48c6 100644 --- a/framework/src/main/java/org/tron/keystore/Credentials.java +++ b/framework/src/main/java/org/tron/keystore/Credentials.java @@ -2,7 +2,6 @@ import java.util.Objects; import org.tron.common.crypto.SignInterface; -import org.tron.common.crypto.sm2.SM2; import org.tron.common.utils.StringUtil; /** @@ -23,11 +22,6 @@ public static Credentials create(SignInterface cryptoEngine) { return new Credentials(cryptoEngine, address); } - public static Credentials create(SM2 sm2Pair) { - String address = StringUtil.encode58Check(sm2Pair.getAddress()); - return new Credentials(sm2Pair, address); - } - public SignInterface getSignInterface() { return cryptoEngine; } diff --git a/framework/src/main/java/org/tron/keystore/Wallet.java b/framework/src/main/java/org/tron/keystore/Wallet.java index d38b1c74984..47f18374842 100644 --- a/framework/src/main/java/org/tron/keystore/Wallet.java +++ b/framework/src/main/java/org/tron/keystore/Wallet.java @@ -212,7 +212,7 @@ public static SignInterface decrypt(String password, WalletFile walletFile) byte[] encryptKey = Arrays.copyOfRange(derivedKey, 0, 16); byte[] privateKey = performCipherOperation(Cipher.DECRYPT_MODE, iv, encryptKey, cipherText); - return SignUtils.fromPrivate(privateKey, Args.getInstance().isECKeyCryptoEngine()); + return SignUtils.fromPrivate(privateKey); } static void validate(WalletFile walletFile) throws CipherException { diff --git a/framework/src/main/java/org/tron/keystore/WalletUtils.java b/framework/src/main/java/org/tron/keystore/WalletUtils.java index 8bcc68cbab0..867a6091379 100644 --- a/framework/src/main/java/org/tron/keystore/WalletUtils.java +++ b/framework/src/main/java/org/tron/keystore/WalletUtils.java @@ -48,11 +48,9 @@ public static String generateLightNewWalletFile(String password, File destinatio public static String generateNewWalletFile( String password, File destinationDirectory, boolean useFullScrypt) - throws CipherException, IOException, InvalidAlgorithmParameterException, - NoSuchAlgorithmException, NoSuchProviderException { + throws CipherException, IOException { - SignInterface ecKeyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), - Args.getInstance().isECKeyCryptoEngine()); + SignInterface ecKeyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); return generateWalletFile(password, ecKeyPair, destinationDirectory, useFullScrypt); } diff --git a/framework/src/main/java/org/tron/program/KeystoreFactory.java b/framework/src/main/java/org/tron/program/KeystoreFactory.java index 8199d7e9076..e9535b4a73a 100755 --- a/framework/src/main/java/org/tron/program/KeystoreFactory.java +++ b/framework/src/main/java/org/tron/program/KeystoreFactory.java @@ -59,8 +59,7 @@ private void fileCheck(File file) throws IOException { private void genKeystore() throws CipherException, IOException { String password = WalletUtils.inputPassword2Twice(); - SignInterface eCkey = SignUtils.getGeneratedRandomSign(Utils.random, - CommonParameter.getInstance().isECKeyCryptoEngine()); + SignInterface eCkey = SignUtils.getGeneratedRandomSign(Utils.random); File file = new File(FilePath); fileCheck(file); String fileName = WalletUtils.generateWalletFile(password, eCkey, file, true); @@ -84,8 +83,7 @@ private void importPrivateKey() throws CipherException, IOException { String password = WalletUtils.inputPassword2Twice(); - SignInterface eCkey = SignUtils.fromPrivate(ByteArray.fromHexString(privateKey), - CommonParameter.getInstance().isECKeyCryptoEngine()); + SignInterface eCkey = SignUtils.fromPrivate(ByteArray.fromHexString(privateKey)); File file = new File(FilePath); fileCheck(file); String fileName = WalletUtils.generateWalletFile(password, eCkey, file, true); diff --git a/framework/src/main/resources/config.conf b/framework/src/main/resources/config.conf index 661a592e431..00d5f72729c 100644 --- a/framework/src/main/resources/config.conf +++ b/framework/src/main/resources/config.conf @@ -126,11 +126,6 @@ node.backup { ] } -# Specify the algorithm for generating a public key from private key. To avoid forks, please do not modify it -crypto { - engine = "eckey" -} - node.metrics = { # prometheus metrics prometheus { diff --git a/framework/src/test/java/org/tron/common/BaseTest.java b/framework/src/test/java/org/tron/common/BaseTest.java index dd4400e10f2..34daa068e3f 100644 --- a/framework/src/test/java/org/tron/common/BaseTest.java +++ b/framework/src/test/java/org/tron/common/BaseTest.java @@ -102,8 +102,7 @@ public Protocol.Block getSignedBlock(ByteString witness, long time, byte[] priva ECKey ecKey = ECKey.fromPrivate(privateKey); assert ecKey != null; - ECKey.ECDSASignature signature = ecKey.sign(Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), raw.toByteArray()).getBytes()); + ECKey.ECDSASignature signature = ecKey.sign(Sha256Hash.of(raw.toByteArray()).getBytes()); ByteString sign = ByteString.copyFrom(signature.toByteArray()); Protocol.BlockHeader blockHeader = block.getBlockHeader().toBuilder() diff --git a/framework/src/test/java/org/tron/common/ParameterTest.java b/framework/src/test/java/org/tron/common/ParameterTest.java index d5dbced87fe..f129742016d 100644 --- a/framework/src/test/java/org/tron/common/ParameterTest.java +++ b/framework/src/test/java/org/tron/common/ParameterTest.java @@ -229,8 +229,6 @@ public void testCommonParameter() { assertNull(parameter.getOverlay()); assertNull(parameter.getEventPluginConfig()); assertNull(parameter.getEventFilter()); - parameter.setCryptoEngine(ECKey_ENGINE); - assertEquals(ECKey_ENGINE, parameter.getCryptoEngine()); parameter.setFullNodeHttpEnable(false); assertFalse(parameter.isFullNodeHttpEnable()); parameter.setSolidityNodeHttpEnable(false); diff --git a/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java b/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java index ab6b2832c12..f361117f712 100644 --- a/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java +++ b/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java @@ -7,11 +7,9 @@ import java.math.BigInteger; import java.security.SignatureException; import java.util.Arrays; -import org.bouncycastle.crypto.digests.SM3Digest; import org.bouncycastle.util.encoders.Hex; import org.junit.Assert; import org.junit.Test; -import org.tron.common.crypto.sm2.SM2; import org.tron.common.utils.Sha256Hash; /** @@ -40,11 +38,8 @@ public void testHex() { public void testSha256Hash() { String msg = "transaction raw data"; String spongySha256 = "da36dc042630f1aa810171d1fc4db7771a9f12b585848b0fed6caf5c7bd06531"; - String spongySm3 = "5521fbff5abf495e6db8fb4a83ed2bf27b97197757fc5a1002a7edc58b690900"; - byte[] sha256Hash = Sha256Hash.hash(true, msg.getBytes()); + byte[] sha256Hash = Sha256Hash.hash(msg.getBytes()); assertEquals(spongySha256, Hex.toHexString(sha256Hash)); - byte[] sm3Hash = Sha256Hash.hash(false, msg.getBytes()); - assertEquals(spongySm3, Hex.toHexString(sm3Hash)); } @Test @@ -70,12 +65,12 @@ public void testECKeyAddress() { @Test public void testECKeySignature() throws SignatureException { - SignInterface sign = SignUtils.fromPrivate(Hex.decode(privString), true); + SignInterface sign = SignUtils.fromPrivate(Hex.decode(privString)); String msg = "transaction raw data"; String spongyAddress = "2e988a386a799f506693793c6a5af6b54dfaabfb"; - byte[] hash = Sha256Hash.hash(true, msg.getBytes()); + byte[] hash = Sha256Hash.hash(msg.getBytes()); String sig = sign.signHash(hash); - byte[] address = SignUtils.signatureToAddress(hash, sig, true); + byte[] address = SignUtils.signatureToAddress(hash, sig); assertEquals(spongyAddress, Hex.toHexString(Arrays.copyOfRange(address, 1, 21))); } @@ -85,52 +80,8 @@ public void testECSpongySignature() throws SignatureException { String spongySig = "GwYii3BGoQq3sdyWiGVv7bGCR5hJy62g+IF+1jPOSqHt" + "IDfuKgowhiiK7ivcqk+T7qq/hlfIjaRe+t1drFDZ+Mo="; String spongyAddress = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826"; - byte[] hash = Sha256Hash.hash(true, msg.getBytes()); - byte[] address = SignUtils.signatureToAddress(hash, spongySig, true); - assertEquals(spongyAddress, Hex.toHexString(Arrays.copyOfRange(address, 1, 21))); - } - - @Test - public void testSM3Hash() { - String msg = "transaction raw data"; - String spongyHash = "5521fbff5abf495e6db8fb4a83ed2bf27b97197757fc5a1002a7edc58b690900"; - SM3Digest digest = new SM3Digest(); - digest.update(msg.getBytes(), 0, msg.getBytes().length); - byte[] hash = new byte[digest.getDigestSize()]; - digest.doFinal(hash, 0); - assertEquals(spongyHash, Hex.toHexString(hash)); - } - - @Test - public void testSM2Address() { - String spongyPublickey = "04dc3547dbbc4c90a9cde599848e26cb145e805b3d11daaf9daae0680d9c6824058ac" - + "35ddecb12f3a8bbc3104a2b91a2b7d04851d773d9b4ab8d5e0359243c8628"; - String spongyAddress = "6cb22f88564bdd61eb4cdb36215add53bc702ff1"; - SM2 key = SM2.fromPrivate(privateKey); - assertEquals(spongyPublickey, Hex.toHexString(key.getPubKey())); - byte[] address = key.getAddress(); - assertEquals(spongyAddress, Hex.toHexString(Arrays.copyOfRange(address, 1, 21))); - } - - @Test - public void testSM2Signature() throws SignatureException { - SignInterface sign = SignUtils.fromPrivate(Hex.decode(privString), false); - String msg = "transaction raw data"; - String spongyAddress = "6cb22f88564bdd61eb4cdb36215add53bc702ff1"; - byte[] hash = Sha256Hash.hash(false, msg.getBytes()); - String sig = sign.signHash(hash); - byte[] address = SignUtils.signatureToAddress(hash, sig, false); - assertEquals(spongyAddress, Hex.toHexString(Arrays.copyOfRange(address, 1, 21))); - } - - @Test - public void testSM2SpongySignature() throws SignatureException { - String msg = "transaction raw data"; - String spongySig = "HOoyvBLOJ+dKReQdAc6W/ffRi/KmVntco0+xgzmFItEExq/fHF" - + "veCe0GoCJUBdyHyUFjwn+a18ibtGJcHxnvLj0="; - String spongyAddress = "7dc44d739a5226c0d3037bb7919f653eb2f938b9"; - byte[] hash = Sha256Hash.hash(false, msg.getBytes()); - byte[] address = SignUtils.signatureToAddress(hash, spongySig, false); + byte[] hash = Sha256Hash.hash(msg.getBytes()); + byte[] address = SignUtils.signatureToAddress(hash, spongySig); assertEquals(spongyAddress, Hex.toHexString(Arrays.copyOfRange(address, 1, 21))); } @@ -140,12 +91,7 @@ public void testSignToAddress() { String base64Sign = "G1y76mVO6TRpFwp3qOiLVzHA8uFsrDiOL7hbC2uN9qTHHiLypaW4vnQkfkoUygjo5qBd" + "+NlYQ/mAPVWKu6K00co="; try { - SignUtils.signatureToAddress(Hex.decode(messageHash), base64Sign, Boolean.TRUE); - } catch (Exception e) { - Assert.assertTrue(e instanceof SignatureException); - } - try { - SignUtils.signatureToAddress(Hex.decode(messageHash), base64Sign, Boolean.FALSE); + SignUtils.signatureToAddress(Hex.decode(messageHash), base64Sign); } catch (Exception e) { Assert.assertTrue(e instanceof SignatureException); } diff --git a/framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java b/framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java deleted file mode 100644 index 87e4e14698c..00000000000 --- a/framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java +++ /dev/null @@ -1,284 +0,0 @@ -package org.tron.common.crypto; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.tron.common.utils.client.utils.AbiUtil.generateOccupationConstantPrivateKey; - -import java.math.BigInteger; -import java.security.KeyPairGenerator; -import java.security.SignatureException; -import java.util.Arrays; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.crypto.digests.SM3Digest; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; -import org.tron.common.crypto.sm2.SM2; -import org.tron.common.crypto.sm2.SM2Signer; -import org.tron.core.Wallet; - -/** - * The reason the test case uses the private key plaintext is to ensure that, - * after the ECkey tool or algorithm is upgraded, - * the upgraded differences can be verified. - */ -@Slf4j -public class SM2KeyTest { - - //private String IDa = "ALICE123@YAHOO.COM"; - private static BigInteger SM2_N = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6" - + "B21C6052B53BBF40939D54123", 16); - // For safety reasons, test with a placeholder private key - private String privString = generateOccupationConstantPrivateKey(); - private BigInteger privateKey = new BigInteger(privString, 16); - private String pubString = "04dc3547dbbc4c90a9cde599848e26cb145e805b3d11daaf9daae0680d9c6824058ac" - + "35ddecb12f3a8bbc3104a2b91a2b7d04851d773d9b4ab8d5e0359243c8628"; - private String compressedPubString = - "02dc3547dbbc4c90a9cde599848e26cb145e805b3d11daaf9daae0680d9c682405"; - private byte[] pubKey = Hex.decode(pubString); - private byte[] compressedPubKey = Hex.decode(compressedPubString); - private String address = "6cb22f88564bdd61eb4cdb36215add53bc702ff1"; - - @Test - public void testHashCode() { - assertEquals(578690511, SM2.fromPrivate(privateKey).hashCode()); - } - - @Test - public void testSM2() { - SM2 key = new SM2(); - assertTrue(key.isPubKeyCanonical()); - assertNotNull(key.getPubKey()); - assertNotNull(key.getPrivKeyBytes()); - logger.info(Hex.toHexString(key.getPrivKeyBytes()) + " :Generated privkey"); - logger.info(Hex.toHexString(key.getPubKey()) + " :Generated pubkey"); - logger.info("private key in bigInteger form: " + key.getPrivKey()); - } - - @Test - public void testFromPrivateKey() { - SM2 key = SM2.fromPrivate(privateKey); - assertTrue(key.isPubKeyCanonical()); - assertTrue(key.hasPrivKey()); - assertArrayEquals(pubKey, key.getPubKey()); - - key = SM2.fromPrivate((byte[]) null); - assertNull(key); - key = SM2.fromPrivate(new byte[0]); - assertNull(key); - } - - @Test(expected = IllegalArgumentException.class) - public void testPrivatePublicKeyBytesNoArg() { - new SM2((BigInteger) null, null); - fail("Expecting an IllegalArgumentException for using only null-parameters"); - } - - @Test(expected = IllegalArgumentException.class) - public void testInvalidPrivateKey() throws Exception { - new SM2( - KeyPairGenerator.getInstance("RSA").generateKeyPair().getPrivate(), - SM2.fromPublicOnly(pubKey).getPubKeyPoint()); - fail("Expecting an IllegalArgumentException for using an non EC private key"); - } - - @Test - public void testIsPubKeyOnly() { - SM2 key = SM2.fromPublicOnly(pubKey); - assertTrue(key.isPubKeyCanonical()); - assertTrue(key.isPubKeyOnly()); - assertArrayEquals(key.getPubKey(), pubKey); - } - - @Test(expected = IllegalArgumentException.class) - public void testSignIncorrectInputSize() { - SM2 key = new SM2(); - String message = "The quick brown fox jumps over the lazy dog."; - SM2.SM2Signature sig = key.sign(message.getBytes()); - fail("Expecting an IllegalArgumentException for a non 32-byte input"); - } - - @Test(expected = SignatureException.class) - public void testBadBase64Sig() throws SignatureException { - byte[] messageHash = new byte[32]; - SM2.signatureToKey(messageHash, "This is not valid Base64!"); - fail("Expecting a SignatureException for invalid Base64"); - } - - @Test(expected = SignatureException.class) - public void testInvalidSignatureLength() throws SignatureException { - byte[] messageHash = new byte[32]; - SM2.signatureToKey(messageHash, "abcdefg"); - fail("Expecting a SignatureException for invalid signature length"); - } - - @Test - public void testSM3Hash() { - SM2 key = SM2.fromPublicOnly(pubKey); - SM2Signer signer = key.getSM2SignerForHash(); - String message = "message digest"; - byte[] hash = signer.generateSM3Hash(message.getBytes()); - assertEquals("2A723761EAE35429DF643648FD69FB7787E7FC32F321BFAF7E294390F529BAF4", - Hex.toHexString(hash).toUpperCase()); - } - - - @Test - public void testSignatureToKeyBytes() throws SignatureException { - SM2 key = SM2.fromPrivate(privateKey); - byte[] hash = Hex.decode("B524F552CD82B8B028476E005C377FB" - + "19A87E6FC682D48BB5D42E3D9B9EFFE76"); - SM2.SM2Signature sign = key.sign(hash); - byte[] pubKeys = SM2.signatureToKeyBytes(hash, sign); - assertEquals(Hex.toHexString(pubKey), Hex.toHexString(pubKeys)); - } - - @Test - public void testSignatureToKeyBytes2() throws SignatureException { - SM2 key = SM2.fromPrivate(privateKey); - byte[] hash = Hex.decode("B524F552CD82B8B028476E005C377FB" - + "19A87E6FC682D48BB5D42E3D9B9EFFE76"); - SM2.SM2Signature sign = key.sign(hash); - byte[] pubKeys = SM2.signatureToKeyBytes(hash, sign); - assertArrayEquals(pubKeys, key.getPubKey()); - } - - @Test - public void testSignatureToAddress() throws SignatureException { - SM2 key = SM2.fromPrivate(privateKey); - byte[] hash = Hex.decode("B524F552CD82B8B028476E005C377FB" - + "19A87E6FC682D48BB5D42E3D9B9EFFE76"); - SM2.SM2Signature sign = key.sign(hash); - byte[] addr = SM2.signatureToAddress(hash, sign); - addr = Arrays.copyOfRange(addr, 1, addr.length); - assertEquals(address, Hex.toHexString(addr)); - } - - @Test - public void testPublicKeyFromPrivate() { - byte[] pubFromPriv = SM2.publicKeyFromPrivate(privateKey, false); - assertArrayEquals(pubKey, pubFromPriv); - } - - @Test - public void testPublicKeyFromPrivateCompressed() { - byte[] pubFromPriv = SM2.publicKeyFromPrivate(privateKey, true); - assertArrayEquals(compressedPubKey, pubFromPriv); - } - - @Test - public void testGetAddress() { - SM2 key = SM2.fromPublicOnly(pubKey); - byte[] prefixedAddress = key.getAddress(); - byte[] unprefixedAddress = Arrays.copyOfRange(key.getAddress(), 1, prefixedAddress.length); - assertArrayEquals(Hex.decode(address), unprefixedAddress); - assertEquals(Wallet.getAddressPreFixByte(), prefixedAddress[0]); - } - - @Test - public void testGetAddressFromPrivateKey() { - SM2 key = SM2.fromPrivate(privateKey); - byte[] prefixedAddress = key.getAddress(); - byte[] unprefixedAddress = Arrays.copyOfRange(key.getAddress(), 1, prefixedAddress.length); - assertArrayEquals(Hex.decode(address), unprefixedAddress); - assertEquals(Wallet.getAddressPreFixByte(), prefixedAddress[0]); - } - - @Test - public void testToString() { - SM2 key = SM2.fromPrivate(BigInteger.TEN); // An example private key. - assertEquals("pub:04d3f94862519621c121666061f65c3e32b2d0d065" - + "cd219e3284a04814db5227564b9030cf676f6a742ebd57d146dca" - + "428f6b743f64d1482d147d46fb2bab82a14", key.toString()); - } - - @Test - public void testIsPubKeyCanonicalCorrect() { - // Test correct prefix 4, right length 65 - byte[] canonicalPubkey1 = new byte[65]; - canonicalPubkey1[0] = 0x04; - assertTrue(SM2.isPubKeyCanonical(canonicalPubkey1)); - // Test correct prefix 2, right length 33 - byte[] canonicalPubkey2 = new byte[33]; - canonicalPubkey2[0] = 0x02; - assertTrue(SM2.isPubKeyCanonical(canonicalPubkey2)); - // Test correct prefix 3, right length 33 - byte[] canonicalPubkey3 = new byte[33]; - canonicalPubkey3[0] = 0x03; - assertTrue(SM2.isPubKeyCanonical(canonicalPubkey3)); - } - - @Test - public void testIsPubKeyCanonicalWrongLength() { - // Test correct prefix 4, but wrong length !65 - byte[] nonCanonicalPubkey1 = new byte[64]; - nonCanonicalPubkey1[0] = 0x04; - assertFalse(SM2.isPubKeyCanonical(nonCanonicalPubkey1)); - // Test correct prefix 2, but wrong length !33 - byte[] nonCanonicalPubkey2 = new byte[32]; - nonCanonicalPubkey2[0] = 0x02; - assertFalse(SM2.isPubKeyCanonical(nonCanonicalPubkey2)); - // Test correct prefix 3, but wrong length !33 - byte[] nonCanonicalPubkey3 = new byte[32]; - nonCanonicalPubkey3[0] = 0x03; - assertFalse(SM2.isPubKeyCanonical(nonCanonicalPubkey3)); - } - - @Test - public void testIsPubKeyCanonicalWrongPrefix() { - // Test wrong prefix 4, right length 65 - byte[] nonCanonicalPubkey4 = new byte[65]; - assertFalse(SM2.isPubKeyCanonical(nonCanonicalPubkey4)); - // Test wrong prefix 2, right length 33 - byte[] nonCanonicalPubkey5 = new byte[33]; - assertFalse(SM2.isPubKeyCanonical(nonCanonicalPubkey5)); - // Test wrong prefix 3, right length 33 - byte[] nonCanonicalPubkey6 = new byte[33]; - assertFalse(SM2.isPubKeyCanonical(nonCanonicalPubkey6)); - } - - @Test - public void testGetPrivKeyBytes() { - SM2 key = new SM2(); - assertNotNull(key.getPrivKeyBytes()); - assertEquals(32, key.getPrivKeyBytes().length); - } - - @Test - public void testEqualsObject() { - SM2 key0 = new SM2(); - SM2 key1 = SM2.fromPrivate(privateKey); - SM2 key2 = SM2.fromPrivate(privateKey); - - assertFalse(key0.equals(key1)); - assertTrue(key1.equals(key1)); - assertTrue(key1.equals(key2)); - } - - @Test - public void testNodeId() { - SM2 key = SM2.fromPublicOnly(pubKey); - - assertEquals(key, SM2.fromNodeId(key.getNodeId())); - } - - @Test - public void testSM3() { - String message = "F4A38489E32B45B6F876E3AC2168CA392362DC8F23459C1D1146F" - + "C3DBFB7BC9A6D65737361676520646967657374"; - SM3Digest digest = new SM3Digest(); - byte[] msg = Hex.decode(message); - digest.update(msg, 0, msg.length); - - byte[] eHash = new byte[digest.getDigestSize()]; - - digest.doFinal(eHash, 0); - - assertEquals("b524f552cd82b8b028476e005c377fb19a87e6fc682d48bb5d42e3d9b9effe76", - Hex.toHexString(eHash)); - } -} diff --git a/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java b/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java index b413127db53..c8128f3059e 100644 --- a/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java +++ b/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java @@ -7,20 +7,12 @@ import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; import org.junit.Test; -import org.tron.common.crypto.sm2.SM2; import org.tron.common.utils.PublicMethod; @Slf4j public class SignatureInterfaceTest { - private String SM2_privString = PublicMethod.getSM2RandomPrivateKey(); - private byte[] SM2_privateKey = Hex.decode(SM2_privString); - - private String SM2_pubString = PublicMethod.getSM2PublicByPrivateKey(SM2_privString); - private byte[] SM2_pubKey = Hex.decode(SM2_pubString); - private String SM2_address = PublicMethod.getSM2AddressByPrivateKey(SM2_privString); - private String EC_privString = PublicMethod.getRandomPrivateKey(); private byte[] EC_privateKey = Hex.decode(EC_privString); @@ -28,57 +20,36 @@ public class SignatureInterfaceTest { private byte[] EC_pubKey = Hex.decode(EC_pubString); private String EC_address = PublicMethod.getHexAddressByPrivateKey(EC_privString); - - @Test public void testContructor() { - SignInterface sign = new SM2(); - logger.info(Hex.toHexString(sign.getPrivateKey()) + " :SM2 Generated privkey"); - logger.info(Hex.toHexString(sign.getPubKey()) + " :SM2 Generated pubkey"); - - sign = new ECKey(); + SignInterface sign = new ECKey(); logger.info(Hex.toHexString(sign.getPrivateKey()) + " :ECDSA Generated privkey"); logger.info(Hex.toHexString(sign.getPubKey()) + " :ECDSA Generated pubkey"); } @Test public void testPirvateKey() { - SignInterface sign = new SM2(SM2_privateKey, true); - assertArrayEquals(sign.getPubKey(), SM2_pubKey); - - sign = new ECKey(EC_privateKey, true); + SignInterface sign = new ECKey(EC_privateKey, true); assertArrayEquals(sign.getPubKey(), EC_pubKey); - } @Test public void testPublicKey() { - SignInterface sign = new SM2(SM2_pubKey, false); - assertArrayEquals(sign.getPubKey(), SM2_pubKey); - - sign = new ECKey(EC_pubKey, false); + SignInterface sign = new ECKey(EC_pubKey, false); assertArrayEquals(sign.getPubKey(), EC_pubKey); } @Test public void testNullKey() { - SignInterface sign = new SM2(SM2_pubKey, false); - assertEquals(null, sign.getPrivateKey()); - - sign = new ECKey(EC_pubKey, false); + SignInterface sign = new ECKey(EC_pubKey, false); assertEquals(null, sign.getPrivateKey()); } @Test public void testAddress() { - SignInterface sign = new SM2(SM2_pubKey, false); + SignInterface sign = new ECKey(EC_pubKey, false); byte[] prefix_address = sign.getAddress(); byte[] address = Arrays.copyOfRange(prefix_address, 1, prefix_address.length); - byte[] addressTmp = Arrays.copyOfRange(Hex.decode(SM2_address), 1, prefix_address.length); - assertEquals(Hex.toHexString(addressTmp), Hex.toHexString(address)); - sign = new ECKey(EC_pubKey, false); - prefix_address = sign.getAddress(); - address = Arrays.copyOfRange(prefix_address, 1, prefix_address.length); byte[] ecAddressTmp = Arrays.copyOfRange(Hex.decode(EC_address), 1, prefix_address.length); assertEquals(Hex.toHexString(ecAddressTmp), Hex.toHexString(address)); } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java b/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java index 518d42041ee..403965a390d 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java @@ -103,14 +103,12 @@ public void testDifferentCase() { byte[] address = key.getAddress(); int permissionId = 2; - byte[] data = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), longData); + byte[] data = Sha256Hash.hash(longData); //combine data byte[] merged = ByteUtil.merge(address, ByteArray.fromInt(permissionId), data); //sha256 of it - byte[] toSign = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), merged); + byte[] toSign = Sha256Hash.hash(merged); //sign data diff --git a/framework/src/test/java/org/tron/common/utils/PublicMethod.java b/framework/src/test/java/org/tron/common/utils/PublicMethod.java index 63feab160d4..5fb77986ece 100644 --- a/framework/src/test/java/org/tron/common/utils/PublicMethod.java +++ b/framework/src/test/java/org/tron/common/utils/PublicMethod.java @@ -17,8 +17,6 @@ import org.tron.api.GrpcAPI; import org.tron.api.WalletGrpc; import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.sm2.SM2; -import org.tron.common.crypto.sm2.SM2Signer; import org.tron.common.utils.client.utils.TransactionUtils; import org.tron.core.Wallet; import org.tron.protos.Protocol; @@ -55,37 +53,6 @@ public static byte[] getPublicKeyFromPrivate(String privateKey) { return ECKey.publicKeyFromPrivate(tmpKey, true); } - public static String getSM2RandomPrivateKey() { - SM2 key = new SM2(Utils.getRandom()); - return Hex.toHexString( - Objects.requireNonNull(key.getPrivKeyBytes())); - } - - public static SM2 getSM2byPrivate(String privateKey) { - BigInteger priK = new BigInteger(privateKey, 16); - return SM2.fromPrivate(priK); - } - - public static String getSM2PublicByPrivateKey(String privateKey) { - return Hex.toHexString(getSM2byPrivate(privateKey).getPubKey()); - } - - public static String getSM2AddressByPrivateKey(String privateKey) { - return ByteArray - .toHexString(getSM2byPrivate(privateKey).getAddress()); - } - - public static byte[] getSM2PublicKeyFromPrivate(String privateKey) { - BigInteger tmpKey = new BigInteger(privateKey, 16); - return SM2.publicKeyFromPrivate(tmpKey, true); - } - - public static byte[] getSM2HashByPubKey(byte[] pubKey, String message) { - SM2 key = SM2.fromPublicOnly(pubKey); - SM2Signer signer = key.getSM2SignerForHash(); - return signer.generateSM3Hash(message.getBytes()); - } - /** constructor. */ public static SmartContractOuterClass.SmartContract.ABI jsonStr2Abi(String jsonStr) { if (jsonStr == null) { diff --git a/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java b/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java index 0df72cc125d..e8e03a42db6 100644 --- a/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java +++ b/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java @@ -5,18 +5,14 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import ch.qos.logback.core.util.FileUtil; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.nio.file.Files; import java.util.Arrays; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.IntStream; -import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Test; -import org.tron.common.parameter.CommonParameter; public class Sha256HashTest { @@ -24,10 +20,8 @@ public class Sha256HashTest { public void testHash() throws IOException { //Example from https://github.com/tronprotocol/tips/blob/master/TWP-001.md byte[] input = ByteArray.fromHexString("A0E11973395042BA3C0B52B4CDF4E15EA77818F275"); - byte[] hash0 = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), input); - byte[] hash1 = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), hash0); + byte[] hash0 = Sha256Hash.hash(input); + byte[] hash1 = Sha256Hash.hash(hash0); assertEquals(Arrays.toString(hash0), Arrays.toString(ByteArray .fromHexString("CD5D4A7E8BE869C00E17F8F7712F41DBE2DDBD4D8EC36A7280CD578863717084"))); assertEquals(Arrays.toString(hash1), Arrays.toString(ByteArray @@ -36,22 +30,16 @@ public void testHash() throws IOException { Sha256Hash sha256Hash = new Sha256Hash(1, new byte[32]); assertNotNull(sha256Hash.toBigInteger()); - Sha256Hash.create(true, ("byte1-1").getBytes(StandardCharsets.UTF_8)); + Sha256Hash.create(("byte1-1").getBytes(StandardCharsets.UTF_8)); File testfile = createTempFile("testfile", ".txt").toFile(); - Sha256Hash.of(true, testfile); - Sha256Hash.createDouble(true, new byte[0]); - Sha256Hash.twiceOf(true, new byte[0]); - Sha256Hash.hashTwice(true, new byte[0]); - Sha256Hash.hashTwice(false, new byte[0]); - Sha256Hash.hashTwice(true, new byte[0], 0, 0); - Sha256Hash.hashTwice(false, new byte[0], 0, 0); - Sha256Hash.hash(false, new byte[0], 0, 0); - Sha256Hash.hashTwice(true, new byte[0], 0, 0, new byte[0], 0, 0); - Sha256Hash.hashTwice(false, new byte[0], 0, 0, new byte[0], 0, 0); + Sha256Hash.of(testfile); + Sha256Hash.createDouble(new byte[0]); + Sha256Hash.twiceOf(new byte[0]); + Sha256Hash.hashTwice(new byte[0]); + Sha256Hash.hashTwice(new byte[0], 0, 0); + Sha256Hash.hash(new byte[0], 0, 0); + Sha256Hash.hashTwice(new byte[0], 0, 0, new byte[0], 0, 0); assertTrue(testfile.delete()); - - - } @Test @@ -65,8 +53,7 @@ public void testMultiThreadingHash() { Thread thread = new Thread(() -> { for (int i = 0; i < 10000; i++) { - byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), input); + byte[] hash0 = Sha256Hash.hash(input); countAll.incrementAndGet(); if (!Arrays.equals(hash, hash0)) { countFailed.incrementAndGet(); @@ -84,4 +71,4 @@ public void testMultiThreadingHash() { assertEquals(70000, countAll.get()); assertEquals(0, countFailed.get()); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/common/utils/client/WalletClient.java b/framework/src/test/java/org/tron/common/utils/client/WalletClient.java index 9d9a68da49d..b1816eff657 100644 --- a/framework/src/test/java/org/tron/common/utils/client/WalletClient.java +++ b/framework/src/test/java/org/tron/common/utils/client/WalletClient.java @@ -474,10 +474,8 @@ public static byte[] getPassWord(String password) { return null; } byte[] pwd; - pwd = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), password.getBytes()); - pwd = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), pwd); + pwd = Sha256Hash.hash(password.getBytes()); + pwd = Sha256Hash.hash(pwd); pwd = Arrays.copyOfRange(pwd, 0, 16); return pwd; } @@ -491,8 +489,7 @@ public static byte[] getEncKey(String password) { return null; } byte[] encKey; - encKey = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), password.getBytes()); + encKey = Sha256Hash.hash(password.getBytes()); encKey = Arrays.copyOfRange(encKey, 0, 16); return encKey; } @@ -558,10 +555,8 @@ public static boolean addressValid(byte[] address) { */ public static String encode58Check(byte[] input) { - byte[] hash0 = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), input); - byte[] hash1 = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), hash0); + byte[] hash0 = Sha256Hash.hash(input); + byte[] hash1 = Sha256Hash.hash(hash0); byte[] inputCheck = new byte[input.length + 4]; System.arraycopy(input, 0, inputCheck, 0, input.length); System.arraycopy(hash1, 0, inputCheck, input.length, 4); @@ -575,10 +570,8 @@ private static byte[] decode58Check(String input) { } byte[] decodeData = new byte[decodeCheck.length - 4]; System.arraycopy(decodeCheck, 0, decodeData, 0, decodeData.length); - byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), decodeData); - byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), hash0); + byte[] hash0 = Sha256Hash.hash(decodeData); + byte[] hash1 = Sha256Hash.hash(hash0); if (hash1[0] == decodeCheck[decodeData.length] && hash1[1] == decodeCheck[decodeData.length + 1] && hash1[2] == decodeCheck[decodeData.length + 2] diff --git a/framework/src/test/java/org/tron/common/utils/client/utils/Base58.java b/framework/src/test/java/org/tron/common/utils/client/utils/Base58.java index 2106b191af9..74fe54c5731 100644 --- a/framework/src/test/java/org/tron/common/utils/client/utils/Base58.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/Base58.java @@ -212,10 +212,8 @@ public static boolean addressValid(byte[] address) { */ public static String encode58Check(byte[] input) { - byte[] hash0 = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), input); - byte[] hash1 = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), hash0); + byte[] hash0 = Sha256Hash.hash(input); + byte[] hash1 = Sha256Hash.hash(hash0); byte[] inputCheck = new byte[input.length + 4]; System.arraycopy(input, 0, inputCheck, 0, input.length); System.arraycopy(hash1, 0, inputCheck, input.length, 4); @@ -229,8 +227,8 @@ public static byte[] decode58CheckForShield(String input) { } byte[] decodeData = new byte[decodeCheck.length - 4]; System.arraycopy(decodeCheck, 0, decodeData, 0, decodeData.length); - byte[] hash0 = Sha256Sm3Hash.hash(decodeData); - byte[] hash1 = Sha256Sm3Hash.hash(hash0); + byte[] hash0 = Sha256Hash.hash(decodeData); + byte[] hash1 = Sha256Hash.hash(hash0); if (hash1[0] == decodeCheck[decodeData.length] && hash1[1] == decodeCheck[decodeData.length + 1] && hash1[2] == decodeCheck[decodeData.length + 2] diff --git a/framework/src/test/java/org/tron/common/utils/client/utils/Sha256Sm3Hash.java b/framework/src/test/java/org/tron/common/utils/client/utils/Sha256Sm3Hash.java deleted file mode 100644 index fde88385794..00000000000 --- a/framework/src/test/java/org/tron/common/utils/client/utils/Sha256Sm3Hash.java +++ /dev/null @@ -1,342 +0,0 @@ -package org.tron.common.utils.client.utils; - -/* - * Copyright 2011 Google Inc. - * Copyright 2014 Andreas Schildbach - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import com.google.common.base.Preconditions; -import com.google.common.io.ByteStreams; -import com.google.common.primitives.Ints; -import com.google.common.primitives.Longs; -import com.google.protobuf.ByteString; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.Serializable; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; - -import org.bouncycastle.crypto.digests.SM3Digest; -import org.tron.common.utils.ByteArray; - - -/** - * A Sha256Sm3Hash just wraps a byte[] so that equals and hashcode work correctly, allowing it to be - * used as keys in a map. It also checks that the length is correct and provides a bit more type - * safety. - */ -public class Sha256Sm3Hash implements Serializable, Comparable { - - public static final int LENGTH = 32; // bytes - public static final Sha256Sm3Hash ZERO_HASH = wrap(new byte[LENGTH]); - - private final byte[] bytes; - private static boolean isEckey = true; - - /* static { - Config config = Configuration.getByPath("config.conf"); // it is needs set to be a constant - Config config = "crypto.engine"; - if (config.hasPath("crypto.engine")) { - isEckey = config.getString("crypto.engine").equalsIgnoreCase("eckey"); - System.out.println("Sha256Sm3Hash getConfig isEckey: " + isEckey); - } - }*/ - - public Sha256Sm3Hash(long num, byte[] hash) { - byte[] rawHashBytes = this.generateBlockId(num, hash); - Preconditions.checkArgument(rawHashBytes.length == LENGTH); - this.bytes = rawHashBytes; - } - - public Sha256Sm3Hash(long num, Sha256Sm3Hash hash) { - byte[] rawHashBytes = this.generateBlockId(num, hash); - Preconditions.checkArgument(rawHashBytes.length == LENGTH); - this.bytes = rawHashBytes; - } - - /** - * Use {@link #wrap(byte[])} instead. - */ - @Deprecated - public Sha256Sm3Hash(byte[] rawHashBytes) { - Preconditions.checkArgument(rawHashBytes.length == LENGTH); - this.bytes = rawHashBytes; - } - - /** - * Creates a new instance that wraps the given hash value. - * - * @param rawHashBytes the raw hash bytes to wrap - * @return a new instance - * @throws IllegalArgumentException if the given array length is not exactly 32 - */ - @SuppressWarnings("deprecation") // the constructor will be made private in the future - public static Sha256Sm3Hash wrap(byte[] rawHashBytes) { - return new Sha256Sm3Hash(rawHashBytes); - } - - public static Sha256Sm3Hash wrap(ByteString rawHashByteString) { - return wrap(rawHashByteString.toByteArray()); - } - - /** - * Use {@link #of(byte[])} instead: this old name is ambiguous. - */ - @Deprecated - public static Sha256Sm3Hash create(byte[] contents) { - return of(contents); - } - - /** - * Creates a new instance containing the calculated (one-time) hash of the given bytes. - * - * @param contents the bytes on which the hash value is calculated - * @return a new instance containing the calculated (one-time) hash - */ - public static Sha256Sm3Hash of(byte[] contents) { - return wrap(hash(contents)); - } - - /** - * Creates a new instance containing the calculated (one-time) hash of the given file's contents. - * The file contents are read fully into memory, so this method should only be used with small - * files. - * - * @param file the file on which the hash value is calculated - * @return a new instance containing the calculated (one-time) hash - * @throws IOException if an error occurs while reading the file - */ - public static Sha256Sm3Hash of(File file) throws IOException { - - try (FileInputStream in = new FileInputStream(file)) { - return of(ByteStreams.toByteArray(in)); - } - } - - /** - * Use {@link #twiceOf(byte[])} instead: this old name is ambiguous. - */ - @Deprecated - public static Sha256Sm3Hash createDouble(byte[] contents) { - return twiceOf(contents); - } - - /** - * Creates a new instance containing the hash of the calculated hash of the given bytes. - * - * @param contents the bytes on which the hash value is calculated - * @return a new instance containing the calculated (two-time) hash - */ - public static Sha256Sm3Hash twiceOf(byte[] contents) { - return wrap(hashTwice(contents)); - } - - /** - * Returns a new SHA-256 MessageDigest instance. This is a convenience method which wraps the - * checked exception that can never occur with a RuntimeException. - * - * @return a new SHA-256 MessageDigest instance - */ - public static MessageDigest newDigest() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); // Can't happen. - } - } - - /** - * Returns a new SM3 MessageDigest instance. This is a convenience method which wraps the checked - * exception that can never occur with a RuntimeException. - * - * @return a new SM3 MessageDigest instance - */ - public static SM3Digest newSM3Digest() { - return new SM3Digest(); - } - - /** - * Calculates the SHA-256 hash of the given bytes. - * - * @param input the bytes to hash - * @return the hash (in big-endian order) - */ - public static byte[] hash(byte[] input) { - return hash(input, 0, input.length); - } - - /** - * Calculates the SHA-256 hash of the given byte range. - * - * @param input the array containing the bytes to hash - * @param offset the offset within the array of the bytes to hash - * @param length the number of bytes to hash - * @return the hash (in big-endian order) - */ - public static byte[] hash(byte[] input, int offset, int length) { - if (isEckey) { - MessageDigest digest = newDigest(); - digest.update(input, offset, length); - return digest.digest(); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input, offset, length); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - return eHash; - } - - } - - /** - * Calculates the SHA-256 hash of the given bytes, and then hashes the resulting hash again. - * - * @param input the bytes to hash - * @return the double-hash (in big-endian order) - */ - public static byte[] hashTwice(byte[] input) { - return hashTwice(input, 0, input.length); - } - - /** - * Calculates the SHA-256 hash of the given byte range, and then hashes the resulting hash again. - * - * @param input the array containing the bytes to hash - * @param offset the offset within the array of the bytes to hash - * @param length the number of bytes to hash - * @return the double-hash (in big-endian order) - */ - public static byte[] hashTwice(byte[] input, int offset, int length) { - if (isEckey) { - MessageDigest digest = newDigest(); - digest.update(input, offset, length); - return digest.digest(digest.digest()); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input, offset, length); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - digest.reset(); - digest.update(eHash, 0, eHash.length); - digest.doFinal(eHash, 0); - return eHash; - } - - } - - /** - * Calculates the hash of hash on the given byte ranges. This is equivalent to concatenating the - * two ranges and then passing the result to {@link #hashTwice(byte[])}. - */ - public static byte[] hashTwice(byte[] input1, int offset1, int length1, - byte[] input2, int offset2, int length2) { - if (isEckey) { - MessageDigest digest = newDigest(); - digest.update(input1, offset1, length1); - digest.update(input2, offset2, length2); - return digest.digest(digest.digest()); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input1, offset1, length1); - digest.update(input2, offset2, length2); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - return eHash; - } - } - - private byte[] generateBlockId(long blockNum, Sha256Sm3Hash blockHash) { - byte[] numBytes = Longs.toByteArray(blockNum); - byte[] hash = new byte[blockHash.getBytes().length]; - System.arraycopy(numBytes, 0, hash, 0, 8); - System.arraycopy(blockHash.getBytes(), 8, hash, 8, blockHash.getBytes().length - 8); - return hash; - } - - private byte[] generateBlockId(long blockNum, byte[] blockHash) { - byte[] numBytes = Longs.toByteArray(blockNum); - byte[] hash = new byte[blockHash.length]; - System.arraycopy(numBytes, 0, hash, 0, 8); - System.arraycopy(blockHash, 8, hash, 8, blockHash.length - 8); - return hash; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || !(o instanceof Sha256Sm3Hash)) { - return false; - } - return Arrays.equals(bytes, ((Sha256Sm3Hash) o).bytes); - } - - @Override - public String toString() { - return ByteArray.toHexString(bytes); - } - - /** - * Returns the last four bytes of the wrapped hash. This should be unique enough to be a suitable - * hash code even for blocks, where the goal is to try and get the first bytes to be zeros (i.e. - * the value as a big integer lower than the target value). - */ - @Override - public int hashCode() { - // Use the last 4 bytes, not the first 4 which are often zeros in Bitcoin. - return Ints - .fromBytes(bytes[LENGTH - 4], bytes[LENGTH - 3], bytes[LENGTH - 2], bytes[LENGTH - 1]); - } - - /** - * Returns the bytes interpreted as a positive integer. - */ - public BigInteger toBigInteger() { - return new BigInteger(1, bytes); - } - - /** - * Returns the internal byte array, without defensively copying. Therefore do NOT modify the - * returned array. - */ - public byte[] getBytes() { - return bytes; - } - - /** - * For pb return ByteString. - */ - public ByteString getByteString() { - return ByteString.copyFrom(bytes); - } - - @Override - public int compareTo(final Sha256Sm3Hash other) { - for (int i = LENGTH - 1; i >= 0; i--) { - final int thisByte = this.bytes[i] & 0xff; - final int otherByte = other.bytes[i] & 0xff; - if (thisByte > otherByte) { - return 1; - } - if (thisByte < otherByte) { - return -1; - } - } - return 0; - } -} diff --git a/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java b/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java index 63ffe1b58ff..3c1fc89cd55 100644 --- a/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java @@ -56,8 +56,7 @@ public class TransactionUtils { public static byte[] getHash(Transaction transaction) { Transaction.Builder tmp = transaction.toBuilder(); //tmp.clearId(); - return Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), tmp.build().toByteArray()); + return Sha256Hash.hash(tmp.build().toByteArray()); } /** @@ -133,8 +132,7 @@ public static boolean validTransaction(Transaction signedTransaction) { assert (signedTransaction.getSignatureCount() == signedTransaction.getRawData().getContractCount()); List listContract = signedTransaction.getRawData().getContractList(); - byte[] hash = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), signedTransaction.getRawData().toByteArray()); + byte[] hash = Sha256Hash.hash(signedTransaction.getRawData().toByteArray()); int count = signedTransaction.getSignatureCount(); if (count == 0) { return false; @@ -163,8 +161,7 @@ public static boolean validTransaction(Transaction signedTransaction) { public static Transaction sign(Transaction transaction, ECKey myKey) { Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); - byte[] hash = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), transaction.getRawData().toByteArray()); + byte[] hash = Sha256Hash.hash(transaction.getRawData().toByteArray()); List listContract = transaction.getRawData().getContractList(); for (int i = 0; i < listContract.size(); i++) { ECDSASignature signature = myKey.sign(hash); diff --git a/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java b/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java index 61790849b43..5ac8c69b1f1 100644 --- a/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java +++ b/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java @@ -128,7 +128,7 @@ public void testHasWitnessSignature() { localWitnesses = new LocalWitnesses(); localWitnesses.setPrivateKeys(Arrays.asList(privateKey)); - localWitnesses.initWitnessAccountAddress(null, true); + localWitnesses.initWitnessAccountAddress(null); Args.setLocalWitnesses(localWitnesses); Assert.assertFalse(blockCapsule0.hasWitnessSignature()); diff --git a/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java b/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java index df84433726e..4214ea011eb 100644 --- a/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java +++ b/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java @@ -34,15 +34,13 @@ private static List getHash(int hashNum) { bytes[2] = (byte) ((i >> 8) & 0xFF); bytes[1] = (byte) ((i >> 16) & 0xFF); bytes[0] = (byte) ((i >> 24) & 0xFF); - hashList.add(Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), bytes)); + hashList.add(Sha256Hash.of(bytes)); } return hashList; } private static Sha256Hash computeHash(Sha256Hash leftHash, Sha256Hash rightHash) { - return Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), + return Sha256Hash.of( leftHash.getByteString().concat(rightHash.getByteString()).toByteArray()); } @@ -195,10 +193,10 @@ public void testConcurrent() { Sha256Hash root2 = Sha256Hash.wrap( ByteString.fromHex("4bfc60ea3de4f5d1476f839874df0aba38eec4e524d6fa63f5b19c4bf527eaf3")); List list1 = IntStream.range(0, 10000).mapToObj(i -> - Sha256Hash.of(true, ("byte1-" + i).getBytes(StandardCharsets.UTF_8))) + Sha256Hash.of(("byte1-" + i).getBytes(StandardCharsets.UTF_8))) .collect(Collectors.toList()); List list2 = IntStream.range(0, 10000).mapToObj(i -> - Sha256Hash.of(true, ("byte2-" + i).getBytes(StandardCharsets.UTF_8))) + Sha256Hash.of(("byte2-" + i).getBytes(StandardCharsets.UTF_8))) .collect(Collectors.toList()); Assert.assertEquals(root1, MerkleTree.getInstance().createTree(list1).getRoot().getHash()); Assert.assertEquals(root2, MerkleTree.getInstance().createTree(list2).getRoot().getHash()); diff --git a/framework/src/test/java/org/tron/core/config/args/ArgsTest.java b/framework/src/test/java/org/tron/core/config/args/ArgsTest.java index a4ce9a5030e..1fa4bf87767 100644 --- a/framework/src/test/java/org/tron/core/config/args/ArgsTest.java +++ b/framework/src/test/java/org/tron/core/config/args/ArgsTest.java @@ -67,7 +67,7 @@ public void get() { localWitnesses = new LocalWitnesses(); localWitnesses.setPrivateKeys(Arrays.asList(privateKey)); - localWitnesses.initWitnessAccountAddress(null, true); + localWitnesses.initWitnessAccountAddress(null); Args.setLocalWitnesses(localWitnesses); address = ByteArray.toHexString(Args.getLocalWitnesses() .getWitnessAccountAddress()); diff --git a/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java b/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java index 83a65926446..94b8cd8dd1b 100644 --- a/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java +++ b/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java @@ -162,13 +162,13 @@ public void testConstructor() { LocalWitnesses localWitnesses = new LocalWitnesses(PublicMethod.getRandomPrivateKey()); LocalWitnesses localWitnesses1 = new LocalWitnesses(Lists.newArrayList(PublicMethod.getRandomPrivateKey())); - localWitnesses.initWitnessAccountAddress(new byte[0], true); + localWitnesses.initWitnessAccountAddress(new byte[0]); Assert.assertNotNull(localWitnesses1.getPublicKey()); LocalWitnesses localWitnesses2 = new LocalWitnesses(); Assert.assertNull(localWitnesses2.getPrivateKey()); Assert.assertNull(localWitnesses2.getPublicKey()); - localWitnesses2.initWitnessAccountAddress(null, true); + localWitnesses2.initWitnessAccountAddress(null); LocalWitnesses localWitnesses3 = new LocalWitnesses(); Assert.assertNull(localWitnesses3.getWitnessAccountAddress()); } diff --git a/framework/src/test/java/org/tron/core/db/BlockGenerate.java b/framework/src/test/java/org/tron/core/db/BlockGenerate.java index 197dd562485..2a8a101865e 100644 --- a/framework/src/test/java/org/tron/core/db/BlockGenerate.java +++ b/framework/src/test/java/org/tron/core/db/BlockGenerate.java @@ -50,8 +50,7 @@ public Block getSignedBlock(ByteString witness, long time, byte[] privateKey) { .build(); ECKey ecKey = ECKey.fromPrivate(privateKey); - ECDSASignature signature = ecKey.sign(Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), raw.toByteArray()).getBytes()); + ECDSASignature signature = ecKey.sign(Sha256Hash.of(raw.toByteArray()).getBytes()); ByteString sign = ByteString.copyFrom(signature.toByteArray()); BlockHeader blockHeader = block.getBlockHeader().toBuilder() diff --git a/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java b/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java index ba7478cb22d..bd4a71beb73 100644 --- a/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java +++ b/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java @@ -132,26 +132,14 @@ public void testGetBranch() { khaosDatabase.push(block1OnforkB); // case: block num of param1 > block num of param2 Pair result1 = khaosDatabase.getBranch( - Sha256Hash.of( - CommonParameter - .getInstance().isECKeyCryptoEngine(), - block2OnforkA.getInstance().getBlockHeader().getRawData().toByteArray()), - Sha256Hash.of( - CommonParameter - .getInstance().isECKeyCryptoEngine(), - block1OnforkB.getInstance().getBlockHeader().getRawData().toByteArray())); + Sha256Hash.of(block2OnforkA.getInstance().getBlockHeader().getRawData().toByteArray()), + Sha256Hash.of(block1OnforkB.getInstance().getBlockHeader().getRawData().toByteArray())); Assert.assertEquals(forkA, result1.getKey()); Assert.assertEquals(forkB, result1.getValue()); // case: block num of param2 > block num of param1 Pair result2 = khaosDatabase.getBranch( - Sha256Hash.of( - CommonParameter - .getInstance().isECKeyCryptoEngine(), - block1OnforkB.getInstance().getBlockHeader().getRawData().toByteArray()), - Sha256Hash.of( - CommonParameter - .getInstance().isECKeyCryptoEngine(), - block2OnforkA.getInstance().getBlockHeader().getRawData().toByteArray())); + Sha256Hash.of(block1OnforkB.getInstance().getBlockHeader().getRawData().toByteArray()), + Sha256Hash.of(block2OnforkA.getInstance().getBlockHeader().getRawData().toByteArray())); Assert.assertEquals(forkB, result2.getKey()); Assert.assertEquals(forkA, result2.getValue()); } catch (UnLinkedBlockException | BadNumberBlockException | NonCommonBlockException e) { @@ -168,4 +156,4 @@ public void testIsNotEmpty() { khaosDatabase.start(blockCapsule); khaosDatabase.isNotEmpty(); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/core/db/ManagerTest.java b/framework/src/test/java/org/tron/core/db/ManagerTest.java index eb6f7f2de81..2efcff89d33 100755 --- a/framework/src/test/java/org/tron/core/db/ManagerTest.java +++ b/framework/src/test/java/org/tron/core/db/ManagerTest.java @@ -141,7 +141,7 @@ public void init() throws IOException { localWitnesses = new LocalWitnesses(); localWitnesses.setPrivateKeys(Arrays.asList(privateKey)); - localWitnesses.initWitnessAccountAddress(null, true); + localWitnesses.initWitnessAccountAddress(null); Args.setLocalWitnesses(localWitnesses); blockCapsule2 = diff --git a/framework/src/test/java/org/tron/core/db/TransactionExpireTest.java b/framework/src/test/java/org/tron/core/db/TransactionExpireTest.java index 8e1b295a4ca..0c2b1dd661a 100644 --- a/framework/src/test/java/org/tron/core/db/TransactionExpireTest.java +++ b/framework/src/test/java/org/tron/core/db/TransactionExpireTest.java @@ -57,7 +57,7 @@ private void initLocalWitness() { String randomPrivateKey = PublicMethod.getRandomPrivateKey(); LocalWitnesses localWitnesses = new LocalWitnesses(); localWitnesses.setPrivateKeys(Arrays.asList(randomPrivateKey)); - localWitnesses.initWitnessAccountAddress(null, true); + localWitnesses.initWitnessAccountAddress(null); Args.setLocalWitnesses(localWitnesses); } diff --git a/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java b/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java index 2a4a76a2614..a0b9863448d 100644 --- a/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java +++ b/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java @@ -87,7 +87,7 @@ public void testCheckpointV2() { while (iterator.hasNext()) { Map.Entry entry = iterator.next(); byte[] hashBytes = Bytes.concat(entry.getKey(), entry.getValue()); - preDbHash = Sha256Hash.of(true, Bytes.concat(preDbHash.getBytes(), hashBytes)); + preDbHash = Sha256Hash.of(Bytes.concat(preDbHash.getBytes(), hashBytes)); } revokingDatabase.check(); @@ -98,7 +98,7 @@ public void testCheckpointV2() { while (iterator2.hasNext()) { Map.Entry entry = iterator2.next(); byte[] hashBytes = Bytes.concat(entry.getKey(), entry.getValue()); - afterDbHash = Sha256Hash.of(true, Bytes.concat(afterDbHash.getBytes(), hashBytes)); + afterDbHash = Sha256Hash.of(Bytes.concat(afterDbHash.getBytes(), hashBytes)); } Assert.assertEquals(0, preDbHash.compareTo(afterDbHash)); diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/PbftMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/PbftMsgHandlerTest.java index 65a8f615bfe..11c504814d7 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/PbftMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/PbftMsgHandlerTest.java @@ -92,10 +92,9 @@ public void testPbft() throws Exception { .setData(blockCapsule.getBlockId().getByteString()); Protocol.PBFTMessage.Raw raw = rawBuilder.build(); builder.setRawData(raw); - SignInterface sign = SignUtils.fromPrivate(Hex.decode(PublicMethod.getRandomPrivateKey()), - true); + SignInterface sign = SignUtils.fromPrivate(Hex.decode(PublicMethod.getRandomPrivateKey())); builder.setSignature(ByteString.copyFrom(sign.Base64toBytes(sign.signHash( - Sha256Hash.hash(true, raw.toByteArray()))))); + Sha256Hash.hash(raw.toByteArray()))))); Protocol.PBFTMessage message = builder.build(); pbftMessage.setType(MessageTypes.PBFT_MSG.asByte()); pbftMessage.setPbftMessage(message); diff --git a/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java b/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java index 6f34288939f..f796e0faa4e 100644 --- a/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java +++ b/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java @@ -178,14 +178,11 @@ private void testCheckHelloMessage() { Node node = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(), null, a1.getPort()); - SignInterface cryptoEngine = SignUtils.fromPrivate(ByteArray.fromHexString(key), - Args.getInstance().isECKeyCryptoEngine()); + SignInterface cryptoEngine = SignUtils.fromPrivate(ByteArray.fromHexString(key)); HelloMessage helloMessage = new HelloMessage(node, System.currentTimeMillis(), ChainBaseManager.getChainBaseManager()); ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine - .signHash(Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), ByteArray.fromLong(helloMessage - .getTimestamp())).getBytes()))); + .signHash(Sha256Hash.of(ByteArray.fromLong(helloMessage.getTimestamp())).getBytes()))); helloMessage.setHelloMessage(helloMessage.getHelloMessage().toBuilder() .setAddress(address) .setSignature(sig) diff --git a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java index f40ec48e035..ebcd69ffbbe 100644 --- a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java +++ b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java @@ -735,8 +735,7 @@ private static BlockIdentifier getBlockIdentifier() { Block nowBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); raw rawData = nowBlock.getBlockHeader().getRawData(); BlockCapsule.BlockId blockId = - new BlockCapsule.BlockId(Sha256Hash.of(getInstance().isECKeyCryptoEngine(), - rawData.toByteArray()), + new BlockCapsule.BlockId(Sha256Hash.of(rawData.toByteArray()), rawData.getNumber()); return BlockIdentifier.newBuilder() .setNumber(rawData.getNumber()) diff --git a/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java b/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java index ed52e014a7b..3a738c72e93 100644 --- a/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java @@ -197,8 +197,7 @@ private void initMerkleTreeWitnessInfo() throws ZksnarkException { Transaction transaction2 = createTransaction(cm3, cm4); Block block = Block.newBuilder().addTransactions(0, transaction) .addTransactions(1, transaction2).build(); - Sha256Hash blockKey = Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), ByteArray.fromLong(blockNum)); + Sha256Hash blockKey = Sha256Hash.of(ByteArray.fromLong(blockNum)); BlockId blockId = new BlockId(blockKey, blockNum); dbManager.getBlockStore().put(blockId.getBytes(), new BlockCapsule(block)); dbManager.getBlockIndexStore().put(blockId); @@ -237,8 +236,7 @@ private void initMerkleTreeWitnessInfo() throws ZksnarkException { String cm2 = "2e0bfc1e123edcb6252251611650f3667371f781b60302385c414716c75e8abc"; Transaction transaction = createTransaction(cm1, cm2); Block block = Block.newBuilder().addTransactions(0, transaction).build(); - Sha256Hash blockKey = Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), ByteArray.fromLong(blockNum)); + Sha256Hash blockKey = Sha256Hash.of(ByteArray.fromLong(blockNum)); BlockId blockId = new BlockId(blockKey, blockNum); dbManager.getBlockStore().put(blockId.getBytes(), new BlockCapsule(block)); dbManager.getBlockIndexStore().put(blockId); @@ -267,8 +265,7 @@ private void initMerkleTreeWitnessInfo() throws ZksnarkException { Transaction transaction2 = createTransaction(cm3, cm4); Block block = Block.newBuilder().addTransactions(0, transaction) .addTransactions(1, transaction2).build(); - Sha256Hash blockKey = Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), ByteArray.fromLong(blockNum)); + Sha256Hash blockKey = Sha256Hash.of(ByteArray.fromLong(blockNum)); BlockId blockId = new BlockId(blockKey, blockNum); dbManager.getBlockStore().put(blockId.getBytes(), new BlockCapsule(block)); dbManager.getBlockIndexStore().put(blockId); @@ -308,8 +305,7 @@ private void initMerkleTreeWitnessInfo() throws ZksnarkException { String cm2 = "26e8c4061f2ad984d19f2c0a4436b9800e529069c0b0d3186d4683e83bb7eb8c"; Transaction transaction = createTransaction(cm1, cm2); Block block = Block.newBuilder().addTransactions(0, transaction).build(); - Sha256Hash blockKey = Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), ByteArray.fromLong(blockNum)); + Sha256Hash blockKey = Sha256Hash.of(ByteArray.fromLong(blockNum)); BlockId blockId = new BlockId(blockKey, blockNum); dbManager.getBlockStore().put(blockId.getBytes(), new BlockCapsule(block)); dbManager.getBlockIndexStore().put(blockId); diff --git a/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java b/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java index e7dfa06d094..1dc3599becf 100644 --- a/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java @@ -629,8 +629,7 @@ public void pushShieldedTransactionAndDecryptWithOvk() } private byte[] getHash() { - return Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), "this is a test".getBytes()).getBytes(); + return Sha256Hash.of("this is a test".getBytes()).getBytes(); } @Ignore diff --git a/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java b/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java index 118e0e1f384..51580b12b01 100755 --- a/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java @@ -1617,12 +1617,9 @@ private byte[] hashWithMissingColumn(TransactionCapsule tx, TestSignMissingColum byte[] mergedByte = Bytes.concat( Sha256Hash.of( - CommonParameter - .getInstance().isECKeyCryptoEngine(), CommonParameter.getInstance().getZenTokenId().getBytes()).getBytes(), transaction.getRawData().toByteArray()); - return Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), mergedByte).getBytes(); + return Sha256Hash.of(mergedByte).getBytes(); } private ZenTransactionBuilder generateShield2ShieldBuilder(ZenTransactionBuilder builder, diff --git a/framework/src/test/java/org/tron/keystore/CredentialsTest.java b/framework/src/test/java/org/tron/keystore/CredentialsTest.java index 3fe2ce02b63..7b723a7eabb 100644 --- a/framework/src/test/java/org/tron/keystore/CredentialsTest.java +++ b/framework/src/test/java/org/tron/keystore/CredentialsTest.java @@ -7,8 +7,6 @@ import org.junit.Test; import org.springframework.util.Assert; import org.tron.common.crypto.SignUtils; -import org.tron.common.crypto.sm2.SM2; -import org.tron.common.utils.ByteUtil; @Slf4j public class CredentialsTest extends TestCase { @@ -16,29 +14,18 @@ public class CredentialsTest extends TestCase { @Test public void testCreate() throws NoSuchAlgorithmException { Credentials credentials = Credentials.create(SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"),true)); + SecureRandom.getInstance("NativePRNG"))); Assert.hasText(credentials.getAddress(),"Credentials address create failed!"); Assert.notNull(credentials.getSignInterface(), "Credentials cryptoEngine create failed"); } - @Test - public void testCreateFromSM2() { - try { - Credentials.create(SM2.fromNodeId(ByteUtil.hexToBytes("fffffffffff" - + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - + "fffffffffffffffffffffffffffffffffffffff"))); - } catch (Exception e) { - Assert.isInstanceOf(IllegalArgumentException.class, e); - } - } - @Test public void testEquals() throws NoSuchAlgorithmException { Credentials credentials1 = Credentials.create(SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"),true)); + SecureRandom.getInstance("NativePRNG"))); Credentials credentials2 = Credentials.create(SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"),true)); + SecureRandom.getInstance("NativePRNG"))); Assert.isTrue(!credentials1.equals(credentials2), "Credentials instance should be not equal!"); Assert.isTrue(!(credentials1.hashCode() == credentials2.hashCode()), diff --git a/framework/src/test/java/org/tron/keystore/WalletFileTest.java b/framework/src/test/java/org/tron/keystore/WalletFileTest.java index c24647be322..272a29e6838 100644 --- a/framework/src/test/java/org/tron/keystore/WalletFileTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletFileTest.java @@ -14,9 +14,9 @@ public class WalletFileTest { @Test public void testGetAddress() throws NoSuchAlgorithmException, CipherException { WalletFile walletFile1 = Wallet.createStandard("", SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"),true)); + SecureRandom.getInstance("NativePRNG"))); WalletFile walletFile2 = Wallet.createStandard("", SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"),true)); + SecureRandom.getInstance("NativePRNG"))); WalletFile walletFile3 = (WalletFile) getSame(walletFile1); Assert.assertNotEquals(walletFile1.getAddress(), walletFile2.getAddress()); Assert.assertNotEquals(walletFile1.getCrypto(), walletFile2.getCrypto()); diff --git a/plugins/src/main/java/common/org/tron/plugins/DbRoot.java b/plugins/src/main/java/common/org/tron/plugins/DbRoot.java index 45854bbebdc..307eafaa772 100644 --- a/plugins/src/main/java/common/org/tron/plugins/DbRoot.java +++ b/plugins/src/main/java/common/org/tron/plugins/DbRoot.java @@ -109,8 +109,7 @@ private Ret calcMerkleRoot(String name) { } private Sha256Hash getHash(Map.Entry entry) { - return Sha256Hash.of(true, - Bytes.concat(entry.getKey(), entry.getValue())); + return Sha256Hash.of(Bytes.concat(entry.getKey(), entry.getValue())); } private void printInfo(Ret ret) { diff --git a/plugins/src/main/java/common/org/tron/plugins/utils/DBUtils.java b/plugins/src/main/java/common/org/tron/plugins/utils/DBUtils.java index 6eb097cbec5..ca3345ba20a 100644 --- a/plugins/src/main/java/common/org/tron/plugins/utils/DBUtils.java +++ b/plugins/src/main/java/common/org/tron/plugins/utils/DBUtils.java @@ -139,7 +139,6 @@ public static String simpleDecode(byte[] bytes) { } public static Sha256Hash getTransactionId(Protocol.Transaction transaction) { - return Sha256Hash.of(true, - transaction.getRawData().toByteArray()); + return Sha256Hash.of(transaction.getRawData().toByteArray()); } } diff --git a/plugins/src/main/java/common/org/tron/plugins/utils/MerkleRoot.java b/plugins/src/main/java/common/org/tron/plugins/utils/MerkleRoot.java index 055f5dcdee0..b77a2a7e5e8 100644 --- a/plugins/src/main/java/common/org/tron/plugins/utils/MerkleRoot.java +++ b/plugins/src/main/java/common/org/tron/plugins/utils/MerkleRoot.java @@ -56,7 +56,7 @@ private static Leaf createLeaf(Sha256Hash hash) { } private static Sha256Hash computeHash(Sha256Hash leftHash, Sha256Hash rightHash) { - return Sha256Hash.of(true, + return Sha256Hash.of( leftHash.getByteString().concat(rightHash.getByteString()).toByteArray()); } diff --git a/plugins/src/main/java/common/org/tron/plugins/utils/Sha256Hash.java b/plugins/src/main/java/common/org/tron/plugins/utils/Sha256Hash.java index 67e6e64ea79..1f49c5f1124 100644 --- a/plugins/src/main/java/common/org/tron/plugins/utils/Sha256Hash.java +++ b/plugins/src/main/java/common/org/tron/plugins/utils/Sha256Hash.java @@ -29,7 +29,6 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; -import org.bouncycastle.crypto.digests.SM3Digest; /** @@ -71,8 +70,8 @@ public static Sha256Hash wrap(byte[] rawHashBytes) { * @param contents the bytes on which the hash value is calculated * @return a new instance containing the calculated (one-time) hash */ - public static Sha256Hash of(boolean isSha256, byte[] contents) { - return wrap(hash(isSha256, contents)); + public static Sha256Hash of(byte[] contents) { + return wrap(hash(contents)); } /** @@ -84,10 +83,10 @@ public static Sha256Hash of(boolean isSha256, byte[] contents) { * @return a new instance containing the calculated (one-time) hash * @throws IOException if an error occurs while reading the file */ - public static Sha256Hash of(boolean isSha256, File file) throws IOException { + public static Sha256Hash of(File file) throws IOException { try (FileInputStream in = new FileInputStream(file)) { - return of(isSha256, ByteStreams.toByteArray(in)); + return of(ByteStreams.toByteArray(in)); } } @@ -106,24 +105,14 @@ public static MessageDigest newDigest() { } } - /** - * Returns a new SM3 MessageDigest instance. This is a convenience method which wraps the checked - * exception that can never occur with a RuntimeException. - * - * @return a new SM3 MessageDigest instance - */ - public static SM3Digest newSM3Digest() { - return new SM3Digest(); - } - /** * Calculates the SHA-256 hash of the given bytes. * * @param input the bytes to hash * @return the hash (in big-endian order) */ - public static byte[] hash(boolean isSha256, byte[] input) { - return hash(isSha256, input, 0, input.length); + public static byte[] hash(byte[] input) { + return hash(input, 0, input.length); } /** @@ -134,19 +123,10 @@ public static byte[] hash(boolean isSha256, byte[] input) { * @param length the number of bytes to hash * @return the hash (in big-endian order) */ - public static byte[] hash(boolean isSha256, byte[] input, int offset, int length) { - if (isSha256) { - MessageDigest digest = newDigest(); - digest.update(input, offset, length); - return digest.digest(); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input, offset, length); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - return eHash; - } - + public static byte[] hash(byte[] input, int offset, int length) { + MessageDigest digest = newDigest(); + digest.update(input, offset, length); + return digest.digest(); } @Override