diff --git a/README.md b/README.md index 47382e47..461582a1 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ [TOC] -#JD区块链 0.8.3-SNAPSHOT +#JD区块链 0.5.0-SNAPSHOT ------------------------------------------------------------------------ ### 版本修订历史 @@ -354,266 +354,325 @@ JD区块链的核心对象包括: ## 五、编程接口 ### 1. 服务连接 + // 区块链共识域; + String realm = "SUPPLY_CHAIN_ALLIANCE"; + // 节点地址列表; + String[] peerIPs = { "192.168.10.10", "192.168.10.11", "192.168.10.12", "192.168.10.13" }; + // 客户端的认证账户; + String clientAddress = "kkjsafieweqEkadsfaslkdslkae998232jojf=="; + String privKey = "safefsd32q34vdsvs"; + // 创建服务代理; + BlockchainService service = BlockchainServiceFactory.createServiceProxy(realm, peerIPs, clientAddress, privKey); + +### 2. 账户注册 + // 创建服务代理; + BlockchainService service = BlockchainServiceFactory.createServiceProxy(realm, peerIPs, clientAddress, privKey); + + // 在本地定义注册账号的 TX; + String sponsorAddress = "kFGeafiafEeqEkadsfaslkdslkae99ds66jf=="; + String sponsorPrivKey = "privKkjwlkejflkjdsfoiajfij329323=="; + TransactionTemplate txTemp = service.newTransaction(sponsorAddress); + + //-------------------------------------- + // 区块链秘钥生成器;用于在客户端生成账户的公私钥和地址; + BlockchainKeyGenerator generator = BlockchainKeyGenerator.getInstance(); + BlockchainKeyPair bcKey1 = generator.generate(KeyType.ED25519); + BlockchainKeyPair bcKey2 = generator.generate(KeyType.ED25519); + + String exchangeContractScript = "function(){}"; + // 注册账户; + txTemp.registerAccount() + .register(bcKey1, AccountStateType.MAP, exchangeContractScript) + .register(bcKey2, AccountStateType.OBJECT, null); + //-------------------------------------- + // TX 准备就绪; + PreparedTransaction prepTx = txTemp.prepare(); -```java - //创建服务代理 - public static BlockchainKeyPair CLIENT_CERT = BlockchainKeyGenerator.getInstance().generate(); - final String GATEWAY_IP = "127.0.0.1"; - final int GATEWAY_PORT = 80; - final boolean SECURE = false; - GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect(GATEWAY_IP, GATEWAY_PORT, SECURE, - CLIENT_CERT); - // 创建服务代理; - BlockchainService service = serviceFactory.getBlockchainService(); -``` - - -### 2. 用户注册 - - -```java - // 创建服务代理; - BlockchainService service = serviceFactory.getBlockchainService(); - // 在本地定义注册账号的 TX; - TransactionTemplate txTemp = service.newTransaction(ledgerHash); - SignatureFunction signatureFunction = asymmetricCryptography.getSignatureFunction(CryptoAlgorithm.ED25519); - CryptoKeyPair cryptoKeyPair = signatureFunction.generateKeyPair(); - BlockchainKeyPair user = new BlockchainKeyPair(cryptoKeyPair.getPubKey(), cryptoKeyPair.getPrivKey()); - - txTemp.users().register(user.getIdentity()); - - // TX 准备就绪; - PreparedTransaction prepTx = txTemp.prepare(); - // 使用私钥进行签名; - CryptoKeyPair keyPair = getSponsorKey(); - prepTx.sign(keyPair); - - // 提交交易; - prepTx.commit(); -``` - - -### 3. 数据账户注册 - - -```java - // 创建服务代理; - BlockchainService service = serviceFactory.getBlockchainService(); - // 在本地定义注册账号的 TX; - TransactionTemplate txTemp = service.newTransaction(ledgerHash); - SignatureFunction signatureFunction = asymmetricCryptography.getSignatureFunction(CryptoAlgorithm.ED25519); - CryptoKeyPair cryptoKeyPair = signatureFunction.generateKeyPair(); - BlockchainKeyPair dataAccount = new BlockchainKeyPair(cryptoKeyPair.getPubKey(), cryptoKeyPair.getPrivKey()); - - txTemp.dataAccounts().register(dataAccount.getIdentity()); - - // TX 准备就绪; - PreparedTransaction prepTx = txTemp.prepare(); - // 使用私钥进行签名; - CryptoKeyPair keyPair = getSponsorKey(); - prepTx.sign(keyPair); - - // 提交交易; - prepTx.commit(); -``` - -### 4. 写入数据 - -```java - // 创建服务代理; - BlockchainService service = serviceFactory.getBlockchainService(); - - HashDigest ledgerHash = getLedgerHash(); - // 在本地定义注册账号的 TX; - TransactionTemplate txTemp = service.newTransaction(ledgerHash); - - // -------------------------------------- - // 将商品信息写入到指定的账户中; - // 对象将被序列化为 JSON 形式存储,并基于 JSON 结构建立查询索引; - String commodityDataAccount = "GGhhreGeasdfasfUUfehf9932lkae99ds66jf=="; - Commodity commodity1 = new Commodity(); - txTemp.dataAccount(commodityDataAccount).set("ASSET_CODE", commodity1.getCode().getBytes(), -1); - - // TX 准备就绪; - PreparedTransaction prepTx = txTemp.prepare(); - - String txHash = ByteArray.toBase64(prepTx.getHash().toBytes()); - // 使用私钥进行签名; - CryptoKeyPair keyPair = getSponsorKey(); - prepTx.sign(keyPair); - - // 提交交易; - prepTx.commit(); -``` - - -### 5. 查询数据 - -> 注:详细的查询可参考模块sdk-samples中SDK_GateWay_Query_Test_相关测试用例 - -```java - // 创建服务代理; - BlockchainService service = serviceFactory.getBlockchainService(); - - // 查询区块信息; - // 区块高度; - long ledgerNumber = service.getLedger(LEDGER_HASH).getLatestBlockHeight(); - // 最新区块; - LedgerBlock latestBlock = service.getBlock(LEDGER_HASH, ledgerNumber); - // 区块中的交易的数量; - long txCount = service.getTransactionCount(LEDGER_HASH, latestBlock.getHash()); - // 获取交易列表; - LedgerTransaction[] txList = service.getTransactions(LEDGER_HASH, ledgerNumber, 0, 100); - // 遍历交易列表 - for (LedgerTransaction ledgerTransaction : txList) { - TransactionContent txContent = ledgerTransaction.getTransactionContent(); - Operation[] operations = txContent.getOperations(); - if (operations != null && operations.length > 0) { - for (Operation operation : operations) { - operation = ClientOperationUtil.read(operation); - // 操作类型:数据账户注册操作 - if (operation instanceof DataAccountRegisterOperation) { - DataAccountRegisterOperation daro = (DataAccountRegisterOperation) operation; - BlockchainIdentity blockchainIdentity = daro.getAccountID(); - } - // 操作类型:用户注册操作 - else if (operation instanceof UserRegisterOperation) { - UserRegisterOperation uro = (UserRegisterOperation) operation; - BlockchainIdentity blockchainIdentity = uro.getUserID(); - } - // 操作类型:账本注册操作 - else if (operation instanceof LedgerInitOperation) { - - LedgerInitOperation ledgerInitOperation = (LedgerInitOperation)operation; - LedgerInitSetting ledgerInitSetting = ledgerInitOperation.getInitSetting(); - - ParticipantNode[] participantNodes = ledgerInitSetting.getConsensusParticipants(); - } - // 操作类型:合约发布操作 - else if (operation instanceof ContractCodeDeployOperation) { - ContractCodeDeployOperation ccdo = (ContractCodeDeployOperation) operation; - BlockchainIdentity blockchainIdentity = ccdo.getContractID(); - } - // 操作类型:合约执行操作 - else if (operation instanceof ContractEventSendOperation) { - ContractEventSendOperation ceso = (ContractEventSendOperation) operation; - } - // 操作类型:KV存储操作 - else if (operation instanceof DataAccountKVSetOperation) { - DataAccountKVSetOperation.KVWriteEntry[] kvWriteEntries = - ((DataAccountKVSetOperation) operation).getWriteSet(); - if (kvWriteEntries != null && kvWriteEntries.length > 0) { - for (DataAccountKVSetOperation.KVWriteEntry kvWriteEntry : kvWriteEntries) { - BytesValue bytesValue = kvWriteEntry.getValue(); - DataType dataType = bytesValue.getType(); - Object showVal = ClientOperationUtil.readValueByBytesValue(bytesValue); - System.out.println("writeSet.key=" + kvWriteEntry.getKey()); - System.out.println("writeSet.value=" + showVal); - System.out.println("writeSet.type=" + dataType); - System.out.println("writeSet.version=" + kvWriteEntry.getExpectedVersion()); - } - } - } - } - } - } - - // 根据交易的 hash 获得交易;注:客户端生成 PrepareTransaction 时得到交易hash; - HashDigest txHash = txList[0].getTransactionContent().getHash(); - Transaction tx = service.getTransactionByContentHash(LEDGER_HASH, txHash); - // 获取数据; - String commerceAccount = "GGhhreGeasdfasfUUfehf9932lkae99ds66jf=="; - String[] objKeys = new String[] { "x001", "x002" }; - KVDataEntry[] kvData = service.getDataEntries(LEDGER_HASH, commerceAccount, objKeys); - - long payloadVersion = kvData[0].getVersion(); - - // 获取数据账户下所有的KV列表 - KVDataEntry[] kvData = service.getDataEntries(ledgerHash, commerceAccount, 0, 100); - if (kvData != null && kvData.length > 0) { - for (KVDataEntry kvDatum : kvData) { - System.out.println("kvData.key=" + kvDatum.getKey()); - System.out.println("kvData.version=" + kvDatum.getVersion()); - System.out.println("kvData.type=" + kvDatum.getType()); - System.out.println("kvData.value=" + kvDatum.getValue()); - } - } -``` - - -### 6. 合约发布 - - -```java - - // 创建服务代理; - BlockchainService service = serviceFactory.getBlockchainService(); - - // 在本地定义TX模板 - TransactionTemplate txTemp = service.newTransaction(ledgerHash); - - // 合约内容读取 - byte[] contractBytes = FileUtils.readBytes(new File(CONTRACT_FILE)); - - // 生成用户 - BlockchainIdentityData blockchainIdentity = new BlockchainIdentityData(getSponsorKey().getPubKey()); - - // 发布合约 - txTemp.contracts().deploy(blockchainIdentity, contractBytes); - - // TX 准备就绪; - PreparedTransaction prepTx = txTemp.prepare(); - - // 使用私钥进行签名; - CryptoKeyPair keyPair = getSponsorKey(); - - prepTx.sign(keyPair); - - // 提交交易; - TransactionResponse transactionResponse = prepTx.commit(); - - assertTrue(transactionResponse.isSuccess()); - - // 打印合约地址 - System.out.println(blockchainIdentity.getAddress().toBase58()); - -``` - -### 7. 合约执行 - -```java - - // 创建服务代理; - BlockchainService service = serviceFactory.getBlockchainService(); - - // 在本地定义TX模板 - TransactionTemplate txTemp = service.newTransaction(ledgerHash); - - // 合约地址 - String contractAddressBase58 = ""; - - // Event - String event = ""; + // 使用私钥进行签名; + prepTx.sign(sponsorAddress, sponsorPrivKey); - // args(注意参数的格式) - byte[] args = "20##30##abc".getBytes(); + // 提交交易; + prepTx.commit(); +### 3. 权限设置 - // 提交合约执行代码 - txTemp.contractEvents().send(contractAddressBase58, event, args); + // 创建服务代理; + BlockchainService service = BlockchainServiceFactory.createServiceProxy(realm, peerIPs, clientAddress, privKey); + + // 在本地定义注册账号的 TX; + String sponsorAddress = "kFGeafiafEeqEkadsfaslkdslkae99ds66jf=="; + String sponsorPrivKey = "privKkjwlkejflkjdsfoiajfij329323=="; + TransactionTemplate txTemp = service.newTransaction(sponsorAddress); + + //-------------------------------------- + // 配置账户的权限; + String walletAccount = "Kjfe8832hfa9jjjJJDkshrFjksjdlkfj93F=="; + String user1 = "MMMEy902jkjjJJDkshreGeasdfassdfajjf=="; + String user2 = "Kjfe8832hfa9jjjJJDkshrFjksjdlkfj93F=="; + // 配置: + // “状态数据的写入权限”的阈值为 100; + // 需要 user1、user2 两个账户的联合签名才能写入; + // 当前账户仅用于表示一个业务钱包,禁止自身的写入权限,只能由业务角色的账户才能操作; + txTemp.configPrivilege(walletAccount) + .setThreshhold(PrivilegeType.STATE_WRITE, 100) + .enable(PrivilegeType.STATE_WRITE, user1, 50) + .enable(PrivilegeType.STATE_WRITE, user2, 50) + .disable(PrivilegeType.STATE_WRITE, walletAccount); + //-------------------------------------- + + // TX 准备就绪; + PreparedTransaction prepTx = txTemp.prepare(); + + // 使用私钥进行签名; + prepTx.sign(sponsorAddress, sponsorPrivKey); + + // 提交交易; + prepTx.commit(); - // TX 准备就绪; - PreparedTransaction prepTx = txTemp.prepare(); +### 4. 写入数据 - // 生成私钥并使用私钥进行签名; - CryptoKeyPair keyPair = getSponsorKey(); + // 创建服务代理; + BlockchainService service = BlockchainServiceFactory.createServiceProxy(realm, peerIPs, clientAddress, privKey); + + // 在本地定义注册账号的 TX; + String sponsorAddress = "kFGeafiafEeqEkadsfaslkdslkae99ds66jf=="; + String sponsorPrivKey = "privKkjwlkejflkjdsfoiajfij329323=="; + TransactionTemplate txTemp = service.newTransaction(sponsorAddress); + + // -------------------------------------- + // 将商品信息写入到指定的账户中; + // 对象将被序列化为 JSON 形式存储,并基于 JSON 结构建立查询索引; + String commodityDataAccount = "GGhhreGeasdfasfUUfehf9932lkae99ds66jf=="; + Commodity commodity1 = new Commodity(); + Commodity commodity2 = new Commodity(); + txTemp.updateObjects(commodityDataAccount) + .insert(commodity1.getCode(), commodity1) + .update(commodity2.getCode(), commodity2, true); + + // 在钱包账户以 KEY “RMB-ASSET” 表示一种数字资产,通过在一个 TX + // 对两个账户的同一个资产数值分别增加和减少,实现转账的功能; + String walletAccount1 = "MMMEy902jkjjJJDkshreGeasdfassdfajjf=="; + String walletAccount2 = "Kjfe8832hfa9jjjJJDkshrFjksjdlkfj93F=="; + txTemp.updateMap(walletAccount1).decreaseInt("RMB-ASSET", 1000); + txTemp.updateMap(walletAccount2).increaseInt("RMB-ASSET", 1000); + // -------------------------------------- + + // TX 准备就绪; + PreparedTransaction prepTx = txTemp.prepare(); + String txHash = prepTx.getHash(); + + // 使用私钥进行签名; + prepTx.sign(sponsorAddress, sponsorPrivKey); + + // 提交交易; + prepTx.commit(); + +### 5. 查询数据 + // 创建服务代理; + BlockchainService service = BlockchainServiceFactory.createServiceProxy(realm, peerIPs, clientAddress, privKey); + + // 查询区块信息; + // 区块高度; + long ledgerNumber = service.getLedgerNumber(); + // 最新区块; + Block latestBlock = service.getBlock(ledgerNumber); + // 区块中的交易的数量; + int txCount = latestBlock.getTxCount(); + // 获取交易列表; + Transaction[] txList = service.getTransactions(ledgerNumber, 0, 100); + + // 根据交易的 hash 获得交易;注:客户端生成 PrepareTransaction 时得到交易hash; + String txHash = "iikjeqke98321rjoijsdfa"; + Transaction tx = service.getTransaction(txHash); + + // 获取数据; + String commerceAccount = "GGhhreGeasdfasfUUfehf9932lkae99ds66jf=="; + Set objKeys = ArrayUtils.asSet(new String[] { "x001", "x002" }); + + PayloadMap payloadData = service.getPayload(commerceAccount, objKeys); + + AccountStateType payloadType = payloadData.getPayloadType(); + long payloadVersion = payloadData.getPayloadVersion(); + + boolean exist = service.containPayload(commerceAccount, "x003"); + + // 按条件查询; + // 1、从保存会员信息的账户地址查询; + String condition = "female = true AND age > 18 AND address.city = 'beijing'"; + String memberInfoAccountAddress = "kkf2io39823jfIjfiIRWKQj30203fx=="; + PayloadMap memberInfo = service.queryObject(memberInfoAccountAddress, condition); + + // 2、从保存会员信息的账户地址查询; + Map memberInfoWithAccounts = service.queryObject(condition); + +### 6. 合约调用 + // 创建服务代理; + BlockchainService service = BlockchainServiceFactory.createServiceProxy(realm, peerIPs, clientAddress, privKey); + + // 发起交易; + String sponsorAddress = "kFGeafiafEeqEkadsfaslkdslkae99ds66jf=="; + String sponsorPrivKey = "privKkjwlkejflkjdsfoiajfij329323=="; + TransactionTemplate txTemp = service.newTransaction(sponsorAddress); + + // -------------------------------------- + // 一个贸易账户,贸易结算后的利润将通过一个合约账户来执行利润分配; + // 合约账户被设置为通用的账户,不具备对贸易结算账户的直接权限; + // 只有当前交易发起人具备对贸易账户的直接权限,当交易发起人对交易进行签名之后,权限被间接传递给合约账户; + String commerceAccount = "GGhhreGeasdfasfUUfehf9932lkae99ds66jf=="; + // 处理利润分成的通用业务逻辑的合约账户; + String profitDistributionContract = "AAdfe4346fHhefe34fwf343kaeER4678RT=="; + + //收益人账户; + String receiptorAccount1 = "MMMEy902jkjjJJDkshreGeasdfassdfajjf=="; + String receiptorAccount2 = "Kjfe8832hfa9jjjJJDkshrFjksjdlkfj93F=="; + //资产编码; + String assetKey = "RMB-ASSET"; + //此次待分配利润; + long profit = 1000000; + + //备注信息; + Remark remark = new Remark(); + String remarkJSON = SerializeUtils.serializeToJSON(remark); + + // 合约代码的参数表; + String[] args = { commerceAccount, assetKey, profit+"", receiptorAccount1, receiptorAccount2, remarkJSON }; + + // 调用合约代码的分配操作; + txTemp.executeScript(commerceAccount) + .invoke("DISTRIBUTE", args); + // -------------------------------------- - prepTx.sign(keyPair); + // TX 准备就绪; + PreparedTransaction prepTx = txTemp.prepare(); + String txHash = prepTx.getHash(); - // 提交交易; - TransactionResponse transactionResponse = prepTx.commit(); + // 使用私钥进行签名; + prepTx.sign(sponsorAddress, sponsorPrivKey); - assertTrue(transactionResponse.isSuccess()); + // 提交交易; + prepTx.commit(); -``` \ No newline at end of file +### 7. 事件监听 + // 创建服务代理; + BlockchainService service = BlockchainServiceFactory.createServiceProxy(realm, peerIPs, clientAddress, privKey); + + //监听账户变动; + String walletAccount = "MMMEy902jkjjJJDkshreGeasdfassdfajjf=="; + service.addBlockchainEventListener(BlockchainEventType.PAYLOAD_UPDATED.CODE, null, walletAccount, new BlockchainEventListener() { + @Override + public void onEvent(BlockchainEventMessage eventMessage, BlockchainEventHandle eventHandle) { + //钱包余额; + PayloadMap balancePayload = service.getPayload(walletAccount, "RMB-ASSET"); + Long balance =(Long) balancePayload.get("RMB-ASSET"); + if (balance != null) { + //notify balance change; + }else{ + //wallet is empty and isn't listened any more; + eventHandle.cancel(); + } + } + }); + + //销毁服务代理; + service.dispose(); + +### 8. 合约开发 + /** + * 示例:一个“资产管理”智能合约的实现; + * + * 注: 1、实现 EventProcessingAwire 接口以便合约实例在运行时可以从上下文获得合约生命周期事件的通知; 2、实现 + * AssetContract 接口定义的合约方法; + * + * @author huanghaiquan + * + */ + public class AssetContractImpl implements EventProcessingAwire, AssetContract { + // 资产管理账户的地址; + private static final String ASSET_ADDRESS = "2njZBNbFQcmKd385DxVejwSjy4driRzf9Pk"; + // 保存资产总数的键; + private static final String KEY_TOTAL = "TOTAL"; + // 合约事件上下文; + private ContractEventContext eventContext; + + /** + * ------------------- 定义可以由外部用户通过提交“交易”触发的调用方法 ------------------ + */ + + @Override + public void issue(long amount, String assetHolderAddress) { + checkAllOwnersAgreementPermission(); + + // 新发行的资产数量; + if (amount < 0) { + throw new ContractError("The amount is negative!"); + } + if (amount == 0) { + return; + } + + // 校验持有者账户的有效性; + BlockchainAccount holderAccount = eventContext.getLedger().getAccount(currentLedgerHash(), assetHolderAddress); + if (holderAccount == null) { + throw new ContractError("The holder is not exist!"); + } + + // 查询当前值; + Set keys = new HashSet<>(); + keys.add(KEY_TOTAL); + keys.add(assetHolderAddress); + StateMap currStates = eventContext.getLedger().getStates(currentLedgerHash(), ASSET_ADDRESS, keys); + + // 计算资产的发行总数; + StateEntry currTotal = currStates.get(KEY_TOTAL); + StateEntry newTotal = currTotal.newLong(currTotal.longValue() + amount); + + // 分配到持有者账户; + StateEntry holderAmount = currStates.get(assetHolderAddress); + StateEntry newHodlerAmount = holderAmount.newLong(holderAmount.longValue() + amount); + + // 把数据的更改写入到账本; + SimpleStateMap newStates = new SimpleStateMap(currStates.getAccount(), currStates.getAccountVersion(), + currStates.getStateVersion()); + newStates.setValue(newTotal); + newStates.setValue(newHodlerAmount); + + eventContext.getLedger().updateState(ASSET_ADDRESS).setStates(currStates); + } + + @Override + public void transfer(String fromAddress, String toAddress, long amount) { + if (amount < 0) { + throw new ContractError("The amount is negative!"); + } + if (amount == 0) { + return; + } + + //校验“转出账户”是否已签名; + checkSignerPermission(fromAddress); + + // 查询现有的余额; + Set keys = new HashSet<>(); + keys.add(fromAddress); + keys.add(toAddress); + StateMap origBalances = eventContext.getLedger().getStates(currentLedgerHash(), ASSET_ADDRESS, keys); + StateEntry fromBalance = origBalances.get(fromAddress); + StateEntry toBalance = origBalances.get(toAddress); + + //检查是否余额不足; + if ((fromBalance.longValue() - amount) < 0) { + throw new ContractError("Insufficient balance!"); + } + + // 把数据的更改写入到账本; + SimpleStateMap newBalances = new SimpleStateMap(origBalances.getAccount(), origBalances.getAccountVersion(), + origBalances.getStateVersion()); + StateEntry newFromBalance = fromBalance.newLong(fromBalance.longValue() - amount); + StateEntry newToBalance = toBalance.newLong(toBalance.longValue() + amount); + newBalances.setValue(newFromBalance); + newBalances.setValue(newToBalance); + + eventContext.getLedger().updateState(ASSET_ADDRESS).setStates(newBalances); + } + } \ No newline at end of file diff --git a/README.zip b/README.zip new file mode 100644 index 00000000..7484f742 Binary files /dev/null and b/README.zip differ diff --git a/docs/readme.zip b/docs/readme.zip index 5ad632fe..7484f742 100644 Binary files a/docs/readme.zip and b/docs/readme.zip differ diff --git a/source/base/pom.xml b/source/base/pom.xml index 68a2cf0e..9a67837e 100644 --- a/source/base/pom.xml +++ b/source/base/pom.xml @@ -8,4 +8,12 @@ 0.9.0-SNAPSHOT base + + + + org.slf4j + slf4j-api + + + \ No newline at end of file diff --git a/source/base/src/main/java/com/jd/blockchain/base/data/TypeCodes.java b/source/base/src/main/java/com/jd/blockchain/consts/TypeCodes.java similarity index 97% rename from source/base/src/main/java/com/jd/blockchain/base/data/TypeCodes.java rename to source/base/src/main/java/com/jd/blockchain/consts/TypeCodes.java index b2e28bd9..3289a18f 100644 --- a/source/base/src/main/java/com/jd/blockchain/base/data/TypeCodes.java +++ b/source/base/src/main/java/com/jd/blockchain/consts/TypeCodes.java @@ -1,4 +1,4 @@ -package com.jd.blockchain.base.data; +package com.jd.blockchain.consts; /** * @author huanghaiquan @@ -83,7 +83,7 @@ public interface TypeCodes { public static final int ENUM_TYPE = 0xB20; - public static final int ENUM_TYPE_CRYPTO_ALGORITHM = 0xB21; + public static final int CRYPTO_ALGORITHM = 0xB21; public static final int ENUM_TYPE_TRANSACTION_STATE = 0xB22; diff --git a/source/base/src/main/java/com/jd/blockchain/provider/NamedProvider.java b/source/base/src/main/java/com/jd/blockchain/provider/NamedProvider.java new file mode 100644 index 00000000..a1e08b27 --- /dev/null +++ b/source/base/src/main/java/com/jd/blockchain/provider/NamedProvider.java @@ -0,0 +1,20 @@ +package com.jd.blockchain.provider; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Mark a class as a named service provider; + * + * @author huanghaiquan + * + */ +@Target({ ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +public @interface NamedProvider { + + String value() default ""; + +} diff --git a/source/base/src/main/java/com/jd/blockchain/provider/Provider.java b/source/base/src/main/java/com/jd/blockchain/provider/Provider.java new file mode 100644 index 00000000..6843a1a6 --- /dev/null +++ b/source/base/src/main/java/com/jd/blockchain/provider/Provider.java @@ -0,0 +1,11 @@ +package com.jd.blockchain.provider; + +public interface Provider { + + String getShortName(); + + String getFullName(); + + S getService(); + +} diff --git a/source/base/src/main/java/com/jd/blockchain/provider/ProviderException.java b/source/base/src/main/java/com/jd/blockchain/provider/ProviderException.java new file mode 100644 index 00000000..68840e59 --- /dev/null +++ b/source/base/src/main/java/com/jd/blockchain/provider/ProviderException.java @@ -0,0 +1,11 @@ +package com.jd.blockchain.provider; + +public class ProviderException extends RuntimeException { + + private static final long serialVersionUID = 6422628637835262811L; + + public ProviderException(String message) { + super(message); + } + +} diff --git a/source/base/src/main/java/com/jd/blockchain/provider/ProviderManager.java b/source/base/src/main/java/com/jd/blockchain/provider/ProviderManager.java new file mode 100644 index 00000000..af6fabdc --- /dev/null +++ b/source/base/src/main/java/com/jd/blockchain/provider/ProviderManager.java @@ -0,0 +1,247 @@ +package com.jd.blockchain.provider; + +import java.security.AccessControlContext; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.ServiceLoader; +import java.util.concurrent.ConcurrentHashMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The ProviderManager manages all serivce providers in the system. + *

+ * + * The service is represented by an interface, and the provider is + * implementation class of the service. + *

+ * + * One service can have multiple providers in the system. + *

+ * + * A provider must have a name, and implementor can use the annotation + * {@link NamedProvider} to specify a short name, otherwise the system defaults + * to the full name of the implementation class. + * + * + * @author huanghaiquan + * + */ +public final class ProviderManager { + + private final Logger LOGGER = LoggerFactory.getLogger(ProviderManager.class); + + private final Object mutex = new Object(); + + private ConcurrentHashMap, NamedProviders> serviceProviders = new ConcurrentHashMap<>(); + + /** + * 返回指定提供者的服务; + * + * @param serviceClazz + * @param providerName + * @return + */ + public S getService(Class serviceClazz, String providerName) { + NamedProviders providers = getServiceProvider(serviceClazz); + return providers.getService(providerName); + } + + public Collection> getAllProviders(Class serviceClazz) { + NamedProviders providers = getServiceProvider(serviceClazz); + return providers.getProviders(); + } + + public S installProvider(Class serviceClazz, String providerFullName) { + NamedProviders providers = getServiceProvider(serviceClazz); + return providers.install(providerFullName); + } + + public S installProvider(Class service, String providerFullName, ClassLoader classLoader) { + NamedProviders providers = getServiceProvider(service); + return providers.install(providerFullName, classLoader); + } + + public void installAllProviders(Class serviceClazz, ClassLoader classLoader) { + NamedProviders providers = getServiceProvider(serviceClazz); + providers.installAll(classLoader); + } + + @SuppressWarnings("unchecked") + private NamedProviders getServiceProvider(Class serviceClazz) { + NamedProviders providers = (NamedProviders) serviceProviders.get(serviceClazz); + if (providers == null) { + synchronized (mutex) { + providers = (NamedProviders) serviceProviders.get(serviceClazz); + if (providers == null) { + providers = new NamedProviders(serviceClazz); + serviceProviders.put(serviceClazz, providers); + } + } + } + return providers; + } + + /** + * @author huanghaiquan + * + * @param + * Type of Service + */ + private class NamedProviders { + + private Class serviceClazz; + + private Map> namedProviders = new LinkedHashMap<>(); + + private AccessControlContext acc; + + public NamedProviders(Class serviceClazz) { + this.serviceClazz = serviceClazz; + this.acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null; + installAll(); + } + + public void installAll(ClassLoader classLoader) { + ServiceLoader sl = ServiceLoader.load(serviceClazz, classLoader); + installAll(sl); + } + + public void installAll() { + // 默认采用线程上下文的类加载器;避免直接采用系统的类加载器: ClassLoader.getSystemClassLoader() ; + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + installAll(classLoader); + } + + private synchronized void installAll(ServiceLoader sl) { + for (S provider : sl) { + install(provider); + } + } + + /** + * 安装指定的服务提供者;
+ * + * 如果同名的服务提供者已经存在(包括ShortName和FullName任意之一存在),则返回 false;
+ * + * 如果同名的服务提供者不存在,则返回 false; + * + * @param service + * 提供者的服务实现; + * @return + */ + private synchronized boolean install(S service) { + String fullName = service.getClass().getName(); + if (namedProviders.containsKey(fullName)) { + LOGGER.warn(String.format("The provider[%s] already exists.", fullName)); + return false; + } + String shortName = null; + NamedProvider annoNP = service.getClass().getAnnotation(NamedProvider.class); + if (annoNP != null && annoNP.value() != null) { + String n = annoNP.value().trim(); + if (n.length() > 0) { + shortName = n; + } + } + if (shortName != null && namedProviders.containsKey(shortName)) { + return false; + } + ProviderInfo provider = new ProviderInfo<>(shortName, fullName, service); + if (shortName != null) { + namedProviders.put(shortName, provider); + } + namedProviders.put(fullName, provider); + return true; + } + + public S install(String providerFullName) { + return install(providerFullName, null); + } + + public S install(String providerFullName, ClassLoader classLoader) { + // 默认采用线程上下文的类加载器;避免直接采用系统的类加载器: ClassLoader.getSystemClassLoader() ; + ClassLoader cl = (classLoader == null) ? Thread.currentThread().getContextClassLoader() : classLoader; + S p = null; + if (acc == null) { + p = instantiate(providerFullName, cl); + } else { + PrivilegedAction action = new PrivilegedAction() { + public S run() { + return instantiate(providerFullName, cl); + } + }; + p = AccessController.doPrivileged(action, acc); + } + if (!install(p)) { + throw new ProviderException( + "[" + serviceClazz.getName() + "] Provider " + providerFullName + " already exist!"); + } + return p; + } + + public Collection> getProviders() { + return namedProviders.values(); + } + + public S getService(String name) { + Provider pd = namedProviders.get(name); + return pd == null ? null : pd.getService(); + } + + private S instantiate(String className, ClassLoader classLoader) { + Class c = null; + try { + c = Class.forName(className, false, classLoader); + } catch (ClassNotFoundException x) { + throw new ProviderException("[" + serviceClazz.getName() + "] Provider " + className + " not found"); + } + if (!serviceClazz.isAssignableFrom(c)) { + throw new ProviderException( + "[" + serviceClazz.getName() + "] Provider " + className + " not a subtype"); + } + try { + S provider = serviceClazz.cast(c.newInstance()); + return provider; + } catch (Throwable e) { + throw new ProviderException("[" + serviceClazz.getName() + "] Provider " + className + + " could not be instantiated! --" + e.getMessage()); + } + } + } + + private static class ProviderInfo implements Provider { + + private final String shortName; + + private final String fullName; + + private final S service; + + public ProviderInfo(String shortName, String fullName, S service) { + this.shortName = shortName; + this.fullName = fullName; + this.service = service; + } + + @Override + public String getShortName() { + return shortName; + } + + @Override + public String getFullName() { + return fullName; + } + + @Override + public S getService() { + return service; + } + + } +} diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartClientIncomingConfig.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartClientIncomingConfig.java index d8e7c115..afa21aeb 100644 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartClientIncomingConfig.java +++ b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartClientIncomingConfig.java @@ -1,6 +1,6 @@ package com.jd.blockchain.consensus.bftsmart; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; public class BftsmartClientIncomingConfig implements BftsmartClientIncomingSettings { diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartClientIncomingSettings.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartClientIncomingSettings.java index 9a1548b6..354180a8 100644 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartClientIncomingSettings.java +++ b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartClientIncomingSettings.java @@ -1,10 +1,10 @@ package com.jd.blockchain.consensus.bftsmart; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; import com.jd.blockchain.consensus.ClientIncomingSettings; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.consts.TypeCodes; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.utils.ValueType; @DataContract(code = TypeCodes.CONSENSUS_BFTSMART_CLI_INCOMING_SETTINGS) diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartCommitBlockSettings.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartCommitBlockSettings.java index 749fdaed..e99ea811 100644 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartCommitBlockSettings.java +++ b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartCommitBlockSettings.java @@ -1,8 +1,8 @@ package com.jd.blockchain.consensus.bftsmart; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.ValueType; diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusSettings.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusSettings.java index ae72383e..8b6fa451 100644 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusSettings.java +++ b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusSettings.java @@ -1,9 +1,9 @@ package com.jd.blockchain.consensus.bftsmart; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; import com.jd.blockchain.consensus.ConsensusSettings; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.Property; import com.jd.blockchain.utils.ValueType; import com.jd.blockchain.utils.serialize.binary.BinarySerializeUtils; diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusSettingsBuilder.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusSettingsBuilder.java index 6c25f0ac..1311a3a2 100644 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusSettingsBuilder.java +++ b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartConsensusSettingsBuilder.java @@ -14,7 +14,7 @@ import org.springframework.core.io.ClassPathResource; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.consensus.ConsensusSettingsBuilder; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; public class BftsmartConsensusSettingsBuilder implements ConsensusSettingsBuilder { diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartNodeConfig.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartNodeConfig.java index 005e05c5..fd45b144 100644 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartNodeConfig.java +++ b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartNodeConfig.java @@ -2,7 +2,7 @@ package com.jd.blockchain.consensus.bftsmart; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.utils.net.NetworkAddress; public class BftsmartNodeConfig implements BftsmartNodeSettings { diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartNodeSettings.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartNodeSettings.java index 50a5e1a1..e1595626 100644 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartNodeSettings.java +++ b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/BftsmartNodeSettings.java @@ -1,10 +1,10 @@ package com.jd.blockchain.consensus.bftsmart; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; import com.jd.blockchain.consensus.NodeSettings; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.consts.TypeCodes; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.utils.ValueType; import com.jd.blockchain.utils.net.NetworkAddress; diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientConfig.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientConfig.java index 6bb9e238..89dfe1e4 100644 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientConfig.java +++ b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientConfig.java @@ -2,7 +2,7 @@ package com.jd.blockchain.consensus.bftsmart.client; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.consensus.bftsmart.BftsmartClientIncomingSettings; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; public class BftsmartClientConfig implements BftsmartClientSettings { diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientIdentification.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientIdentification.java index 3b046e1f..7ce425a3 100644 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientIdentification.java +++ b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartClientIdentification.java @@ -2,12 +2,8 @@ package com.jd.blockchain.consensus.bftsmart.client; import com.jd.blockchain.consensus.ClientIdentification; import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider; -import com.jd.blockchain.crypto.CryptoUtils; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; -import com.jd.blockchain.crypto.asymmetric.SignatureFunction; - -import java.util.Arrays; public class BftsmartClientIdentification implements ClientIdentification { diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartConsensusClientFactory.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartConsensusClientFactory.java index 51afe4d2..b0855c7a 100644 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartConsensusClientFactory.java +++ b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartConsensusClientFactory.java @@ -12,6 +12,8 @@ import com.jd.blockchain.consensus.client.ClientFactory; import com.jd.blockchain.consensus.client.ClientSettings; import com.jd.blockchain.consensus.client.ConsensusClient; import com.jd.blockchain.crypto.CryptoUtils; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.*; import com.jd.blockchain.utils.http.agent.HttpServiceAgent; import com.jd.blockchain.utils.http.agent.ServiceEndpoint; diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartMessageService.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartMessageService.java index 53a5f0a8..a80375a4 100644 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartMessageService.java +++ b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/client/BftsmartMessageService.java @@ -27,16 +27,16 @@ public class BftsmartMessageService implements MessageService { AsynchServiceProxy asynchServiceProxy = null; try { asynchServiceProxy = asyncPeerProxyPool.borrowObject(); -// //0: Transaction msg, 1: Commitblock msg -// byte[] msgType = BytesUtils.toBytes(0); -// byte[] wrapMsg = new byte[message.length + 4]; -// System.arraycopy(message, 0, wrapMsg, 4, message.length); -// System.arraycopy(msgType, 0, wrapMsg, 0, 4); -// -// System.out.printf("BftsmartMessageService invokeOrdered time = %s, id = %s threadId = %s \r\n", -// System.currentTimeMillis(), asynchServiceProxy.getProcessId(), Thread.currentThread().getId()); - - byte[] result = asynchServiceProxy.invokeOrdered(message); + //0: Transaction msg, 1: Commitblock msg + byte[] msgType = BytesUtils.toBytes(0); + byte[] wrapMsg = new byte[message.length + 4]; + System.arraycopy(message, 0, wrapMsg, 4, message.length); + System.arraycopy(msgType, 0, wrapMsg, 0, 4); + + System.out.printf("BftsmartMessageService invokeOrdered time = %s, id = %s threadId = %s \r\n", + System.currentTimeMillis(), asynchServiceProxy.getProcessId(), Thread.currentThread().getId()); + + byte[] result = asynchServiceProxy.invokeOrdered(wrapMsg); asyncFuture.complete(result); } catch (Exception e) { diff --git a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartNodeServer.java b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartNodeServer.java index f25c8d61..84f6aab2 100644 --- a/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartNodeServer.java +++ b/source/consensus/consensus-bftsmart/src/main/java/com/jd/blockchain/consensus/bftsmart/service/BftsmartNodeServer.java @@ -1,15 +1,27 @@ package com.jd.blockchain.consensus.bftsmart.service; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + import bftsmart.tom.*; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; + +import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.consensus.ConsensusManageService; import com.jd.blockchain.consensus.NodeSettings; +import com.jd.blockchain.consensus.bftsmart.BftsmartCommitBlockSettings; import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider; import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusSettings; import com.jd.blockchain.consensus.bftsmart.BftsmartNodeSettings; @@ -19,12 +31,28 @@ import com.jd.blockchain.consensus.service.NodeServer; import com.jd.blockchain.consensus.service.ServerSettings; import com.jd.blockchain.consensus.service.StateHandle; import com.jd.blockchain.consensus.service.StateMachineReplicate; +import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoUtils; +import com.jd.blockchain.crypto.hash.HashDigest; +import com.jd.blockchain.ledger.BlockchainKeyGenerator; +import com.jd.blockchain.ledger.BlockchainKeyPair; +import com.jd.blockchain.ledger.TransactionContent; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.ledger.TransactionRespHandle; +import com.jd.blockchain.ledger.TransactionResponse; import com.jd.blockchain.ledger.TransactionState; +import com.jd.blockchain.ledger.data.TxContentBlob; +import com.jd.blockchain.ledger.data.TxRequestMessage; import com.jd.blockchain.utils.PropertiesUtils; +import com.jd.blockchain.utils.codec.Base58Utils; import com.jd.blockchain.utils.concurrent.AsyncFuture; +import com.jd.blockchain.utils.concurrent.CompletableAsyncFuture; import com.jd.blockchain.utils.io.BytesUtils; +import com.jd.blockchain.utils.serialize.binary.BinarySerializeUtils; + import bftsmart.reconfiguration.util.HostsConfig; import bftsmart.reconfiguration.util.TOMConfiguration; +import bftsmart.reconfiguration.views.MemoryBasedViewStorage; import bftsmart.tom.core.messages.TOMMessage; import bftsmart.tom.server.defaultservices.DefaultRecoverable; @@ -34,9 +62,15 @@ public class BftsmartNodeServer extends DefaultRecoverable implements NodeServer private List stateHandles = new CopyOnWriteArrayList<>(); +// private List batchConsensusListeners = new LinkedList<>(); + +// private Map> replyContextMessages = new ConcurrentHashMap<>(); + // TODO 暂不处理队列溢出问题 private ExecutorService notifyReplyExecutors = Executors.newSingleThreadExecutor(); +// private ExecutorService sendCommitExecutors = Executors.newFixedThreadPool(2); + private volatile Status status = Status.STOPPED; private final Object mutex = new Object(); @@ -67,6 +101,28 @@ public class BftsmartNodeServer extends DefaultRecoverable implements NodeServer private int serverId; +// private volatile String batchId = null; +// +//// private List> replyMessages ; +// +// private boolean leader_has_makedicision = false; +// +// private boolean commit_block_condition = false; +// +// private final AtomicLong txIndex = new AtomicLong(); +// +// private final AtomicLong blockIndex = new AtomicLong(); +// +// private static final AtomicInteger incrementNum = new AtomicInteger(); +// +//// private final BlockingQueue txRequestQueue = new LinkedBlockingQueue(); +// +// private final ExecutorService queueExecutor = Executors.newSingleThreadExecutor(); +// +// private final ScheduledExecutorService timerEexecutorService = new ScheduledThreadPoolExecutor(10); +// private ServiceProxy peerProxy; + + public BftsmartNodeServer() { } @@ -83,6 +139,22 @@ public class BftsmartNodeServer extends DefaultRecoverable implements NodeServer initConfig(serverId, systemConfig, hostsConfig); } + //aim to send commit block message +// protected void createProxyClient() { +// BftsmartTopology topologyCopy = (BftsmartTopology) topology.copyOf(); +// +// MemoryBasedViewStorage viewStorage = new MemoryBasedViewStorage(topologyCopy.getView()); +// +// byte[] bytes = BinarySerializeUtils.serialize(tomConfig); +// +// TOMConfiguration decodeTomConfig = BinarySerializeUtils.deserialize(bytes); +// +// decodeTomConfig.setProcessId(0); +// +// peerProxy = new ServiceProxy(decodeTomConfig, viewStorage, null, null); +// +// } + protected int findServerId() { int serverId = 0; @@ -190,12 +262,214 @@ public class BftsmartNodeServer extends DefaultRecoverable implements NodeServer return appExecuteBatch(commands, msgCtxs, fromConsensus, null); } +// private boolean checkLeaderId(MessageContext[] msgCtxs) { +// boolean result = false; +// +// for (int i = 0; i < msgCtxs.length - 1; i++) { +// if (msgCtxs[i].getLeader() != msgCtxs[i+1].getLeader()) +// return result; +// } +// +// result = true; +// +// return result; +// } +// +// //普通消息处理 +// private void normalMsgProcess(ReplyContextMessage replyContextMsg, byte[] msg, String realmName, String batchId) { +// AsyncFuture replyMsg = messageHandle.processOrdered(replyContextMsg.getMessageContext().getOperationId(), msg, realmName, batchId); +// replyContextMessages.put(replyContextMsg, replyMsg); +// } +// +// //结块消息处理 +// private void commitMsgProcess(ReplyContextMessage replyContextMsg, String realmName, String batchId) { +// try{ +// //receive messages before commitblock message, then execute commit +// if (replyContextMessages.size() != 0) { +// messageHandle.completeBatch(realmName, batchId); +// messageHandle.commitBatch(realmName, batchId); +// } +// +// // commit block msg need response too +// CompletableAsyncFuture asyncFuture = new CompletableAsyncFuture<>(); +// TransactionResponse transactionRespHandle = new TransactionRespHandle(newBlockCommitRequest(), +// TransactionState.SUCCESS, TransactionState.SUCCESS); +// +// asyncFuture.complete(BinaryEncodingUtils.encode(transactionRespHandle, TransactionResponse.class)); +// replyContextMessages.put(replyContextMsg, asyncFuture); +// }catch (Exception e){ +// LOGGER.error("Error occurred on commit batch transactions, so the new block is canceled! --" + e.getMessage(), e); +// messageHandle.rollbackBatch(realmName, batchId, -1); +// }finally{ +// this.batchId = null; +// } +// } + +// private void sendCommitMessage() { +// +// HashDigest ledgerHash = new HashDigest(Base58Utils.decode(realmName)); +// +// BlockchainKeyPair userKeyPeer = BlockchainKeyGenerator.getInstance().generate(); +// +// TxContentBlob txContentBlob = new TxContentBlob(ledgerHash); +// +// byte[] reqBytes = BinaryEncodingUtils.encode(txContentBlob, TransactionContent.class); +// +// HashDigest reqHash = CryptoUtils.hash(CryptoAlgorithm.SHA256).hash(reqBytes); +// +// txContentBlob.setHash(reqHash); +// +// TxRequestMessage transactionRequest = new TxRequestMessage(txContentBlob); +// +// byte[] msg = BinaryEncodingUtils.encode(transactionRequest, TransactionRequest.class); +// +// byte[] type = BytesUtils.toBytes(1); +// +// byte[] wrapMsg = new byte[msg.length + 4]; +// +// System.arraycopy(type, 0, wrapMsg, 0, 4); +// System.arraycopy(msg, 0, wrapMsg, 4, msg.length); +// +// peerProxy.invokeOrdered(wrapMsg); +// +// LOGGER.info("Send commit block msg success!"); +// } + +// private TransactionRequest newBlockCommitRequest() { +// +// HashDigest ledgerHash = new HashDigest(Base58Utils.decode(realmName)); +// +// TxContentBlob txContentBlob = new TxContentBlob(ledgerHash); +// +// byte[] reqBytes = BinaryEncodingUtils.encode(txContentBlob, TransactionContent.class); +// +// HashDigest reqHash = CryptoUtils.hash(CryptoAlgorithm.SHA256).hash(reqBytes); +// +// txContentBlob.setHash(reqHash); +// +// TxRequestMessage transactionRequest = new TxRequestMessage(txContentBlob); +// +// return transactionRequest; +// } + +// private void checkConsensusFinish() { +// BftsmartCommitBlockSettings commitBlockSettings = ((BftsmartServerSettings)serverSettings).getConsensusSettings().getCommitBlockSettings(); +// int txSize = commitBlockSettings.getTxSizePerBlock(); +// long maxDelay = commitBlockSettings.getMaxDelayMilliSecondsPerBlock(); +// +// long currIndex = txIndex.incrementAndGet(); +// if (currIndex == txSize) { +// txIndex.set(0); +// this.blockIndex.getAndIncrement(); +// sendCommitExecutors.execute(()-> { +// sendCommitMessage(); +// }); +// } else if (currIndex == 1) { +//// System.out.printf("checkConsensusFinish schedule blockIndex = %s \r\n", this.blockIndex.get()); +// timerEexecutorService.schedule(timeTask(this.blockIndex.get()), maxDelay, TimeUnit.MILLISECONDS); +// } +// +// return; +// } + +// @Override +// public byte[][] appExecuteBatch(byte[][] commands, MessageContext[] msgCtxs, boolean fromConsensus, List replyList) { +// +// if (!checkLeaderId(msgCtxs)) { +// throw new IllegalArgumentException(); +// } +// +// boolean isLeader = (msgCtxs[0].getLeader() == getId()); +// +// if (isLeader) { +// for (int i = 0; i < commands.length; i++) { +// byte[] wrapMsg = commands[i]; +// byte[] type = new byte[4]; +// byte[] msg= new byte[wrapMsg.length - 4]; +// +// System.arraycopy(wrapMsg, 0, type, 0, 4); +// System.arraycopy(wrapMsg, 4, msg, 0, wrapMsg.length - 4); +// +// MessageContext messageContext = msgCtxs[i]; +// ReplyContextMessage replyContextMessage = replyList.get(i); +// replyContextMessage.setMessageContext(messageContext); +// +// if (batchId == null) { +// batchId = messageHandle.beginBatch(realmName); +// } +// +// int msgType = BytesUtils.readInt(new ByteArrayInputStream(type)); +// +// if (msgType == 0) { +// +// //only leader do it +// checkConsensusFinish(); +// //normal message process +// normalMsgProcess(replyContextMessage, msg, realmName, batchId); +// } +// if (!leader_has_makedicision) { +// if (msgType == 1) { +// LOGGER.error("Error occurred on appExecuteBatch msg process, leader confilicting error!"); +// } +// +// if (commit_block_condition) { +// leader_has_makedicision = true; +// +//// sendCommitExecutors.execute(() -> { +// commit_block_condition = false; +// LOGGER.info("Txcount execute commit block!"); +// sendCommitMessage(); +//// }); +// +// } +// } else if (msgType == 1) { +// //commit block message +// commitMsgProcess(replyContextMessage, realmName, batchId); +// leader_has_makedicision = false; +// sendReplyMessage(); +// } +// } +// } else { +// for (int i = 0; i < commands.length; i++) { +// byte[] wrapMsg = commands[i]; +// byte[] type = new byte[4]; +// byte[] msg= new byte[wrapMsg.length - 4]; +// +// System.arraycopy(wrapMsg, 0, type, 0, 4); +// System.arraycopy(wrapMsg, 4, msg, 0, wrapMsg.length - 4); +// +// MessageContext messageContext = msgCtxs[i]; +// ReplyContextMessage replyContextMessage = replyList.get(i); +// replyContextMessage.setMessageContext(messageContext); +// +// if (batchId == null) { +// batchId = messageHandle.beginBatch(realmName); +// } +// +// int msgType = BytesUtils.readInt(new ByteArrayInputStream(type)); +// +// if (msgType == 0) { +// //normal message +// normalMsgProcess(replyContextMessage, msg, realmName, batchId); +// } else if (msgType == 1) { +// // commit block message +// commitMsgProcess(replyContextMessage, realmName, batchId); +// sendReplyMessage(); +// } +// } +// } +// +// return null; +// } + @Override public byte[][] appExecuteBatch(byte[][] commands, MessageContext[] msgCtxs, boolean fromConsensus, List replyList) { if (replyList == null || replyList.size() == 0) { throw new IllegalArgumentException(); } + + // todo 此部分需要重新改造 /** * 默认BFTSmart接口提供的commands是一个或多个共识结果的顺序集合 @@ -227,6 +501,52 @@ public class BftsmartNodeServer extends DefaultRecoverable implements NodeServer if (!manageConsensusCmds.isEmpty()) { blockAndReply(manageConsensusCmds, manageReplyMsgs); } + + +//// if (!checkLeaderId(msgCtxs)) { +//// throw new IllegalArgumentException(); +//// } +// +// if (replyList == null || replyList.size() == 0) { +// throw new IllegalArgumentException(); +// } +// +// for (int i = 0; i < commands.length; i++) { +// byte[] wrapMsg = commands[i]; +// byte[] type = new byte[4]; +// byte[] msg= new byte[wrapMsg.length - 4]; +// // batch messages, maybe in different consensus instance, leader also maybe different +// boolean isLeader = (msgCtxs[i].getLeader() == getId()); +// +// System.arraycopy(wrapMsg, 0, type, 0, 4); +// System.arraycopy(wrapMsg, 4, msg, 0, wrapMsg.length - 4); +// +// MessageContext messageContext = msgCtxs[i]; +// ReplyContextMessage replyContextMessage = replyList.get(i); +// replyContextMessage.setMessageContext(messageContext); +// +// if (batchId == null) { +// batchId = messageHandle.beginBatch(realmName); +// } +// +// int msgType = BytesUtils.readInt(new ByteArrayInputStream(type)); +// +// if (msgType == 0) { +// +// //only leader do it +// if (isLeader) { +// checkConsensusFinish(); +// } +// //normal message process +// normalMsgProcess(replyContextMessage, msg, realmName, batchId); +// } +// else if (msgType == 1) { +// //commit block message +// commitMsgProcess(replyContextMessage, realmName, batchId); +// sendReplyMessage(); +// } +// } + return null; } @@ -274,6 +594,46 @@ public class BftsmartNodeServer extends DefaultRecoverable implements NodeServer }); } +// private void sendReplyMessage() { +// for (ReplyContextMessage msg: replyContextMessages.keySet()) { +// byte[] reply = replyContextMessages.get(msg).get(); +// msg.setReply(reply); +// TOMMessage request = msg.getTomMessage(); +// ReplyContext replyContext = msg.getReplyContext(); +// request.reply = new TOMMessage(replyContext.getId(), request.getSession(), request.getSequence(), +// request.getOperationId(), msg.getReply(), replyContext.getCurrentViewId(), +// request.getReqType()); +// +// if (replyContext.getNumRepliers() > 0) { +// bftsmart.tom.util.Logger.println("(ServiceReplica.receiveMessages) sending reply to " +// + request.getSender() + " with sequence number " + request.getSequence() +// + " and operation ID " + request.getOperationId() + " via ReplyManager"); +// replyContext.getRepMan().send(request); +// } else { +// bftsmart.tom.util.Logger.println("(ServiceReplica.receiveMessages) sending reply to " +// + request.getSender() + " with sequence number " + request.getSequence() +// + " and operation ID " + request.getOperationId()); +// replyContext.getReplier().manageReply(request, msg.getMessageContext()); +// // cs.send(new int[]{request.getSender()}, request.reply); +// } +// } +// replyContextMessages.clear(); +// } + +// private Runnable timeTask(final long currBlockIndex) { +// Runnable task = () -> { +// boolean isAdd = this.blockIndex.compareAndSet(currBlockIndex, currBlockIndex + 1); +// if (isAdd) { +// LOGGER.info("TimerTask execute commit block! "); +// this.txIndex.set(0); +// timerEexecutorService.execute(()-> { +// sendCommitMessage(); +// }); +// } +// }; +// return task; +// } + //notice public byte[] getSnapshot() { LOGGER.debug("------- GetSnapshot...[replica.id=" + this.getId() + "]"); @@ -283,6 +643,9 @@ public class BftsmartNodeServer extends DefaultRecoverable implements NodeServer for (StateHandle stateHandle : stateHandles) { // TODO: 测试代码; return stateHandle.takeSnapshot(); + + // byte[] state = stateHandle.takeSnapshot(); + // BytesEncoding.writeInNormal(state, out); } return out.toByteArray(); } @@ -349,7 +712,34 @@ public class BftsmartNodeServer extends DefaultRecoverable implements NodeServer } } } - + +// private static class ActionRequestExtend { +// +// +// ReplyContextMessage replyContextMessage; +// +// private byte[] message; +// +// private ActionRequest actionRequest; +// +// public ActionRequestExtend(byte[] message) { +// this.message = message; +// actionRequest = BinaryEncodingUtils.decode(message); +// } +// +// public byte[] getMessage() { +// return message; +// } +// +// public ReplyContextMessage getReplyContextMessage() { +// return replyContextMessage; +// } +// +// public ActionRequest getActionRequest() { +// return actionRequest; +// } +// } + enum Status { STARTING, diff --git a/source/consensus/consensus-bftsmart/src/test/java/test/com/jd/blockchain/consensus/bftsmart/proxyClientTest.java b/source/consensus/consensus-bftsmart/src/test/java/test/com/jd/blockchain/consensus/bftsmart/proxyClientTest.java index 10462343..5c6d0d52 100644 --- a/source/consensus/consensus-bftsmart/src/test/java/test/com/jd/blockchain/consensus/bftsmart/proxyClientTest.java +++ b/source/consensus/consensus-bftsmart/src/test/java/test/com/jd/blockchain/consensus/bftsmart/proxyClientTest.java @@ -8,7 +8,7 @@ import com.jd.blockchain.consensus.bftsmart.client.BftsmartMessageService; import com.jd.blockchain.consensus.bftsmart.service.BftsmartNodeServer; import com.jd.blockchain.consensus.bftsmart.service.BftsmartServerSettingConfig; import com.jd.blockchain.consensus.service.ServerSettings; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeyPair; import com.jd.blockchain.utils.PropertiesUtils; diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentification.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentification.java index 73198cb5..4f7c34d7 100644 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentification.java +++ b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentification.java @@ -1,9 +1,9 @@ package com.jd.blockchain.consensus; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.consts.TypeCodes; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.utils.ValueType; diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentifications.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentifications.java index 0b620074..8d23135a 100644 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentifications.java +++ b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIdentifications.java @@ -8,9 +8,9 @@ */ package com.jd.blockchain.consensus; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; /** * diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIncomingSettings.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIncomingSettings.java index d0644443..3585c613 100644 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIncomingSettings.java +++ b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ClientIncomingSettings.java @@ -1,8 +1,8 @@ package com.jd.blockchain.consensus; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.ValueType; /** diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusSettings.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusSettings.java index a2d99ad3..b7849625 100644 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusSettings.java +++ b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusSettings.java @@ -1,8 +1,8 @@ package com.jd.blockchain.consensus; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; /** * 共识网络的配置参数; diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/NodeSettings.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/NodeSettings.java index 31ae9a36..a0c7ee66 100644 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/NodeSettings.java +++ b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/NodeSettings.java @@ -1,9 +1,9 @@ package com.jd.blockchain.consensus; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.consts.TypeCodes; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.utils.ValueType; /** diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionRequest.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionRequest.java index b88fc0f5..694d7326 100644 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionRequest.java +++ b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionRequest.java @@ -1,8 +1,8 @@ package com.jd.blockchain.consensus.action; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.ValueType; @DataContract(code= TypeCodes.CONSENSUS_ACTION_REQUEST) diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionResponse.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionResponse.java index 8e388aa2..1ba34d01 100644 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionResponse.java +++ b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionResponse.java @@ -1,8 +1,8 @@ package com.jd.blockchain.consensus.action; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.ValueType; @DataContract(code= TypeCodes.CONSENSUS_ACTION_RESPONSE) diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ClientSettings.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ClientSettings.java index 5551e18a..9c4fa89f 100644 --- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ClientSettings.java +++ b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/client/ClientSettings.java @@ -1,7 +1,7 @@ package com.jd.blockchain.consensus.client; import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; /** * 共识客户端的配置参数; diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/MsgQueueConsensusSettingsBuilder.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/MsgQueueConsensusSettingsBuilder.java index 025ffcef..839be6e0 100644 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/MsgQueueConsensusSettingsBuilder.java +++ b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/MsgQueueConsensusSettingsBuilder.java @@ -20,7 +20,7 @@ import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; import com.jd.blockchain.consensus.mq.settings.MsgQueueNetworkSettings; import com.jd.blockchain.consensus.mq.settings.MsgQueueNodeSettings; import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.PropertiesUtils; diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueClientFactory.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueClientFactory.java index 2158f223..63028e85 100644 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueClientFactory.java +++ b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueClientFactory.java @@ -20,8 +20,8 @@ import com.jd.blockchain.consensus.mq.settings.MsgQueueClientIncomingSettings; import com.jd.blockchain.consensus.mq.settings.MsgQueueClientSettings; import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; import com.jd.blockchain.crypto.CryptoUtils; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.asymmetric.SignatureFunction; diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueClientIdentification.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueClientIdentification.java index b34b70b3..e0184606 100644 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueClientIdentification.java +++ b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/client/MsgQueueClientIdentification.java @@ -11,7 +11,7 @@ package com.jd.blockchain.consensus.mq.client; import com.jd.blockchain.consensus.ClientIdentification; import com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider; import com.jd.blockchain.crypto.CryptoUtils; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.asymmetric.SignatureFunction; diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueClientConfig.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueClientConfig.java index 5fec7a69..78f9f7c3 100644 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueClientConfig.java +++ b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueClientConfig.java @@ -11,7 +11,7 @@ package com.jd.blockchain.consensus.mq.config; import com.jd.blockchain.consensus.mq.settings.MsgQueueClientSettings; import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; import com.jd.blockchain.consensus.mq.settings.MsgQueueNetworkSettings; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; /** * diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueClientIncomingConfig.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueClientIncomingConfig.java index 8e947f26..967c03de 100644 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueClientIncomingConfig.java +++ b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueClientIncomingConfig.java @@ -13,7 +13,7 @@ import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider; import com.jd.blockchain.consensus.mq.settings.MsgQueueClientIncomingSettings; import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import java.lang.reflect.Method; diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueConsensusConfig.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueConsensusConfig.java index 526ac603..9ece2285 100644 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueConsensusConfig.java +++ b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueConsensusConfig.java @@ -11,7 +11,7 @@ package com.jd.blockchain.consensus.mq.config; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.consensus.NodeSettings; import com.jd.blockchain.consensus.mq.settings.*; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import java.lang.reflect.Method; import java.lang.reflect.Proxy; diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueNodeConfig.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueNodeConfig.java index c7cc03d7..9e9506ed 100644 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueNodeConfig.java +++ b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/config/MsgQueueNodeConfig.java @@ -9,7 +9,7 @@ package com.jd.blockchain.consensus.mq.config; import com.jd.blockchain.consensus.mq.settings.MsgQueueNodeSettings; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; /** * peer节点IP diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueConsensusManageService.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueConsensusManageService.java index d33c462e..1c6dc677 100644 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueConsensusManageService.java +++ b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/server/MsgQueueConsensusManageService.java @@ -17,7 +17,7 @@ import com.jd.blockchain.consensus.mq.config.MsgQueueConsensusConfig; import com.jd.blockchain.consensus.mq.settings.MsgQueueClientIncomingSettings; import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; import com.jd.blockchain.crypto.CryptoUtils; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureFunction; import java.lang.reflect.Proxy; diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueBlockSettings.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueBlockSettings.java index 95ba2000..e2edaa7b 100644 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueBlockSettings.java +++ b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueBlockSettings.java @@ -8,9 +8,9 @@ */ package com.jd.blockchain.consensus.mq.settings; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.ValueType; /** diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueClientIncomingSettings.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueClientIncomingSettings.java index 1eeffa91..e0cb03d1 100644 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueClientIncomingSettings.java +++ b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueClientIncomingSettings.java @@ -8,12 +8,12 @@ */ package com.jd.blockchain.consensus.mq.settings; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; import com.jd.blockchain.consensus.ClientIncomingSettings; import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.consts.TypeCodes; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.utils.ValueType; /** diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueConsensusSettings.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueConsensusSettings.java index d24c5422..d4e9e648 100644 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueConsensusSettings.java +++ b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueConsensusSettings.java @@ -8,11 +8,11 @@ */ package com.jd.blockchain.consensus.mq.settings; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.consensus.mq.config.MsgQueueBlockConfig; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.Property; import com.jd.blockchain.utils.ValueType; diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNetworkSettings.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNetworkSettings.java index d512c32b..fea1690e 100644 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNetworkSettings.java +++ b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNetworkSettings.java @@ -8,9 +8,9 @@ */ package com.jd.blockchain.consensus.mq.settings; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.ValueType; /** diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNodeSettings.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNodeSettings.java index 784a1708..acfeb22b 100644 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNodeSettings.java +++ b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNodeSettings.java @@ -8,9 +8,9 @@ */ package com.jd.blockchain.consensus.mq.settings; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.consensus.NodeSettings; +import com.jd.blockchain.consts.TypeCodes; /** * diff --git a/source/contract/contract-compile/pom.xml b/source/contract/contract-compile/pom.xml index e6c67b88..67eec97b 100644 --- a/source/contract/contract-compile/pom.xml +++ b/source/contract/contract-compile/pom.xml @@ -5,7 +5,7 @@ contract com.jd.blockchain - 0.8.3.RELEASE + 0.8.2.RELEASE 4.0.0 @@ -100,15 +100,6 @@ - - - org.apache.maven.plugins - maven-deploy-plugin - 2.8.2 - - true - - diff --git a/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract1.java b/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract1.java index 8fae2439..2926a757 100644 --- a/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract1.java +++ b/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract1.java @@ -2,7 +2,7 @@ package com.jd.blockchain.contract; import com.jd.blockchain.contract.model.*; import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.*; import com.jd.blockchain.utils.BaseConstant; @@ -14,23 +14,23 @@ import java.util.Map; import java.util.Set; /** - * mock the smart contract; + * 模拟用智能合约; */ @Contract public class AssetContract1 implements EventProcessingAwire { // private static final Logger LOGGER = LoggerFactory.getLogger(AssetContract1.class); - // the address of asset manager; + // 资产管理账户的地址; // private static String ASSET_ADDRESS = "2njZBNbFQcmKd385DxVejwSjy4driRzf9Pk"; private static String ASSET_ADDRESS = ""; - //account address; + //账户地址; private static final String ACCOUNT_ADDRESS = "accountAddress"; String contractAddress = "2njZBNbFQcmKd385DxVejwSjy4driRzf9Pk"; String userPubKeyVal = "this is user's pubKey"; - // the key of save asset; + // 保存资产总数的键; private static final String KEY_TOTAL = "TOTAL"; - // contractEvent context; + // 合约事件上下文; private ContractEventContext eventContext; private Object eventContextObj; private byte[] eventContextBytes; @@ -59,7 +59,7 @@ public class AssetContract1 implements EventProcessingAwire { } /** - * issue-asset; + * 发行资产; * @param contractEventContext * @throws Exception */ @@ -83,6 +83,7 @@ public class AssetContract1 implements EventProcessingAwire { // checkAllOwnersAgreementPermission(); + // 新发行的资产数量;在传递过程中都改为字符串,需要反转; // long amount = BytesUtils.toLong(args[0]); if (amount < 0) { @@ -92,77 +93,83 @@ public class AssetContract1 implements EventProcessingAwire { return; } + // 校验持有者账户的有效性; // BlockchainAccount holderAccount = eventContext.getLedger().getAccount(currentLedgerHash(), assetHolderAddress); // if (holderAccount == null) { // throw new ContractError("The holder is not exist!"); // } + // 查询当前值; HashDigest hashDigest = eventContext.getCurrentLedgerHash(); + //赋值;mock的对象直接赋值无效; // eventContext.getLedger().dataAccount(ACCOUNT_ADDRESS).set(KEY_TOTAL,"total new dataAccount".getBytes(),2); // KVDataEntry[] kvEntries = eventContext.getLedger().getDataEntries(hashDigest, ASSET_ADDRESS, KEY_TOTAL,assetHolderAddress); // assert ByteArray.toHex("total new dataAccount".getBytes()).equals(kvEntries[0].getValue()) // && ByteArray.toHex("abc new dataAccount".getBytes()).equals(kvEntries[1].getValue()) : -// "getDataEntries() test,expect!=actual;"; +// "getDataEntries() test,期望值!=设定值;"; KVDataEntry[] kvEntries = eventContext.getLedger().getDataEntries(hashDigest, ASSET_ADDRESS, KEY_TOTAL,assetHolderAddress,"ledgerHash"); //,"latestBlockHash" + //当前mock设定值为:TOTAL="total value,dataAccount";abc="abc value,dataAccount"; assert ByteArray.toHex("total value,dataAccount".getBytes()).equals(kvEntries[0].getValue()) && ByteArray.toHex("abc value,dataAccount".getBytes()).equals(kvEntries[1].getValue()) : - "getDataEntries() test,expect=actual;"; + "getDataEntries() test,期望值=设定值;"; - //get the latest block; + //高度只是一个模拟,看结果是否与期望相同;//get the latest block; LedgerBlock ledgerBlock = eventContext.getLedger().getBlock(hashDigest, eventContext.getLedger().getLedger(hashDigest).getLatestBlockHeight()); // assert "zhaogw".equals(new String(ledgerBlock.getLedgerHash().getRawDigest())) && // "lisi".equals(new String(ledgerBlock.getPreviousHash().getRawDigest())) : -// "getBlock(hash,long) test,expect!=actual;"; +// "getBlock(hash,long) test,期望值!=设定值;"; assert ByteArray.toHex(eventContext.getCurrentLedgerHash().getRawDigest()).equals(kvEntries[2].getValue()) && ledgerBlock.getPreviousHash().toBase58().equals(previousBlockHash) : - "getPreviousHash() test,expect!=acutal;"; + "getPreviousHash() test,期望值!=设定值;"; //模拟:根据hash来获得区块; LedgerBlock ledgerBlock1 = eventContext.getLedger().getBlock(hashDigest,ledgerBlock.getHash()); assert eventContext.getLedger().getTransactionCount(hashDigest,1) == 2 : - "getTransactionCount(),expect!=acutal"; + "getTransactionCount(),期望值!=设定值"; // assert "zhaogw".equals(new String(ledgerBlock1.getLedgerHash().getRawDigest())) && // "lisi".equals(new String(ledgerBlock1.getPreviousHash().getRawDigest())) : -// "getBlock(hash,blockHash) test,expect!=acutal;"; +// "getBlock(hash,blockHash) test,期望值!=设定值;"; assert ByteArray.toHex(eventContext.getCurrentLedgerHash().getRawDigest()).equals(kvEntries[2].getValue()) && ledgerBlock1.getPreviousHash().toBase58().equals(previousBlockHash) : - "getBlock(hash,blockHash) test,expect!=acutal;"; + "getBlock(hash,blockHash) test,期望值!=设定值;"; assert ASSET_ADDRESS.equals(eventContext.getLedger().getDataAccount(hashDigest,ASSET_ADDRESS).getAddress()) : - "getDataAccount(hash,address), expect!=acutal"; + "getDataAccount(hash,address), 期望值!=设定值"; + //mock user()等;内部赋值,验证外部是否能够得到; PubKey pubKey = new PubKey(CryptoAlgorithm.ED25519, pubKeyVal.getBytes()); BlockchainIdentity contractID = new BlockchainIdentityData(pubKey); // assert contractID == contractEventContext.getLedger().dataAccounts().register(contractID).getAccountID() : -// "dataAccounts(),expect!=acutal"; +// "dataAccounts(),期望值!=设定值"; contractEventContext.getLedger().dataAccounts().register(contractID); contractEventContext.getLedger().dataAccount(contractID.getAddress()). set(KEY_TOTAL,"hello".getBytes(),-1).getOperation(); assert userAddress.equals(eventContext.getLedger().getUser(hashDigest,userAddress).getAddress()) : - "getUser(hash,address), expect!=acutal"; + "getUser(hash,address), 期望值!=设定值"; assert contractAddress.equals(eventContext.getLedger().getContract(hashDigest,contractAddress).getAddress()) : - "getContract(hash,address), expect!=acutal"; + "getContract(hash,address), 期望值!=设定值"; PubKey userPubKey = new PubKey(CryptoAlgorithm.ED25519, userPubKeyVal.getBytes()); BlockchainIdentity userBlockId = new BlockchainIdentityData(userPubKey); contractEventContext.getLedger().users().register(userBlockId); // txRootHash + //此方法未实现;需要相关人员进一步完善; // eventContext.getLedger().getTransactions(hashDigest,ledgerBlock1.getHash(),0,10); HashDigest txHashDigest = new HashDigest(Base58Utils.decode(txHash)); LedgerTransaction ledgerTransactions = eventContext.getLedger().getTransactionByContentHash(hashDigest,txHashDigest); - assert ledgerTransactions != null : "getTransactionByContentHash(hashDigest,txHashDigest),expect!=acutal"; + assert ledgerTransactions != null : "getTransactionByContentHash(hashDigest,txHashDigest),期望值!=设定值"; System.out.println("issue(),over."); } @@ -185,6 +192,9 @@ public class AssetContract1 implements EventProcessingAwire { System.out.println("transfer(),over."); } + /** + * 只有全部的合约拥有者同意才能通过校验; + */ private void checkAllOwnersAgreementPermission() { Set owners = eventContext.getContracOwners(); Set requestors = eventContext.getTxSigners(); @@ -204,6 +214,11 @@ public class AssetContract1 implements EventProcessingAwire { } } + /** + * 校验指定的账户是否签署了当前交易; + * + * @param address + */ private void checkSignerPermission(String address) { Set requestors = eventContext.getTxSigners(); for (BlockchainIdentity r : requestors) { diff --git a/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract2.java b/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract2.java index 247e36e8..44c3bb4c 100644 --- a/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract2.java +++ b/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract2.java @@ -6,7 +6,7 @@ import com.jd.blockchain.ledger.KVDataEntry; import com.jd.blockchain.utils.BaseConstant; /** - * mock the smart contract; + * 模拟用智能合约; */ @Contract public class AssetContract2 implements EventProcessingAwire { @@ -31,11 +31,12 @@ public class AssetContract2 implements EventProcessingAwire { HashDigest hashDigest = eventContext.getCurrentLedgerHash(); KVDataEntry[] kvEntries = eventContext.getLedger().getDataEntries(hashDigest, contractDataAddress, KEY_TOTAL,LEDGER_HASH); //,"latestBlockHash" + //当前mock设定值为:TOTAL="total value,dataAccount";abc="abc value,dataAccount"; // // assert ByteArray.toHex("total value,dataAccount".getBytes()).equals(kvEntries[0].getValue()) // && ByteArray.toHex("abc value,dataAccount".getBytes()).equals(kvEntries[1].getValue()) : -// "getDataEntries() test,expect=actual;"; +// "getDataEntries() test,期望值=设定值;"; System.out.println("in dataSet,KEY_TOTAL="+new String(kvEntries[0].getValue().toString())); System.out.println("in dataSet,LEDGER_HASH="+new String(kvEntries[1].getValue().toString())); } diff --git a/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract3.java b/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract3.java index acae4716..d6c8b190 100644 --- a/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract3.java +++ b/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract3.java @@ -4,8 +4,8 @@ import com.jd.blockchain.contract.model.*; import com.jd.blockchain.utils.BaseConstant; /** - * mock the smart contract; - * Do only the simplest addition operation. + * 模拟用智能合约; + * 只做最简单的加法运算; */ @Contract public class AssetContract3 implements EventProcessingAwire { diff --git a/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract4.java b/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract4.java index 0b2766b0..0bb265bb 100644 --- a/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract4.java +++ b/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract4.java @@ -8,9 +8,8 @@ import com.jd.blockchain.utils.BaseConstant; import com.jd.blockchain.utils.io.ByteArray; /** - * mock the smart contract; - * The test takes data from the chain and compares it with the expected value; - * the value of param1Val should be consistent with that of Integration Test; + * 模拟用智能合约; + * 测试从链中取数据,然后对比是否与预定值一致;param1Val 的值要与IntegrationTest中保持一致; */ @Contract public class AssetContract4 implements EventProcessingAwire { @@ -32,6 +31,7 @@ public class AssetContract4 implements EventProcessingAwire { ",contractDataAddress= "+contractDataAddress); BlockchainKeyPair dataAccount = BlockchainKeyGenerator.getInstance().generate(); + //TODO:register牵扯到账本中的事务处理,需要优化; // contractEventContext.getLedger().dataAccounts().register(dataAccount.getIdentity()); // contractEventContext.getLedger().dataAccount(dataAccount.getAddress()). // set(param1,param1Val.getBytes(),-1).getOperation(); @@ -55,9 +55,9 @@ public class AssetContract4 implements EventProcessingAwire { KVDataEntry[] kvEntries = eventContext.getLedger().getDataEntries(eventContext.getCurrentLedgerHash(), contractDataAddress, param1); if (ByteArray.toHex(param1Val.getBytes()).equals(kvEntries[0].getValue())){ - System.out.println("getDataEntries() test,expect==actual;"); + System.out.println("getDataEntries() test,期望值==设定值;"); } else { - System.out.println("getDataEntries() test,expect==actual;"); + System.out.println("getDataEntries() test,期望值!=设定值;"); } } diff --git a/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract5.java b/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract5.java index bf3d8def..de6fe3cc 100644 --- a/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract5.java +++ b/source/contract/contract-compile/src/main/java/com/jd/blockchain/contract/AssetContract5.java @@ -4,8 +4,8 @@ import com.jd.blockchain.contract.model.*; import com.jd.blockchain.utils.BaseConstant; /** - * mock the smart contract; - * Do only the simplest addition operation. + * 模拟用智能合约; + * 只做最简单的加法运算; */ @Contract public class AssetContract5 implements EventProcessingAwire { diff --git a/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/ContractEngine.java b/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/ContractEngine.java index fe6f6a7a..09f7b416 100644 --- a/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/ContractEngine.java +++ b/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/ContractEngine.java @@ -1,7 +1,7 @@ package com.jd.blockchain.contract; /** - * contract engine. + * 合约引擎; * * @author huanghaiquan * @@ -9,9 +9,9 @@ package com.jd.blockchain.contract; public interface ContractEngine { /** - * Returns the contract code for the specified address;
+ * 返回指定地址的合约代码;
* - * If not, return null; + * 如果不存在,则返回 null; * * @param address * @return @@ -19,9 +19,9 @@ public interface ContractEngine { ContractCode getContract(String address, long version); /** - * Load contract code;
+ * 装入合约代码;
* - * If it already exists, it returns the existing instance directly. + * 如果已经存在,则直接返回已有实例; * * @param address * @param code diff --git a/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/ContractServiceProvider.java b/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/ContractServiceProvider.java index 1cc94b5e..ae8a0d00 100644 --- a/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/ContractServiceProvider.java +++ b/source/contract/contract-framework/src/main/java/com/jd/blockchain/contract/ContractServiceProvider.java @@ -5,7 +5,7 @@ public interface ContractServiceProvider { String getName(); /** - * Return the contract code execution engine instance; + * 返回合约代码执行引擎实例; * * @return */ diff --git a/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/JavaContractCode.java b/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/JavaContractCode.java index 282f06c6..147b6a26 100644 --- a/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/JavaContractCode.java +++ b/source/contract/contract-jvm/src/main/java/com/jd/blockchain/contract/jvm/JavaContractCode.java @@ -52,32 +52,31 @@ public class JavaContractCode implements ContractCode { } class ContractThread implements Runnable{ - @Override public void run(){ LOGGER.info("ContractThread execute()."); try { - //Perform pretreatment; + //执行预处理; long startTime = System.currentTimeMillis(); String contractClassName = codeModule.getMainClass(); Class myClass = codeModule.loadClass(contractClassName); - Object contractMainClassObj = myClass.newInstance(); + Object contractMainClassObj = myClass.newInstance();//合约主类生成的类实例; Method beforeMth_ = myClass.getMethod("beforeEvent",codeModule.loadClass(ContractEventContext.class.getName())); ReflectionUtils.invokeMethod(beforeMth_,contractMainClassObj,contractEventContext); - LOGGER.info("beforeEvent,spend time:"+(System.currentTimeMillis()-startTime)); + LOGGER.info("beforeEvent,耗时:"+(System.currentTimeMillis()-startTime)); Method eventMethod = this.getMethodByAnno(contractMainClassObj,contractEventContext.getEvent()); startTime = System.currentTimeMillis(); ReflectionUtils.invokeMethod(eventMethod,contractMainClassObj,contractEventContext); - LOGGER.info("execute contract,spend time:"+(System.currentTimeMillis()-startTime)); + LOGGER.info("合约执行,耗时:"+(System.currentTimeMillis()-startTime)); Method mth2 = myClass.getMethod("postEvent"); startTime = System.currentTimeMillis(); ReflectionUtils.invokeMethod(mth2,contractMainClassObj); - LOGGER.info("postEvent,spend time:"+(System.currentTimeMillis()-startTime)); + LOGGER.info("postEvent,耗时:"+(System.currentTimeMillis()-startTime)); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (Exception e) { @@ -85,7 +84,7 @@ public class JavaContractCode implements ContractCode { } } - //get the relation between the methods and annotations + //得到当前类中相关方法和注解对应关系; Method getMethodByAnno(Object classObj, String eventName){ Class c = classObj.getClass(); Class contractEventClass = null; @@ -100,9 +99,9 @@ public class JavaContractCode implements ContractCode { for(int i = 0;i - 4.0.0 - + + 4.0.0 + com.jd.blockchain crypto - 0.9.0-SNAPSHOT + 0.9.0-SNAPSHOT - crypto-adv + crypto-adv + com.jd.blockchain + crypto-sm + ${project.version} + + org.bouncycastle bcprov-jdk15on @@ -48,28 +55,14 @@ org.mockito mockito-core - 1.10.19 test - - com.jd.blockchain - crypto-framework - ${project.version} - compile - - - + + com.jd.blockchain + crypto-framework + ${project.version} + compile + - - - - org.apache.maven.plugins - maven-deploy-plugin - 2.8.2 - - true - - - - + \ No newline at end of file diff --git a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/ecvrf/VRF.java b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/ecvrf/VRF.java index 0fd713ef..45e05083 100644 --- a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/ecvrf/VRF.java +++ b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/ecvrf/VRF.java @@ -1,6 +1,7 @@ package com.jd.blockchain.crypto.ecvrf; +import com.jd.blockchain.crypto.CryptoException; import com.sun.jna.Library; import com.sun.jna.Native; @@ -27,7 +28,9 @@ public class VRF { } // unsupported OS - else throw new IllegalArgumentException("The VRF implementation is not supported in this Operation System!"); + else { + throw new CryptoException("The VRF implementation is not supported in this Operation System!"); + } path = Objects.requireNonNull(VRF.class.getClassLoader().getResource(lib)).getPath(); return path; diff --git a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/EqualVerify.java b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/EqualVerify.java index 7d3dfc61..68393c8c 100644 --- a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/EqualVerify.java +++ b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/EqualVerify.java @@ -1,5 +1,6 @@ package com.jd.blockchain.crypto.mpc; +import com.jd.blockchain.crypto.CryptoException; import com.jd.blockchain.crypto.elgamal.ElGamalUtils; import com.jd.blockchain.utils.io.BytesUtils; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; @@ -56,8 +57,9 @@ public class EqualVerify { public static byte[] responder(int responderInput, byte[] sponsorOutput, byte[] responderEPubKeyBytes, byte[] responderEPrivKeyBytes) { - if (sponsorOutput.length != ELEMENTLENGTH) - throw new IllegalArgumentException("The sponsorOutput' length is not 64!"); + if (sponsorOutput.length != ELEMENTLENGTH) { + throw new CryptoException("The sponsorOutput' length is not 64!"); + } BigInteger responderBigInt = BigInteger.valueOf(responderInput); BigInteger responderEPubKey = new BigInteger(1,responderEPubKeyBytes); @@ -72,8 +74,9 @@ public class EqualVerify { public static boolean sponsorCheck(int sponsorInput, byte[] responderOutput, byte[] sponsorEPrivKeyBytes){ - if (responderOutput.length != 2 * ELEMENTLENGTH) - throw new IllegalArgumentException("The responderOutput's length is not 128!"); + if (responderOutput.length != 2 * ELEMENTLENGTH) { + throw new CryptoException("The responderOutput's length is not 128!"); + } byte[] responderCipherBytes = new byte[ELEMENTLENGTH]; byte[] dhValueBytes = new byte[ELEMENTLENGTH]; @@ -99,9 +102,12 @@ public class EqualVerify { private static byte[] bigIntegerTo64Bytes(BigInteger b){ byte[] tmp = b.toByteArray(); byte[] result = new byte[64]; - if (tmp.length > result.length) - System.arraycopy(tmp, tmp.length-result.length, result, 0, result.length); - else System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); + if (tmp.length > result.length) { + System.arraycopy(tmp, tmp.length - result.length, result, 0, result.length); + } + else { + System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); + } return result; } } diff --git a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/IntCompare.java b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/IntCompare.java index 68afd2e5..f6ff71c6 100644 --- a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/IntCompare.java +++ b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/IntCompare.java @@ -1,5 +1,6 @@ package com.jd.blockchain.crypto.mpc; +import com.jd.blockchain.crypto.CryptoException; import com.jd.blockchain.crypto.elgamal.ElGamalUtils; import com.jd.blockchain.utils.io.BytesUtils; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; @@ -67,13 +68,15 @@ public class IntCompare { public static byte[][] responder(int responderInt, byte[][] cipherArray, byte[] pubKeyBytes){ - if (cipherArray.length != 2 * INTLENGTH) - throw new IllegalArgumentException("The cipherArray has wrong format!"); + if (cipherArray.length != 2 * INTLENGTH) { + throw new CryptoException("The cipherArray has wrong format!"); + } int i,j; for (i = 0; i < cipherArray.length; i++){ - if(cipherArray[i].length != CIPHERLENGTH) - throw new IllegalArgumentException("The cipherArray has wrong format!"); + if(cipherArray[i].length != CIPHERLENGTH) { + throw new CryptoException("The cipherArray has wrong format!"); + } } String[] responderStrSet = encoding(responderInt, false); @@ -131,16 +134,18 @@ public class IntCompare { public static int sponsorOutput(byte[][] aggregatedCipherArray, byte[] privKeyBytes){ - if (aggregatedCipherArray.length != INTLENGTH) - throw new IllegalArgumentException("The aggregatedCipherArray has wrong format!"); + if (aggregatedCipherArray.length != INTLENGTH) { + throw new CryptoException("The aggregatedCipherArray has wrong format!"); + } int i; byte[] plaintext; for (i = 0; i < aggregatedCipherArray.length; i++){ - if(aggregatedCipherArray[i].length != CIPHERLENGTH) - throw new IllegalArgumentException("The aggregatedCipherArray has wrong format!"); + if(aggregatedCipherArray[i].length != CIPHERLENGTH) { + throw new CryptoException("The aggregatedCipherArray has wrong format!"); + } plaintext = ElGamalUtils.decrypt(aggregatedCipherArray[i], privKeyBytes); @@ -186,8 +191,9 @@ public class IntCompare { private static String to32BinaryString(int integer) { - if (integer < 0) - throw new IllegalArgumentException("integer must be non-negative!"); + if (integer < 0) { + throw new CryptoException("integer must be non-negative!"); + } int i; String str = Integer.toBinaryString(integer); @@ -204,16 +210,19 @@ public class IntCompare { * @return the next pseudorandom, uniformly distributed {@code int} * value between min (inclusive) and max (inclusive) * from this random number generator's sequence - * @throws IllegalArgumentException if min is not non-negative, + * @throws CryptoException if min is not non-negative, * max is not positive, or min is bigger than max */ private static int randInt(int min, int max) { - if (min < 0) - throw new IllegalArgumentException("min must be non-negative!"); - if (max <= 0) - throw new IllegalArgumentException("max must be positive!"); - if (min > max) - throw new IllegalArgumentException("min must not be greater than max"); + if (min < 0) { + throw new CryptoException("min must be non-negative!"); + } + if (max <= 0) { + throw new CryptoException("max must be positive!"); + } + if (min > max) { + throw new CryptoException("min must not be greater than max"); + } Random random = new Random(); return random.nextInt(max) % (max - min + 1) + min; @@ -244,23 +253,28 @@ public class IntCompare { private static byte[] bigIntegerTo64Bytes(BigInteger b){ byte[] tmp = b.toByteArray(); byte[] result = new byte[64]; - if (tmp.length > result.length) - System.arraycopy(tmp, tmp.length-result.length, result, 0, result.length); - else System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); + if (tmp.length > result.length) { + System.arraycopy(tmp, tmp.length - result.length, result, 0, result.length); + } + else { + System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); + } return result; } private static BigInteger getLeftBigIntegerFrom128Bytes(byte[] byteArray){ - if (byteArray.length != 128) - throw new IllegalArgumentException("The byteArray's length must be 128!"); + if (byteArray.length != 128) { + throw new CryptoException("The byteArray's length must be 128!"); + } byte[] tmp = new byte[64]; System.arraycopy(byteArray, 0, tmp, 0, tmp.length); return new BigInteger(1, tmp); } private static BigInteger getRightBigIntegerFrom128Bytes(byte[] byteArray){ - if (byteArray.length != 128) - throw new IllegalArgumentException("The byteArray's length must be 128!"); + if (byteArray.length != 128) { + throw new CryptoException("The byteArray's length must be 128!"); + } byte[] tmp = new byte[64]; System.arraycopy(byteArray, 64, tmp, 0, tmp.length); return new BigInteger(1, tmp); diff --git a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/MultiSum.java b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/MultiSum.java index 4a5dcc9c..cb0316d3 100644 --- a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/MultiSum.java +++ b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/mpc/MultiSum.java @@ -1,11 +1,6 @@ package com.jd.blockchain.crypto.mpc; -import com.jd.blockchain.crypto.paillier.KeyPair; -import com.jd.blockchain.crypto.paillier.PaillierUtils; -import com.jd.blockchain.crypto.paillier.PublicKey; -import com.jd.blockchain.crypto.smutils.asymmetric.SM2Utils; -import com.jd.blockchain.crypto.smutils.hash.SM3Utils; -import com.jd.blockchain.utils.io.BytesUtils; +import java.math.BigInteger; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.CipherParameters; @@ -17,7 +12,12 @@ import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.math.ec.ECPoint; import org.bouncycastle.util.encoders.Hex; -import java.math.BigInteger; +import com.jd.blockchain.crypto.paillier.KeyPair; +import com.jd.blockchain.crypto.paillier.PaillierUtils; +import com.jd.blockchain.crypto.paillier.PublicKey; +import com.jd.blockchain.crypto.utils.sm.SM2Utils; +import com.jd.blockchain.crypto.utils.sm.SM3Utils; +import com.jd.blockchain.utils.io.BytesUtils; public class MultiSum { diff --git a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierUtils.java b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierUtils.java index ac14f22b..4c199487 100644 --- a/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierUtils.java +++ b/source/crypto/crypto-adv/src/main/java/com/jd/blockchain/crypto/paillier/PaillierUtils.java @@ -11,9 +11,12 @@ public class PaillierUtils { public static byte[] BigIntegerToLBytes(BigInteger b, int l){ byte[] tmp = b.toByteArray(); byte[] result = new byte[l]; - if (tmp.length > result.length) - System.arraycopy(tmp, tmp.length-result.length, result, 0, result.length); - else System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); + if (tmp.length > result.length) { + System.arraycopy(tmp, tmp.length - result.length, result, 0, result.length); + } + else { + System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); + } return result; } diff --git a/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/ecvrf/VRFTest.java b/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/ecvrf/VRFTest.java index 5c109651..2ee66422 100644 --- a/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/ecvrf/VRFTest.java +++ b/source/crypto/crypto-adv/src/test/java/test/com/jd/blockchain/crypto/ecvrf/VRFTest.java @@ -1,5 +1,6 @@ package test.com.jd.blockchain.crypto.ecvrf; +import com.jd.blockchain.crypto.CryptoException; import com.jd.blockchain.crypto.ecvrf.VRF; import org.junit.Test; @@ -66,7 +67,7 @@ public class VRFTest { } else { assertNotNull(actualEx); - Class expectedException = IllegalArgumentException.class; + Class expectedException = CryptoException.class; assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); } } diff --git a/source/crypto/crypto-classic/pom.xml b/source/crypto/crypto-classic/pom.xml new file mode 100644 index 00000000..bd59aeb8 --- /dev/null +++ b/source/crypto/crypto-classic/pom.xml @@ -0,0 +1,20 @@ + + 4.0.0 + + com.jd.blockchain + crypto + 0.9.0-SNAPSHOT + + crypto-classic + + + + com.jd.blockchain + crypto-framework + ${project.version} + + + + \ No newline at end of file diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/AESEncryptionFunction.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/AESEncryptionFunction.java new file mode 100644 index 00000000..5a4a1539 --- /dev/null +++ b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/AESEncryptionFunction.java @@ -0,0 +1,216 @@ +package com.jd.blockchain.crypto.service.classic; + +import static com.jd.blockchain.crypto.BaseCryptoKey.KEY_TYPE_BYTES; +import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; +import static com.jd.blockchain.crypto.CryptoKeyType.SYMMETRIC_KEY; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import com.jd.blockchain.crypto.*; +import com.jd.blockchain.crypto.SymmetricKey; +import com.jd.blockchain.crypto.symmetric.SymmetricCiphertext; +import com.jd.blockchain.crypto.symmetric.SymmetricEncryptionFunction; +import com.jd.blockchain.utils.security.AESUtils; + +public class AESEncryptionFunction implements SymmetricEncryptionFunction { + + public static final CryptoAlgorithm AES = ClassicCryptoService.AES_ALGORITHM; + + private static final int KEY_SIZE = 128 / 8; + private static final int BLOCK_SIZE = 128 / 8; + + private static final int PLAINTEXT_BUFFER_LENGTH = 256; + private static final int CIPHERTEXT_BUFFER_LENGTH = 256 + 16 + 2; + + private static final int SYMMETRICKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + KEY_SIZE; + + AESEncryptionFunction() { + } + + @Override + public Ciphertext encrypt(SymmetricKey key, byte[] data) { + + byte[] rawKeyBytes = key.getRawKeyBytes(); + + // 验证原始密钥长度为128比特,即16字节 + if (rawKeyBytes.length != KEY_SIZE) { + throw new CryptoException("This key has wrong format!"); + } + + // 验证密钥数据的算法标识对应AES算法 + if (key.getAlgorithm().code() != AES.code()) { + throw new CryptoException("The is not AES symmetric key!"); + } + + // 调用底层AES128算法并计算密文数据 + return new SymmetricCiphertext(AES, AESUtils.encrypt(data, rawKeyBytes)); + } + + @Override + public void encrypt(SymmetricKey key, InputStream in, OutputStream out) { + // 读输入流得到明文,加密,密文数据写入输出流 + try { + // TODO: 错误地使用 available 方法; + + byte[] buffBytes = new byte[PLAINTEXT_BUFFER_LENGTH]; + + // The final byte of plaintextWithPadding represents the length of padding in the first 256 bytes, + // and the padded value in hexadecimal + byte[] plaintextWithPadding = new byte[buffBytes.length + 1]; + + byte padding; + + int len; + int i; + + while((len=in.read(buffBytes)) > 0){ + padding = (byte) (PLAINTEXT_BUFFER_LENGTH - len); + i = len; + while (i < plaintextWithPadding.length){ + plaintextWithPadding[i] = padding; + i++; + } + out.write(encrypt(key,plaintextWithPadding).toBytes()); + } +// int size = in.available(); +// if (size < 1){ +// throw new CryptoException("The input is null!"); +// } +// +// byte[] aesData = new byte[size]; +// +// if (in.read(aesData) != -1) { +// out.write(encrypt(key, aesData).); +// } +// +// in.close(); +// out.close(); + + } catch (IOException e) { + throw new CryptoException(e.getMessage(), e); + } + } + + @Override + public byte[] decrypt(SymmetricKey key, Ciphertext ciphertext) { + byte[] rawKeyBytes = key.getRawKeyBytes(); + byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); + + // 验证原始密钥长度为128比特,即16字节 + if (rawKeyBytes.length != KEY_SIZE) { + throw new CryptoException("This key has wrong format!"); + } + + // 验证密钥数据的算法标识对应AES算法 + if (key.getAlgorithm().code() != AES.code()) { + throw new CryptoException("The is not AES symmetric key!"); + } + + // 验证原始密文长度为分组长度的整数倍 + if (rawCiphertextBytes.length % BLOCK_SIZE != 0) { + throw new CryptoException("This ciphertext has wrong format!"); + } + + // 验证密文数据算法标识对应AES算法 + if (ciphertext.getAlgorithm().code() != AES.code()) { + throw new CryptoException("This is not AES ciphertext!"); + } + + // 调用底层AES128算法解密,得到明文 + return AESUtils.decrypt(rawCiphertextBytes, rawKeyBytes); + } + + @Override + public void decrypt(SymmetricKey key, InputStream in, OutputStream out) { + // 读输入流得到密文数据,解密,明文写入输出流 + try { + byte[] buffBytes = new byte[CIPHERTEXT_BUFFER_LENGTH]; + byte[] plaintextWithPadding = new byte[PLAINTEXT_BUFFER_LENGTH + 1]; + + byte padding; + byte[] plaintext; + + int len,i; + while ((len = in.read(buffBytes)) > 0){ + if (len != CIPHERTEXT_BUFFER_LENGTH){ + throw new CryptoException("inputStream's length is wrong!"); + } + if (!supportCiphertext(buffBytes)) { + throw new CryptoException("InputStream is not valid AES ciphertext!"); + } + + plaintextWithPadding = decrypt(key,resolveCiphertext(buffBytes)); + + if (plaintextWithPadding.length != (PLAINTEXT_BUFFER_LENGTH +1)){ + throw new CryptoException("The decrypted plaintext is valid"); + } + + + padding = plaintextWithPadding[PLAINTEXT_BUFFER_LENGTH]; + i = PLAINTEXT_BUFFER_LENGTH; + + + while ((PLAINTEXT_BUFFER_LENGTH - padding) < i){ + + i--; + } + plaintext = new byte[PLAINTEXT_BUFFER_LENGTH - padding]; + System.arraycopy(plaintextWithPadding,0,plaintext,0,plaintext.length); + out.write(plaintext); + } + +// // TODO: 错误地使用 available 方法; +// byte[] aesData = new byte[in.available()]; +// in.read(aesData); +// in.close(); +// +// if (!supportCiphertext(aesData)) { +// throw new CryptoException("InputStream is not valid AES ciphertext!"); +// } +// +// out.write(decrypt(key, resolveCiphertext(aesData))); +// out.close(); + } catch (IOException e) { + throw new CryptoException(e.getMessage(), e); + } + } + + @Override + public boolean supportSymmetricKey(byte[] symmetricKeyBytes) { + // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,字节数组的算法标识对应AES算法且密钥密钥类型是对称密钥 + return symmetricKeyBytes.length == SYMMETRICKEY_LENGTH && CryptoAlgorithm.match(AES, symmetricKeyBytes) + && symmetricKeyBytes[ALGORYTHM_CODE_SIZE] == SYMMETRIC_KEY.CODE; + } + + @Override + public SymmetricKey resolveSymmetricKey(byte[] symmetricKeyBytes) { + // 由框架调用 support 方法检查有效性,在此不做重复检查; + return new SymmetricKey(symmetricKeyBytes); + } + + @Override + public boolean supportCiphertext(byte[] ciphertextBytes) { + // 验证(输入字节数组长度-算法标识长度)是分组长度的整数倍,字节数组的算法标识对应AES算法 + return (ciphertextBytes.length - ALGORYTHM_CODE_SIZE) % BLOCK_SIZE == 0 + && CryptoAlgorithm.match(AES, ciphertextBytes); + } + + @Override + public SymmetricCiphertext resolveCiphertext(byte[] ciphertextBytes) { + // 由框架调用 support 方法检查有效性,在此不做重复检查; + return new SymmetricCiphertext(ciphertextBytes); + } + + @Override + public CryptoAlgorithm getAlgorithm() { + return AES; + } + + @Override + public CryptoKey generateSymmetricKey() { + // 根据对应的标识和原始密钥生成相应的密钥数据 + return new SymmetricKey(AES, AESUtils.generateKey128_Bytes()); + } +} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ClassicCryptoService.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ClassicCryptoService.java new file mode 100644 index 00000000..d807fd7c --- /dev/null +++ b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ClassicCryptoService.java @@ -0,0 +1,62 @@ +package com.jd.blockchain.crypto.service.classic; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoAlgorithmDefinition; +import com.jd.blockchain.crypto.CryptoFunction; +import com.jd.blockchain.crypto.CryptoService; +import com.jd.blockchain.provider.NamedProvider; + +@NamedProvider("CLASSIC") +public class ClassicCryptoService implements CryptoService { + + public static final CryptoAlgorithm ED25519_ALGORITHM = CryptoAlgorithmDefinition.defineSignature("ED25519", + false, (byte) 21); + public static final CryptoAlgorithm ECDSA_ALGORITHM = CryptoAlgorithmDefinition.defineSignature("ECDSA", + false, (byte) 22); + + public static final CryptoAlgorithm RSA_ALGORITHM = CryptoAlgorithmDefinition.defineSignature("RSA", + true, (byte) 23); + + public static final CryptoAlgorithm SHA256_ALGORITHM = CryptoAlgorithmDefinition.defineHash("SHA256", + (byte) 24); + + public static final CryptoAlgorithm RIPEMD160_ALGORITHM = CryptoAlgorithmDefinition.defineHash("RIPEMD160", + (byte) 25); + + public static final CryptoAlgorithm AES_ALGORITHM = CryptoAlgorithmDefinition.defineSymmetricEncryption("AES", + (byte) 26); + + public static final CryptoAlgorithm JVM_SECURE_RANDOM_ALGORITHM = CryptoAlgorithmDefinition + .defineRandom("JVM-SECURE-RANDOM", (byte) 27); + + public static final AESEncryptionFunction AES = new AESEncryptionFunction(); + + public static final ED25519SignatureFunction ED25519 = new ED25519SignatureFunction(); + + public static final RIPEMD160HashFunction RIPEMD160 = new RIPEMD160HashFunction(); + + public static final SHA256HashFunction SHA256 = new SHA256HashFunction(); + + public static final JVMSecureRandomFunction JVM_SECURE_RANDOM = new JVMSecureRandomFunction(); + + // public static final ECDSASignatureFunction ECDSA = new + // ECDSASignatureFunction(); + + private static final Collection FUNCTIONS; + + static { + List funcs = Arrays.asList(AES, ED25519, RIPEMD160, SHA256, JVM_SECURE_RANDOM); + FUNCTIONS = Collections.unmodifiableList(funcs); + } + + @Override + public Collection getFunctions() { + return FUNCTIONS; + } + +} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ECDSASignatureFunction.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ECDSASignatureFunction.java new file mode 100644 index 00000000..11ef1217 --- /dev/null +++ b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ECDSASignatureFunction.java @@ -0,0 +1,67 @@ +package com.jd.blockchain.crypto.service.classic; + +import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; +import com.jd.blockchain.crypto.asymmetric.*; + +public class ECDSASignatureFunction implements SignatureFunction { + + ECDSASignatureFunction() { + } + + @Override + public SignatureDigest sign(PrivKey privKey, byte[] data) { + return null; + } + + @Override + public boolean verify(SignatureDigest digest, PubKey pubKey, byte[] data) { + return false; + } + + @Override + public byte[] retrievePubKeyBytes(byte[] privKeyBytes) { + return new byte[0]; + } + + @Override + public boolean supportPrivKey(byte[] privKeyBytes) { + return false; + } + + @Override + public PrivKey resolvePrivKey(byte[] privKeyBytes) { + return null; + } + + @Override + public boolean supportPubKey(byte[] pubKeyBytes) { + return false; + } + + @Override + public PubKey resolvePubKey(byte[] pubKeyBytes) { + return null; + } + + @Override + public boolean supportDigest(byte[] digestBytes) { + return false; + } + + @Override + public SignatureDigest resolveDigest(byte[] digestBytes) { + return null; + } + + @Override + public CryptoAlgorithm getAlgorithm() { + return ClassicCryptoService.ECDSA_ALGORITHM; + } + + @Override + public CryptoKeyPair generateKeyPair() { + return null; + } +} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/asymmetric/ED25519SignatureFunction.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ED25519SignatureFunction.java similarity index 65% rename from source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/asymmetric/ED25519SignatureFunction.java rename to source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ED25519SignatureFunction.java index 519f3c88..1d60c2e8 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/asymmetric/ED25519SignatureFunction.java +++ b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/ED25519SignatureFunction.java @@ -1,7 +1,19 @@ -package com.jd.blockchain.crypto.impl.def.asymmetric; +package com.jd.blockchain.crypto.service.classic; + +import static com.jd.blockchain.crypto.BaseCryptoKey.KEY_TYPE_BYTES; +import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; +import static com.jd.blockchain.crypto.CryptoKeyType.PRIV_KEY; +import static com.jd.blockchain.crypto.CryptoKeyType.PUB_KEY; + +import java.security.KeyPair; import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.*; +import com.jd.blockchain.crypto.CryptoException; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; +import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; +import com.jd.blockchain.crypto.asymmetric.SignatureDigest; +import com.jd.blockchain.crypto.asymmetric.SignatureFunction; import com.jd.blockchain.utils.security.Ed25519Utils; import net.i2p.crypto.eddsa.EdDSAPrivateKey; @@ -11,25 +23,19 @@ import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable; import net.i2p.crypto.eddsa.spec.EdDSAParameterSpec; import net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec; -import java.security.KeyPair; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.ED25519; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_BYTES; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIV_KEY; -import static com.jd.blockchain.crypto.CryptoKeyType.PUB_KEY; -import static com.jd.blockchain.crypto.base.BaseCryptoKey.KEY_TYPE_BYTES; - public class ED25519SignatureFunction implements SignatureFunction { + private static final CryptoAlgorithm ED25519 = ClassicCryptoService.ED25519_ALGORITHM; + private static final int PUBKEY_SIZE = 32; private static final int PRIVKEY_SIZE = 32; - private static final int DIGEST_SIZE = 64; + private static final int SIGNATUREDIGEST_SIZE = 64; - private static final int PUBKEY_LENGTH = ALGORYTHM_BYTES + KEY_TYPE_BYTES + PUBKEY_SIZE; - private static final int PRIVKEY_LENGTH = ALGORYTHM_BYTES + KEY_TYPE_BYTES + PRIVKEY_SIZE; - private static final int SIGNATUREDIGEST_LENGTH = ALGORYTHM_BYTES + DIGEST_SIZE; + private static final int PUBKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + PUBKEY_SIZE; + private static final int PRIVKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + PRIVKEY_SIZE; + private static final int SIGNATUREDIGEST_LENGTH = ALGORYTHM_CODE_SIZE + SIGNATUREDIGEST_SIZE; - public ED25519SignatureFunction() { + ED25519SignatureFunction() { } @Override @@ -38,12 +44,14 @@ public class ED25519SignatureFunction implements SignatureFunction { byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); // 验证原始私钥长度为256比特,即32字节 - if (rawPrivKeyBytes.length != PRIVKEY_SIZE) - throw new IllegalArgumentException("This key has wrong format!"); + if (rawPrivKeyBytes.length != PRIVKEY_SIZE) { + throw new CryptoException("This key has wrong format!"); + } // 验证密钥数据的算法标识对应ED25519签名算法 - if (privKey.getAlgorithm() != ED25519) - throw new IllegalArgumentException("This key is not ED25519 private key!"); + if (privKey.getAlgorithm().code() != ED25519.code()) { + throw new CryptoException("This key is not ED25519 private key!"); + } // 调用ED25519签名算法计算签名结果 return new SignatureDigest(ED25519, Ed25519Utils.sign_512(data, rawPrivKeyBytes)); @@ -56,16 +64,19 @@ public class ED25519SignatureFunction implements SignatureFunction { byte[] rawDigestBytes = digest.getRawDigest(); // 验证原始公钥长度为256比特,即32字节 - if (rawPubKeyBytes.length != PUBKEY_SIZE) - throw new IllegalArgumentException("This key has wrong format!"); + if (rawPubKeyBytes.length != PUBKEY_SIZE) { + throw new CryptoException("This key has wrong format!"); + } // 验证密钥数据的算法标识对应ED25519签名算法 - if (pubKey.getAlgorithm() != ED25519) - throw new IllegalArgumentException("This key is not ED25519 public key!"); + if (pubKey.getAlgorithm().code() != ED25519.code()) { + throw new CryptoException("This key is not ED25519 public key!"); + } // 验证密文数据的算法标识对应ED25519签名算法,并且原始摘要长度为64字节 - if (digest.getAlgorithm() != ED25519 || rawDigestBytes.length != DIGEST_SIZE) - throw new IllegalArgumentException("This is not ED25519 signature digest!"); + if (digest.getAlgorithm().code() != ED25519.code() || rawDigestBytes.length != SIGNATUREDIGEST_SIZE) { + throw new CryptoException("This is not ED25519 signature digest!"); + } // 调用ED25519验签算法验证签名结果 return Ed25519Utils.verify(data, rawPubKeyBytes, rawDigestBytes); @@ -78,13 +89,14 @@ public class ED25519SignatureFunction implements SignatureFunction { EdDSAParameterSpec spec = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.CURVE_ED25519_SHA512); EdDSAPrivateKeySpec privateKeySpec = new EdDSAPrivateKeySpec(rawPrivKeyBytes, spec); byte[] rawPubKeyBytes = privateKeySpec.getA().toByteArray(); - return new PubKey(ED25519,rawPubKeyBytes).toBytes(); + return new PubKey(ED25519, rawPubKeyBytes).toBytes(); } @Override public boolean supportPrivKey(byte[] privKeyBytes) { // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,密钥数据的算法标识对应ED25519签名算法,并且密钥类型是私钥 - return privKeyBytes.length == PRIVKEY_LENGTH && privKeyBytes[0] == ED25519.CODE && privKeyBytes[1] == PRIV_KEY.CODE; + return privKeyBytes.length == PRIVKEY_LENGTH && CryptoAlgorithm.match(ED25519, privKeyBytes) + && privKeyBytes[ALGORYTHM_CODE_SIZE] == PRIV_KEY.CODE; } @Override @@ -96,7 +108,8 @@ public class ED25519SignatureFunction implements SignatureFunction { @Override public boolean supportPubKey(byte[] pubKeyBytes) { // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,密钥数据的算法标识对应ED25519签名算法,并且密钥类型是公钥 - return pubKeyBytes.length == PUBKEY_LENGTH && pubKeyBytes[0] == ED25519.CODE && pubKeyBytes[1] == PUB_KEY.CODE; + return pubKeyBytes.length == PUBKEY_LENGTH && CryptoAlgorithm.match(ED25519, pubKeyBytes) + && pubKeyBytes[ALGORYTHM_CODE_SIZE] == PUB_KEY.CODE; } @@ -109,7 +122,7 @@ public class ED25519SignatureFunction implements SignatureFunction { @Override public boolean supportDigest(byte[] digestBytes) { // 验证输入字节数组长度=算法标识长度+摘要长度,字节数组的算法标识对应ED25519算法 - return digestBytes.length == SIGNATUREDIGEST_LENGTH && digestBytes[0] == ED25519.CODE; + return digestBytes.length == SIGNATUREDIGEST_LENGTH && CryptoAlgorithm.match(ED25519, digestBytes); } @Override diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/JVMSecureRandomFunction.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/JVMSecureRandomFunction.java new file mode 100644 index 00000000..e32b4813 --- /dev/null +++ b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/JVMSecureRandomFunction.java @@ -0,0 +1,54 @@ +package com.jd.blockchain.crypto.service.classic; + +import java.security.SecureRandom; + +import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.RandomFunction; +import com.jd.blockchain.crypto.RandomGenerator; + +public class JVMSecureRandomFunction implements RandomFunction { + + private static final CryptoAlgorithm JVM_SECURE_RANDOM = ClassicCryptoService.JVM_SECURE_RANDOM_ALGORITHM; + + + JVMSecureRandomFunction() { + } + + @Override + public CryptoAlgorithm getAlgorithm() { + return JVM_SECURE_RANDOM; + } + + @Override + public RandomGenerator generate(byte[] seed) { + return new SecureRandomGenerator(seed); + } + + + private static class SecureRandomGenerator implements RandomGenerator{ + + private SecureRandom sr; + + public SecureRandomGenerator(byte[] seed) { + if (seed == null || seed.length == 0) { + // 随机; + sr = new SecureRandom(); + } else { + sr = new SecureRandom(seed); + } + } + + @Override + public byte[] nextBytes(int size) { + byte[] randomBytes = new byte[size]; + sr.nextBytes(randomBytes); + return randomBytes; + } + + @Override + public void nextBytes(byte[] buffer) { + sr.nextBytes(buffer); + } + + } +} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/hash/RIPEMD160HashFunction.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/RIPEMD160HashFunction.java similarity index 66% rename from source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/hash/RIPEMD160HashFunction.java rename to source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/RIPEMD160HashFunction.java index 7933021b..f7ffba03 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/hash/RIPEMD160HashFunction.java +++ b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/RIPEMD160HashFunction.java @@ -1,20 +1,25 @@ -package com.jd.blockchain.crypto.impl.def.hash; +package com.jd.blockchain.crypto.service.classic; -import static com.jd.blockchain.crypto.CryptoAlgorithm.RIPEMD160; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_BYTES; +import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; import java.util.Arrays; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoException; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.crypto.hash.HashFunction; import com.jd.blockchain.utils.security.RipeMD160Utils; public class RIPEMD160HashFunction implements HashFunction { + private static final CryptoAlgorithm RIPEMD160 = ClassicCryptoService.RIPEMD160_ALGORITHM; + private static final int DIGEST_BYTES = 160 / 8; - private static final int DIGEST_LENGTH = ALGORYTHM_BYTES + DIGEST_BYTES; + private static final int DIGEST_LENGTH = ALGORYTHM_CODE_SIZE + DIGEST_BYTES; + + RIPEMD160HashFunction() { + } @Override public CryptoAlgorithm getAlgorithm() { @@ -23,6 +28,11 @@ public class RIPEMD160HashFunction implements HashFunction { @Override public HashDigest hash(byte[] data) { + + if (data == null) { + throw new CryptoException("The input is null!"); + } + byte[] digestBytes = RipeMD160Utils.hash(data); return new HashDigest(RIPEMD160, digestBytes); } @@ -36,7 +46,7 @@ public class RIPEMD160HashFunction implements HashFunction { @Override public boolean supportHashDigest(byte[] digestBytes) { // 验证输入字节数组长度=算法标识长度+摘要长度,以及算法标识; - return RIPEMD160.CODE == digestBytes[0] && DIGEST_LENGTH == digestBytes.length; + return DIGEST_LENGTH == digestBytes.length && CryptoAlgorithm.match(RIPEMD160, digestBytes); } @Override diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/asymmetric/ECDSASignatureFunction.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/RSACryptoFunction.java similarity index 56% rename from source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/asymmetric/ECDSASignatureFunction.java rename to source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/RSACryptoFunction.java index d17ecf3c..d921a398 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/asymmetric/ECDSASignatureFunction.java +++ b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/RSACryptoFunction.java @@ -1,9 +1,27 @@ -package com.jd.blockchain.crypto.impl.def.asymmetric; +package com.jd.blockchain.crypto.service.classic; +import com.jd.blockchain.crypto.Ciphertext; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.*; -public class ECDSASignatureFunction implements SignatureFunction { +/** + * @author zhanglin33 + * @title: RSACryptoFunction + * @description: Interfaces for RSA crypto functions, including key generation, encryption, signature, and so on + * @date 2019-03-25, 17:28 + */ +public class RSACryptoFunction implements AsymmetricEncryptionFunction, SignatureFunction { + @Override + public Ciphertext encrypt(PubKey pubKey, byte[] data) { + return null; + } + + @Override + public byte[] decrypt(PrivKey privKey, Ciphertext ciphertext) { + return new byte[0]; + } @Override public SignatureDigest sign(PrivKey privKey, byte[] data) { @@ -51,8 +69,18 @@ public class ECDSASignatureFunction implements SignatureFunction { } @Override + public boolean supportCiphertext(byte[] ciphertextBytes) { + return false; + } + + @Override + public AsymmetricCiphertext resolveCiphertext(byte[] ciphertextBytes) { + return null; + } + + @Override public CryptoAlgorithm getAlgorithm() { - return CryptoAlgorithm.ECDSA; + return null; } @Override diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/hash/SHA256HashFunction.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/SHA256HashFunction.java similarity index 67% rename from source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/hash/SHA256HashFunction.java rename to source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/SHA256HashFunction.java index b7aebeff..e210bd27 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/hash/SHA256HashFunction.java +++ b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/service/classic/SHA256HashFunction.java @@ -1,20 +1,25 @@ -package com.jd.blockchain.crypto.impl.def.hash; +package com.jd.blockchain.crypto.service.classic; -import static com.jd.blockchain.crypto.CryptoAlgorithm.SHA256; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_BYTES; +import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; import java.util.Arrays; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoException; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.crypto.hash.HashFunction; import com.jd.blockchain.utils.security.ShaUtils; public class SHA256HashFunction implements HashFunction { + private static final CryptoAlgorithm SHA256 = ClassicCryptoService.SHA256_ALGORITHM; + private static final int DIGEST_BYTES = 256 / 8; - private static final int DIGEST_LENGTH = ALGORYTHM_BYTES + DIGEST_BYTES; + private static final int DIGEST_LENGTH = ALGORYTHM_CODE_SIZE + DIGEST_BYTES; + + SHA256HashFunction() { + } @Override public CryptoAlgorithm getAlgorithm() { @@ -23,6 +28,11 @@ public class SHA256HashFunction implements HashFunction { @Override public HashDigest hash(byte[] data) { + + if (data == null) { + throw new CryptoException("The input is null!"); + } + byte[] digestBytes = ShaUtils.hash_256(data); return new HashDigest(SHA256, digestBytes); } @@ -36,7 +46,7 @@ public class SHA256HashFunction implements HashFunction { @Override public boolean supportHashDigest(byte[] digestBytes) { // 验证输入字节数组长度=算法标识长度+摘要长度,以及算法标识; - return SHA256.CODE == digestBytes[0] && DIGEST_LENGTH == digestBytes.length; + return DIGEST_LENGTH == digestBytes.length && CryptoAlgorithm.match(SHA256, digestBytes); } @Override @@ -46,4 +56,3 @@ public class SHA256HashFunction implements HashFunction { } } - diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/ECDSAUtils.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/ECDSAUtils.java new file mode 100644 index 00000000..8ef85fe0 --- /dev/null +++ b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/ECDSAUtils.java @@ -0,0 +1,10 @@ +package com.jd.blockchain.crypto.utils.classic; + +/** + * @author zhanglin33 + * @title: ECDSAUtils + * @description: ECDSA signature algorithm + * @date 2019-03-25, 17:21 + */ +public class ECDSAUtils { +} diff --git a/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/RSAUtils.java b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/RSAUtils.java new file mode 100644 index 00000000..7724de86 --- /dev/null +++ b/source/crypto/crypto-classic/src/main/java/com/jd/blockchain/crypto/utils/classic/RSAUtils.java @@ -0,0 +1,10 @@ +package com.jd.blockchain.crypto.utils.classic; + +/** + * @author zhanglin33 + * @title: RSAUtils + * @description: RSA encryption and signature algorithms + * @date 2019-03-25, 17:20 + */ +public class RSAUtils { +} diff --git a/source/crypto/crypto-classic/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService b/source/crypto/crypto-classic/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService new file mode 100644 index 00000000..75d86390 --- /dev/null +++ b/source/crypto/crypto-classic/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService @@ -0,0 +1 @@ +com.jd.blockchain.crypto.service.classic.ClassicCryptoService \ No newline at end of file diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/asymmetric/AsymmtricCryptographyImplTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/asymmetric/AsymmtricCryptographyImplTest.java new file mode 100644 index 00000000..091938cd --- /dev/null +++ b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/asymmetric/AsymmtricCryptographyImplTest.java @@ -0,0 +1,953 @@ +//package test.com.jd.blockchain.crypto.asymmetric; +// +//import static com.jd.blockchain.crypto.CryptoKeyType.PRIV_KEY; +//import static com.jd.blockchain.crypto.CryptoKeyType.PUB_KEY; +//import static org.junit.Assert.assertArrayEquals; +//import static org.junit.Assert.assertEquals; +//import static org.junit.Assert.assertNotNull; +//import static org.junit.Assert.assertNull; +//import static org.junit.Assert.assertTrue; +// +//import java.util.Random; +// +//import org.junit.Test; +// +//import com.jd.blockchain.crypto.Ciphertext; +//import com.jd.blockchain.crypto.CryptoAlgorithm; +//import com.jd.blockchain.crypto.CryptoException; +//import com.jd.blockchain.crypto.CryptoKeyType; +//import com.jd.blockchain.crypto.PrivKey; +//import com.jd.blockchain.crypto.PubKey; +//import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; +//import com.jd.blockchain.crypto.asymmetric.AsymmetricEncryptionFunction; +//import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; +//import com.jd.blockchain.crypto.asymmetric.SignatureDigest; +//import com.jd.blockchain.crypto.asymmetric.SignatureFunction; +//import com.jd.blockchain.crypto.impl.AsymmtricCryptographyImpl; +//import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; +//import com.jd.blockchain.utils.io.BytesUtils; +// +//public class AsymmtricCryptographyImplTest { +// +// @Test +// public void testGenerateKeyPair() { +// +// //test ED25519 +// CryptoAlgorithm algorithm = ClassicCryptoService.ED25519.getAlgorithm(); +// CryptoKeyPair keyPair = ClassicCryptoService.ED25519.generateKeyPair(); +// +// PubKey pubKey = keyPair.getPubKey(); +// PrivKey privKey = keyPair.getPrivKey(); +// +// assertNotNull(pubKey); +// assertNotNull(privKey); +// +// assertEquals(ClassicCryptoService.ED25519.getAlgorithm().code(),pubKey.getAlgorithm().code()); +// assertEquals(ClassicCryptoService.ED25519.getAlgorithm().code(),privKey.getAlgorithm().code()); +// +// assertEquals(32,pubKey.getRawKeyBytes().length); +// assertEquals(32,privKey.getRawKeyBytes().length); +// +// byte[] pubKeyBytes = pubKey.toBytes(); +// byte[] privKeyBytes = privKey.toBytes(); +// +// assertEquals(32+1+1,pubKeyBytes.length); +// assertEquals(32+1+1,privKeyBytes.length); +// +// byte[] algorithmBytes = CryptoAlgorithm.toBytes(ClassicCryptoService.ED25519.getAlgorithm()); +// assertEquals(algorithmBytes[0],pubKeyBytes[0]); +// assertEquals(algorithmBytes[1],pubKeyBytes[1]); +// assertEquals(algorithmBytes[0],privKeyBytes[0]); +// assertEquals(algorithmBytes[1],privKeyBytes[1]); +// +// assertEquals(pubKey.getKeyType().CODE,pubKeyBytes[CryptoAlgorithm.CODE_SIZE]); +// assertEquals(privKey.getKeyType().CODE,privKeyBytes[CryptoAlgorithm.CODE_SIZE]); +// +// +// //test SM2 +// algorithm = CryptoAlgorithm.SM2; +// keyPair = asymmetricCrypto.generateKeyPair(algorithm); +// +// assertNotNull(keyPair); +// +// pubKey = keyPair.getPubKey(); +// privKey = keyPair.getPrivKey(); +// +// assertNotNull(pubKey); +// assertNotNull(privKey); +// +// assertEquals(algorithm,pubKey.getAlgorithm()); +// assertEquals(algorithm,privKey.getAlgorithm()); +// +// assertEquals(65,pubKey.getRawKeyBytes().length); +// assertEquals(32,privKey.getRawKeyBytes().length); +// +// pubKeyBytes = pubKey.toBytes(); +// privKeyBytes = privKey.toBytes(); +// +// assertEquals(32+1+1,privKeyBytes.length); +// assertEquals(65+1+1,pubKeyBytes.length); +// +// assertEquals(CryptoAlgorithm.SM2.CODE,pubKeyBytes[0]); +// assertEquals(CryptoAlgorithm.SM2.CODE,privKeyBytes[0]); +// assertEquals(CryptoAlgorithm.SM2, CryptoAlgorithm.valueOf(pubKey.getAlgorithm().CODE)); +// assertEquals(CryptoAlgorithm.SM2, CryptoAlgorithm.valueOf(privKey.getAlgorithm().CODE)); +// +// assertEquals(pubKey.getKeyType().CODE,pubKeyBytes[1]); +// assertEquals(privKey.getKeyType().CODE,privKeyBytes[1]); +// +// +// //test JNIED25519 +// algorithm = CryptoAlgorithm.JNIED25519; +// keyPair = asymmetricCrypto.generateKeyPair(algorithm); +// +// assertNotNull(keyPair); +// +// pubKey = keyPair.getPubKey(); +// privKey = keyPair.getPrivKey(); +// +// assertNotNull(pubKey); +// assertNotNull(privKey); +// +// assertEquals(algorithm,pubKey.getAlgorithm()); +// assertEquals(algorithm,privKey.getAlgorithm()); +// +// assertEquals(32,pubKey.getRawKeyBytes().length); +// assertEquals(32,privKey.getRawKeyBytes().length); +// +// pubKeyBytes = pubKey.toBytes(); +// privKeyBytes = privKey.toBytes(); +// +// assertEquals(32+1+1,pubKeyBytes.length); +// assertEquals(32+1+1,privKeyBytes.length); +// +// assertEquals(CryptoAlgorithm.JNIED25519.CODE,pubKeyBytes[0]); +// assertEquals(CryptoAlgorithm.JNIED25519.CODE,privKeyBytes[0]); +// assertEquals(CryptoAlgorithm.JNIED25519, CryptoAlgorithm.valueOf(pubKey.getAlgorithm().CODE)); +// assertEquals(CryptoAlgorithm.JNIED25519, CryptoAlgorithm.valueOf(privKey.getAlgorithm().CODE)); +// +// assertEquals(pubKey.getKeyType().CODE,pubKeyBytes[1]); +// assertEquals(privKey.getKeyType().CODE,privKeyBytes[1]); +// } +// +// @Test +// public void testGetSignatureFunction() { +// +// AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); +// Random random = new Random(); +// +// +// //test ED25519 +// CryptoAlgorithm algorithm = CryptoAlgorithm.ED25519; +// +// // 测试256字节的消息进行签名 +// byte[] data = new byte[256]; +// random.nextBytes(data); +// verifyGetSignatureFunction(asymmetricCrypto,algorithm,data,32,32,64,null); +// +// //错误的算法标识 +// verifyGetSignatureFunction(asymmetricCrypto,CryptoAlgorithm.AES,data,32,32,64,IllegalArgumentException.class); +// +// data = null; +// verifyGetSignatureFunction(asymmetricCrypto,algorithm,data,32,32,64,NullPointerException.class); +// +// +// //test SM2 +// algorithm = CryptoAlgorithm.SM2; +// +// // 测试256字节的消息进行签名 +// data = new byte[256]; +// random.nextBytes(data); +// verifyGetSignatureFunction(asymmetricCrypto,algorithm,data,65,32,64,null); +// +// //错误的算法标识 +// verifyGetSignatureFunction(asymmetricCrypto,CryptoAlgorithm.AES,data,65,32,64,IllegalArgumentException.class); +// +// data = null; +// verifyGetSignatureFunction(asymmetricCrypto,algorithm,data,65,32,64,NullPointerException.class); +// +// +// //test JNNIED25519 +// algorithm = CryptoAlgorithm.JNIED25519; +// +// // 测试256字节的消息进行签名 +// data = new byte[256]; +// random.nextBytes(data); +// verifyGetSignatureFunction(asymmetricCrypto,algorithm,data,32,32,64,null); +// +// //错误的算法标识 +// verifyGetSignatureFunction(asymmetricCrypto,CryptoAlgorithm.AES,data,32,32,64,IllegalArgumentException.class); +// +// data = null; +// verifyGetSignatureFunction(asymmetricCrypto,algorithm,data,32,32,64,IllegalArgumentException.class); +// } +// +// private void verifyGetSignatureFunction(AsymmetricCryptography asymmetricCrypto, CryptoAlgorithm algorithm, byte[] data, +// int expectedPubKeyLength, int expectedPrivKeyLength, +// int expectedSignatureDigestLength, Class expectedException){ +// +// //初始化一个异常 +// Exception actualEx = null; +// +// try { +// SignatureFunction sf = asymmetricCrypto.getSignatureFunction(algorithm); +// +// assertNotNull(sf); +// +// CryptoKeyPair keyPair = sf.generateKeyPair(); +// PubKey pubKey = keyPair.getPubKey(); +// PrivKey privKey = keyPair.getPrivKey(); +// byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); +// byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); +// byte[] pubKeyBytes = pubKey.toBytes(); +// byte[] privKeyBytes = privKey.toBytes(); +// +// assertEquals(algorithm, pubKey.getAlgorithm()); +// assertEquals(algorithm, privKey.getAlgorithm()); +// assertEquals(expectedPubKeyLength,rawPubKeyBytes.length); +// assertEquals(expectedPrivKeyLength,rawPrivKeyBytes.length); +// +// assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},new byte[]{CryptoKeyType.PUB_KEY.CODE},rawPubKeyBytes), pubKeyBytes); +// assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},new byte[]{CryptoKeyType.PRIV_KEY.CODE},rawPrivKeyBytes), privKeyBytes); +// +// SignatureDigest signatureDigest = sf.sign(privKey,data); +// byte[] rawDigest = signatureDigest.getRawDigest(); +// +// assertEquals(algorithm,signatureDigest.getAlgorithm()); +// assertEquals(expectedSignatureDigestLength,rawDigest.length); +// byte[] signatureDigestBytes = signatureDigest.toBytes(); +// assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},rawDigest),signatureDigestBytes); +// +// assertTrue(signatureDigest.equals(signatureDigest)); +// assertEquals(signatureDigest.hashCode(),signatureDigest.hashCode()); +// +// assertTrue(sf.verify(signatureDigest,pubKey,data)); +// +// assertTrue(sf.supportPubKey(pubKeyBytes)); +// assertTrue(sf.supportPrivKey(privKeyBytes)); +// assertTrue(sf.supportDigest(signatureDigestBytes)); +// +// assertEquals(pubKey,sf.resolvePubKey(pubKeyBytes)); +// assertEquals(privKey,sf.resolvePrivKey(privKeyBytes)); +// assertEquals(signatureDigest,sf.resolveDigest(signatureDigestBytes)); +// +// assertEquals(algorithm,sf.getAlgorithm()); +// +// } catch (Exception e){ +// actualEx = e; +// } +// +// if (expectedException == null) { +// assertNull(actualEx); +// } +// else { +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// +// @Test +// public void testVerify() { +// +// AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); +// Random randomData = new Random(); +// +// //test ED25519 +// CryptoAlgorithm algorithm = CryptoAlgorithm.ED25519; +// +// // 测试256字节的消息进行签名 +// byte[] data = new byte[256]; +// randomData.nextBytes(data); +// SignatureFunction sf = asymmetricCrypto.getSignatureFunction(algorithm); +// CryptoKeyPair keyPair = sf.generateKeyPair(); +// byte[] pubKeyBytes = keyPair.getPubKey().toBytes(); +// +// byte[] signatureDigestBytes = sf.sign(keyPair.getPrivKey(),data).toBytes(); +// verifyVerify(asymmetricCrypto,true,data,pubKeyBytes,signatureDigestBytes,null); +// +// //签名数据末尾两个字节丢失情况下,抛出异常 +// byte[] truncatedSignatureDigestBytes = new byte[signatureDigestBytes.length-2]; +// System.arraycopy(signatureDigestBytes,0,truncatedSignatureDigestBytes,0,truncatedSignatureDigestBytes.length); +// verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,truncatedSignatureDigestBytes,IllegalArgumentException.class); +// +// byte[] signatureDigestBytesWithWrongAlgCode = signatureDigestBytes; +// signatureDigestBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,signatureDigestBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// signatureDigestBytes = null; +// verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,signatureDigestBytes,NullPointerException.class); +// +// +// //test SM2 +// algorithm = CryptoAlgorithm.SM2; +// +// // 测试256字节的消息进行签名 +// data = new byte[256]; +// randomData.nextBytes(data); +// sf = asymmetricCrypto.getSignatureFunction(algorithm); +// keyPair = sf.generateKeyPair(); +// pubKeyBytes = keyPair.getPubKey().toBytes(); +// +// signatureDigestBytes = sf.sign(keyPair.getPrivKey(),data).toBytes(); +// verifyVerify(asymmetricCrypto,true,data,pubKeyBytes,signatureDigestBytes,null); +// +// //签名数据末尾两个字节丢失情况下,抛出异常 +// truncatedSignatureDigestBytes = new byte[signatureDigestBytes.length-2]; +// System.arraycopy(signatureDigestBytes,0,truncatedSignatureDigestBytes,0,truncatedSignatureDigestBytes.length); +// verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,truncatedSignatureDigestBytes,IllegalArgumentException.class); +// +// signatureDigestBytesWithWrongAlgCode = signatureDigestBytes; +// signatureDigestBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,signatureDigestBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// signatureDigestBytes = null; +// verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,signatureDigestBytes,NullPointerException.class); +// +// //test JNIED25519 +// algorithm = CryptoAlgorithm.JNIED25519; +// +// // 测试256字节的消息进行签名 +// data = new byte[256]; +// randomData.nextBytes(data); +// sf = asymmetricCrypto.getSignatureFunction(algorithm); +// keyPair = sf.generateKeyPair(); +// pubKeyBytes = keyPair.getPubKey().toBytes(); +// +// signatureDigestBytes = sf.sign(keyPair.getPrivKey(),data).toBytes(); +// verifyVerify(asymmetricCrypto,true,data,pubKeyBytes,signatureDigestBytes,null); +// +// //签名数据末尾两个字节丢失情况下,抛出异常 +// truncatedSignatureDigestBytes = new byte[signatureDigestBytes.length-2]; +// System.arraycopy(signatureDigestBytes,0,truncatedSignatureDigestBytes,0,truncatedSignatureDigestBytes.length); +// verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,truncatedSignatureDigestBytes,IllegalArgumentException.class); +// +// signatureDigestBytesWithWrongAlgCode = signatureDigestBytes; +// signatureDigestBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,signatureDigestBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// signatureDigestBytes = null; +// verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,signatureDigestBytes,NullPointerException.class); +// } +// +// private void verifyVerify(AsymmetricCryptography asymmetricCrypto,boolean expectedResult,byte[] data, +// byte[] pubKeyBytes, byte[] signatureDigestBytes, Class expectedException){ +// +// //初始化一个异常 +// Exception actualEx = null; +// boolean pass = false; +// +// try { +// +// pass = asymmetricCrypto.verify(signatureDigestBytes,pubKeyBytes,data); +// +// } +// catch (Exception e){ +// actualEx = e; +// } +// +// assertEquals(expectedResult, pass); +// +// if (expectedException == null) { +// assertNull(actualEx); +// } +// else { +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// +// @Test +// public void testGetAsymmetricEncryptionFunction() { +// +// AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); +// Random random = new Random(); +// +// +// //test SM2 +// CryptoAlgorithm algorithm = CryptoAlgorithm.SM2; +// +// //Case 1: SM2Encryption with 16 bytes data +// byte[] data = new byte[16]; +// random.nextBytes(data); +// verifyGetAsymmetricEncryptionFunction(asymmetricCrypto, algorithm,65,32,65+16+32,data,null); +// +// //Case 2: SM2Encryption with 256 bytes data +// data = new byte[256]; +// random.nextBytes(data); +// verifyGetAsymmetricEncryptionFunction(asymmetricCrypto, algorithm,65,32,65+256+32,data,null); +// +// //Case 3: SM2Encryption with 1 bytes data +// data = new byte[3]; +// random.nextBytes(data); +// verifyGetAsymmetricEncryptionFunction(asymmetricCrypto, algorithm,65,32,65+3+32,data,null); +// +// //Case 4: SM2Encryption with wrong algorithm +// verifyGetAsymmetricEncryptionFunction(asymmetricCrypto,CryptoAlgorithm.AES,65,32,65+3+32,data,IllegalArgumentException.class); +// +// //Case 5: SM2Encryption with null data +// data = null; +// verifyGetAsymmetricEncryptionFunction(asymmetricCrypto,algorithm,65,32,65+32,data,NullPointerException.class); +// } +// +// private void verifyGetAsymmetricEncryptionFunction(AsymmetricCryptography asymmetricCrypto, CryptoAlgorithm algorithm, +// int expectedPubKeyLength, int expectedPrivKeyLength, +// int expectedCiphertextLength, byte[] data, Class expectedException){ +// +// //初始化一个异常 +// Exception actualEx = null; +// +// try { +// AsymmetricEncryptionFunction aef = asymmetricCrypto.getAsymmetricEncryptionFunction(algorithm); +// //验证获取的算法实例非空 +// assertNotNull(aef); +// +// CryptoKeyPair keyPair = aef.generateKeyPair(); +// PubKey pubKey = keyPair.getPubKey(); +// PrivKey privKey = keyPair.getPrivKey(); +// byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); +// byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); +// byte[] pubKeyBytes = pubKey.toBytes(); +// byte[] privKeyBytes = privKey.toBytes(); +// +// assertEquals(algorithm, pubKey.getAlgorithm()); +// assertEquals(algorithm, privKey.getAlgorithm()); +// assertEquals(expectedPubKeyLength,rawPubKeyBytes.length); +// assertEquals(expectedPrivKeyLength,rawPrivKeyBytes.length); +// +// assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},new byte[]{CryptoKeyType.PUB_KEY.CODE},rawPubKeyBytes), pubKeyBytes); +// assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},new byte[]{CryptoKeyType.PRIV_KEY.CODE},rawPrivKeyBytes), privKeyBytes); +// +// Ciphertext ciphertext = aef.encrypt(pubKey,data); +// byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); +// +// assertEquals(algorithm,ciphertext.getAlgorithm()); +// assertEquals(expectedCiphertextLength,rawCiphertextBytes.length); +// byte[] ciphertextBytes = ciphertext.toBytes(); +// assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},rawCiphertextBytes),ciphertextBytes); +// +// assertArrayEquals(data,aef.decrypt(privKey,ciphertext)); +// +// assertTrue(aef.supportPubKey(pubKeyBytes)); +// assertTrue(aef.supportPrivKey(privKeyBytes)); +// assertTrue(aef.supportCiphertext(ciphertextBytes)); +// +// assertEquals(pubKey,aef.resolvePubKey(pubKeyBytes)); +// assertEquals(privKey,aef.resolvePrivKey(privKeyBytes)); +// assertEquals(ciphertext,aef.resolveCiphertext(ciphertextBytes)); +// +// assertEquals(algorithm,aef.getAlgorithm()); +// +// +// }catch (Exception e){ +// actualEx = e; +// } +// +// if(expectedException == null){ +// assertNull(actualEx); +// } +// else { +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// +// @Test +// public void testDecrypt() { +// +// AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); +// Random random = new Random(); +// +// byte[] data = new byte[16]; +// random.nextBytes(data); +// +// //test SM2 +// CryptoAlgorithm algorithm = CryptoAlgorithm.SM2; +// AsymmetricEncryptionFunction aef = asymmetricCrypto.getAsymmetricEncryptionFunction(algorithm); +// CryptoKeyPair keyPair = aef.generateKeyPair(); +// PubKey pubKey = keyPair.getPubKey(); +// PrivKey privKey = keyPair.getPrivKey(); +// byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); +// Ciphertext ciphertext = aef.encrypt(pubKey,data); +// byte[] ciphertextBytes = ciphertext.toBytes(); +// +// verifyDecrypt(asymmetricCrypto, algorithm, rawPrivKeyBytes, data, ciphertextBytes, null); +// +// //密钥的算法标识与密文的算法标识不一致情况 +// verifyDecrypt(asymmetricCrypto, CryptoAlgorithm.AES, rawPrivKeyBytes, data, ciphertextBytes, IllegalArgumentException.class); +// +// //密文末尾两个字节丢失情况下,抛出异常 +// byte[] truncatedCiphertextBytes = new byte[ciphertextBytes.length-2]; +// System.arraycopy(ciphertextBytes,0,truncatedCiphertextBytes,0,truncatedCiphertextBytes.length); +// verifyDecrypt(asymmetricCrypto, algorithm, rawPrivKeyBytes, data, truncatedCiphertextBytes, com.jd.blockchain.crypto.CryptoException.class); +// +// byte[] ciphertextBytesWithWrongAlgCode = ciphertextBytes; +// ciphertextBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyDecrypt(asymmetricCrypto,algorithm,rawPrivKeyBytes,data,ciphertextBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// ciphertextBytes = null; +// verifyDecrypt(asymmetricCrypto,algorithm,rawPrivKeyBytes,data,ciphertextBytes,NullPointerException.class); +// } +// +// private void verifyDecrypt(AsymmetricCryptography asymmetricCrypto, CryptoAlgorithm algorithm, +// byte[] key, byte[] data, byte[] ciphertextBytes, Class expectedException){ +// Exception actualEx = null; +// +// try { +// PrivKey privKey = new PrivKey(algorithm,key); +// +// byte[] plaintext = asymmetricCrypto.decrypt(privKey.toBytes(), ciphertextBytes); +// +// //解密后的明文与初始的明文一致 +// assertArrayEquals(data,plaintext); +// } +// catch (Exception e){ +// actualEx = e; +// } +// +// if (expectedException == null) { +// assertNull(actualEx); +// } +// else { +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// +// @Test +// public void testResolveCiphertext() { +// +// +// AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); +// Random random = new Random(); +// +// byte[] data = new byte[16]; +// random.nextBytes(data); +// +// //test SM2 +// CryptoAlgorithm algorithm = CryptoAlgorithm.SM2; +// AsymmetricEncryptionFunction aef = asymmetricCrypto.getAsymmetricEncryptionFunction(algorithm); +// CryptoKeyPair keyPair = aef.generateKeyPair(); +// PubKey pubKey = keyPair.getPubKey(); +// PrivKey privKey = keyPair.getPrivKey(); +// byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); +// Ciphertext ciphertext = aef.encrypt(pubKey,data); +// byte[] ciphertextBytes = ciphertext.toBytes(); +// +// verifyResolveCiphertext(asymmetricCrypto, algorithm, ciphertextBytes, null); +// +// +// //密文末尾两个字节丢失情况下,抛出异常 +// byte[] truncatedCiphertextBytes = new byte[ciphertextBytes.length-2]; +// System.arraycopy(ciphertextBytes,0,truncatedCiphertextBytes,0,truncatedCiphertextBytes.length); +// verifyDecrypt(asymmetricCrypto, algorithm, rawPrivKeyBytes, data, truncatedCiphertextBytes, CryptoException.class); +// +// byte[] ciphertextBytesWithWrongAlgCode = ciphertextBytes; +// ciphertextBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyResolveCiphertext(asymmetricCrypto,algorithm,ciphertextBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// ciphertextBytes = null; +// verifyResolveCiphertext(asymmetricCrypto,algorithm,ciphertextBytes,NullPointerException.class); +// } +// +// private void verifyResolveCiphertext(AsymmetricCryptography asymmetricCrypto, CryptoAlgorithm algorithm, byte[] ciphertextBytes, +// Class expectedException){ +// Exception actualEx = null; +// +// try { +// +// Ciphertext ciphertext = asymmetricCrypto.resolveCiphertext(ciphertextBytes); +// +// assertNotNull(ciphertext); +// +// assertEquals(algorithm, ciphertext.getAlgorithm()); +// +// assertArrayEquals(ciphertextBytes, ciphertext.toBytes()); +// } +// catch (Exception e){ +// actualEx = e; +// } +// +// if (expectedException == null) { +// assertNull(actualEx); +// } +// else { +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// +// @Test +// public void testTryResolveCiphertext() { +// } +// +// @Test +// public void testResolveSignatureDigest() { +// +// AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); +// Random randomData = new Random(); +// +// //test ED25519 +// CryptoAlgorithm algorithm = CryptoAlgorithm.ED25519; +// +// // 测试256字节的消息进行签名 +// byte[] data = new byte[256]; +// randomData.nextBytes(data); +// SignatureFunction sf = asymmetricCrypto.getSignatureFunction(algorithm); +// CryptoKeyPair keyPair = sf.generateKeyPair(); +// +// byte[] signatureDigestBytes = sf.sign(keyPair.getPrivKey(),data).toBytes(); +// verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,signatureDigestBytes,null); +// +// //签名数据末尾两个字节丢失情况下,抛出异常 +// byte[] truncatedSignatureDigestBytes = new byte[signatureDigestBytes.length-2]; +// System.arraycopy(signatureDigestBytes,0,truncatedSignatureDigestBytes,0,truncatedSignatureDigestBytes.length); +// verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,truncatedSignatureDigestBytes,IllegalArgumentException.class); +// +// signatureDigestBytes = null; +// verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,signatureDigestBytes,NullPointerException.class); +// +// +// //test SM2 +// algorithm = CryptoAlgorithm.SM2; +// +// // 测试256字节的消息进行签名 +// data = new byte[256]; +// randomData.nextBytes(data); +// sf = asymmetricCrypto.getSignatureFunction(algorithm); +// keyPair = sf.generateKeyPair(); +// +// signatureDigestBytes = sf.sign(keyPair.getPrivKey(),data).toBytes(); +// verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,signatureDigestBytes,null); +// +// //签名数据末尾两个字节丢失情况下,抛出异常 +// truncatedSignatureDigestBytes = new byte[signatureDigestBytes.length-2]; +// System.arraycopy(signatureDigestBytes,0,truncatedSignatureDigestBytes,0,truncatedSignatureDigestBytes.length); +// verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,truncatedSignatureDigestBytes,IllegalArgumentException.class); +// +// signatureDigestBytes = null; +// verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,signatureDigestBytes,NullPointerException.class); +// +// //test JNIED25519 +// algorithm = CryptoAlgorithm.JNIED25519; +// +// // 测试256字节的消息进行签名 +// data = new byte[256]; +// randomData.nextBytes(data); +// sf = asymmetricCrypto.getSignatureFunction(algorithm); +// keyPair = sf.generateKeyPair(); +// +// signatureDigestBytes = sf.sign(keyPair.getPrivKey(),data).toBytes(); +// verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,signatureDigestBytes,null); +// +// //签名数据末尾两个字节丢失情况下,抛出异常 +// truncatedSignatureDigestBytes = new byte[signatureDigestBytes.length-2]; +// System.arraycopy(signatureDigestBytes,0,truncatedSignatureDigestBytes,0,truncatedSignatureDigestBytes.length); +// verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,truncatedSignatureDigestBytes,IllegalArgumentException.class); +// +// signatureDigestBytes = null; +// verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,signatureDigestBytes,NullPointerException.class); +// } +// +// private void verifyResolveSignatureDigest(AsymmetricCryptography asymmetricCrypto, CryptoAlgorithm algorithm, +// int expectedSignatureDigestLength, +// byte[] signatureDigestBytes, Class expectedException){ +// +// //初始化一个异常 +// Exception actualEx = null; +// +// try { +// +// SignatureDigest signatureDigest = asymmetricCrypto.resolveSignatureDigest(signatureDigestBytes); +// +// assertNotNull(signatureDigest); +// +// assertEquals(algorithm,signatureDigest.getAlgorithm()); +// +// assertEquals(expectedSignatureDigestLength,signatureDigest.getRawDigest().length); +// +// assertArrayEquals(signatureDigestBytes,signatureDigest.toBytes()); +// +// } +// catch (Exception e){ +// actualEx = e; +// } +// +// if (expectedException == null) { +// assertNull(actualEx); +// } +// else { +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// +// @Test +// public void testTryResolveSignatureDigest() { +// } +// +// @Test +// public void testRetrievePubKeyBytes() { +// +// AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); +// +// //test ED25519 +// CryptoAlgorithm algorithm = CryptoAlgorithm.ED25519; +// +// CryptoKeyPair keyPair = asymmetricCrypto.generateKeyPair(algorithm); +// +// byte[] expectedPrivKeyBytes = keyPair.getPrivKey().toBytes(); +// byte[] expectedPubKeyBytes = keyPair.getPubKey().toBytes(); +// +// byte[] pubKeyBytes = asymmetricCrypto.retrievePubKeyBytes(expectedPrivKeyBytes); +// +// assertArrayEquals(expectedPubKeyBytes,pubKeyBytes); +// +// +// //test SM2 +// algorithm = CryptoAlgorithm.SM2; +// +// keyPair = asymmetricCrypto.generateKeyPair(algorithm); +// +// expectedPrivKeyBytes = keyPair.getPrivKey().toBytes(); +// expectedPubKeyBytes = keyPair.getPubKey().toBytes(); +// +// pubKeyBytes = asymmetricCrypto.retrievePubKeyBytes(expectedPrivKeyBytes); +// +// assertArrayEquals(expectedPubKeyBytes,pubKeyBytes); +// +// +// //test JNIED25519 +// algorithm = CryptoAlgorithm.JNIED25519; +// +// keyPair = asymmetricCrypto.generateKeyPair(algorithm); +// +// expectedPrivKeyBytes = keyPair.getPrivKey().toBytes(); +// expectedPubKeyBytes = keyPair.getPubKey().toBytes(); +// +// pubKeyBytes = asymmetricCrypto.retrievePubKeyBytes(expectedPrivKeyBytes); +// +// assertArrayEquals(expectedPubKeyBytes,pubKeyBytes); +// +// } +// +// +// @Test +// public void testResolvePubKey() { +// +// AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); +// +// //test ED25519 +// CryptoAlgorithm algorithm = CryptoAlgorithm.ED25519; +// +// CryptoKeyPair keyPair = asymmetricCrypto.generateKeyPair(algorithm); +// +// byte[] pubKeyBytes = keyPair.getPubKey().toBytes(); +// verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytes,null); +// +// byte[] truncatedPubKeyBytes = new byte[pubKeyBytes.length-2]; +// System.arraycopy(pubKeyBytes,0,truncatedPubKeyBytes,0,truncatedPubKeyBytes.length); +// verifyResolvePubKey(asymmetricCrypto,algorithm,32,truncatedPubKeyBytes,IllegalArgumentException.class); +// +// byte[] pubKeyBytesWithWrongAlgCode = pubKeyBytes; +// pubKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// byte[] pubKeyBytesWithWrongKeyType= pubKeyBytes; +// pubKeyBytesWithWrongKeyType[1] = PRIV_KEY.CODE; +// verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytesWithWrongKeyType,IllegalArgumentException.class); +// +// pubKeyBytes = null; +// verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytes,NullPointerException.class); +// +// +// //test SM2 +// algorithm = CryptoAlgorithm.SM2; +// +// keyPair = asymmetricCrypto.generateKeyPair(algorithm); +// +// pubKeyBytes = keyPair.getPubKey().toBytes(); +// verifyResolvePubKey(asymmetricCrypto,algorithm,65,pubKeyBytes,null); +// +// truncatedPubKeyBytes = new byte[pubKeyBytes.length-2]; +// System.arraycopy(pubKeyBytes,0,truncatedPubKeyBytes,0,truncatedPubKeyBytes.length); +// verifyResolvePubKey(asymmetricCrypto,algorithm,65,truncatedPubKeyBytes,IllegalArgumentException.class); +// +// pubKeyBytesWithWrongAlgCode = pubKeyBytes; +// pubKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyResolvePubKey(asymmetricCrypto,algorithm,65,pubKeyBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// pubKeyBytesWithWrongKeyType= pubKeyBytes; +// pubKeyBytesWithWrongKeyType[1] = PRIV_KEY.CODE; +// verifyResolvePubKey(asymmetricCrypto,algorithm,65,pubKeyBytesWithWrongKeyType,IllegalArgumentException.class); +// +// pubKeyBytes = null; +// verifyResolvePubKey(asymmetricCrypto,algorithm,65,pubKeyBytes,NullPointerException.class); +// +// //test JNIED25519 +// algorithm = CryptoAlgorithm.JNIED25519; +// +// keyPair = asymmetricCrypto.generateKeyPair(algorithm); +// +// pubKeyBytes = keyPair.getPubKey().toBytes(); +// verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytes,null); +// +// truncatedPubKeyBytes = new byte[pubKeyBytes.length-2]; +// System.arraycopy(pubKeyBytes,0,truncatedPubKeyBytes,0,truncatedPubKeyBytes.length); +// verifyResolvePubKey(asymmetricCrypto,algorithm,32,truncatedPubKeyBytes,IllegalArgumentException.class); +// +// pubKeyBytesWithWrongAlgCode = pubKeyBytes; +// pubKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// pubKeyBytesWithWrongKeyType= pubKeyBytes; +// pubKeyBytesWithWrongKeyType[1] = PRIV_KEY.CODE; +// verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytesWithWrongKeyType,IllegalArgumentException.class); +// +// pubKeyBytes = null; +// verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytes,NullPointerException.class); +// } +// +// private void verifyResolvePubKey(AsymmetricCryptography asymmetricCrypto, CryptoAlgorithm algorithm, +// int expectedPubKeyLength, byte[] pubKeyBytes,Class expectedException){ +// +// Exception actualEx = null; +// +// try { +// PubKey pubKey = asymmetricCrypto.resolvePubKey(pubKeyBytes); +// +// assertNotNull(pubKey); +// +// assertEquals(algorithm, pubKey.getAlgorithm()); +// +// assertEquals(expectedPubKeyLength, pubKey.getRawKeyBytes().length); +// +// assertArrayEquals(pubKeyBytes, pubKey.toBytes()); +// +// } +// catch (Exception e){ +// actualEx = e; +// } +// +// if (expectedException == null) { +// assertNull(actualEx); +// } +// else { +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// +// @Test +// public void testTryResolvePubKey() { +// } +// +// @Test +// public void testResolvePrivKey() { +// +// AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); +// +// //test ED25519 +// CryptoAlgorithm algorithm = CryptoAlgorithm.ED25519; +// +// CryptoKeyPair keyPair = asymmetricCrypto.generateKeyPair(algorithm); +// +// byte[] privKeyBytes = keyPair.getPrivKey().toBytes(); +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytes,null); +// +// byte[] truncatedPrivKeyBytes = new byte[privKeyBytes.length-2]; +// System.arraycopy(privKeyBytes,0,truncatedPrivKeyBytes,0,truncatedPrivKeyBytes.length); +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,truncatedPrivKeyBytes,IllegalArgumentException.class); +// +// byte[] privKeyBytesWithWrongAlgCode = privKeyBytes; +// privKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// byte[] privKeyBytesWithWrongKeyType = privKeyBytes; +// privKeyBytesWithWrongKeyType[1] = PUB_KEY.CODE; +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytesWithWrongKeyType,IllegalArgumentException.class); +// +// privKeyBytes = null; +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytes,NullPointerException.class); +// +// +// //test SM2 +// algorithm = CryptoAlgorithm.SM2; +// +// keyPair = asymmetricCrypto.generateKeyPair(algorithm); +// +// privKeyBytes = keyPair.getPrivKey().toBytes(); +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytes,null); +// +// truncatedPrivKeyBytes = new byte[privKeyBytes.length-2]; +// System.arraycopy(privKeyBytes,0,truncatedPrivKeyBytes,0,truncatedPrivKeyBytes.length); +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,truncatedPrivKeyBytes,IllegalArgumentException.class); +// +// privKeyBytesWithWrongAlgCode = privKeyBytes; +// privKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// privKeyBytesWithWrongKeyType = privKeyBytes; +// privKeyBytesWithWrongKeyType[1] = PUB_KEY.CODE; +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytesWithWrongKeyType,IllegalArgumentException.class); +// +// privKeyBytes = null; +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytes,NullPointerException.class); +// +// //test JNIED25519 +// algorithm = CryptoAlgorithm.JNIED25519; +// +// keyPair = asymmetricCrypto.generateKeyPair(algorithm); +// +// privKeyBytes = keyPair.getPrivKey().toBytes(); +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytes,null); +// +// truncatedPrivKeyBytes = new byte[privKeyBytes.length-2]; +// System.arraycopy(privKeyBytes,0,truncatedPrivKeyBytes,0,truncatedPrivKeyBytes.length); +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,truncatedPrivKeyBytes,IllegalArgumentException.class); +// +// privKeyBytesWithWrongAlgCode = privKeyBytes; +// privKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// privKeyBytesWithWrongKeyType = privKeyBytes; +// privKeyBytesWithWrongKeyType[1] = PUB_KEY.CODE; +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytesWithWrongKeyType,IllegalArgumentException.class); +// +// privKeyBytes = null; +// verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytes,NullPointerException.class); +// } +// +// private void verifyResolvePrivKey(AsymmetricCryptography asymmetricCrypto, CryptoAlgorithm algorithm, +// int expectedPrivKeyLength, byte[] privKeyBytes,Class expectedException){ +// +// Exception actualEx = null; +// +// try { +// PrivKey privKey = asymmetricCrypto.resolvePrivKey(privKeyBytes); +// +// assertNotNull(privKey); +// +// assertEquals(algorithm, privKey.getAlgorithm()); +// +// assertEquals(expectedPrivKeyLength, privKey.getRawKeyBytes().length); +// +// assertArrayEquals(privKeyBytes, privKey.toBytes()); +// +// } +// catch (Exception e){ +// actualEx = e; +// } +// +// if (expectedException == null) { +// assertNull(actualEx); +// } +// else { +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// +// @Test +// public void testTryResolvePrivKey() { +// } +//} \ No newline at end of file diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/hash/HashCryptographyImplTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/hash/HashCryptographyImplTest.java new file mode 100644 index 00000000..cf7ec9b3 --- /dev/null +++ b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/hash/HashCryptographyImplTest.java @@ -0,0 +1,334 @@ +//package test.com.jd.blockchain.crypto.hash; +// +//import static org.junit.Assert.*; +// +//import java.util.Random; +// +//import com.jd.blockchain.crypto.smutils.hash.SM3Utils; +//import com.jd.blockchain.utils.io.BytesUtils; +//import com.jd.blockchain.utils.security.RipeMD160Utils; +//import com.jd.blockchain.utils.security.ShaUtils; +// +//import org.junit.Test; +// +//import com.jd.blockchain.crypto.CryptoAlgorithm; +//import com.jd.blockchain.crypto.CryptoUtils; +//import com.jd.blockchain.crypto.hash.HashCryptography; +//import com.jd.blockchain.crypto.hash.HashDigest; +//import com.jd.blockchain.crypto.hash.HashFunction; +//import com.jd.blockchain.crypto.impl.HashCryptographyImpl; +// +//public class HashCryptographyImplTest { +// +// @Test +// public void testGetFunction() { +// HashCryptography hashCrypto = CryptoUtils.hashCrypto(); +// Random rand = new Random(); +// // test SHA256 +// CryptoAlgorithm algorithm = CryptoAlgorithm.SHA256; +// byte[] data = new byte[256]; +// rand.nextBytes(data); +// verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); +// +// data = new byte[0]; +// verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); +// +// data = new byte[1056]; +// rand.nextBytes(data); +// verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); +// +// data = null; +// verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,NullPointerException.class); +// +// +// // test RIPEMD160 +// algorithm = CryptoAlgorithm.RIPEMD160; +// data=new byte[256]; +// rand.nextBytes(data); +// verifyGetFunction(hashCrypto, algorithm, data, 160 / 8,null); +// +// data = new byte[0]; +// verifyGetFunction(hashCrypto, algorithm, data, 160/ 8,null); +// +// data = new byte[1056]; +// rand.nextBytes(data); +// verifyGetFunction(hashCrypto, algorithm, data, 160 / 8,null); +// +// data = null; +// verifyGetFunction(hashCrypto, algorithm, data, 160 / 8,NullPointerException.class); +// +// // test SM3 +// algorithm = CryptoAlgorithm.SM3; +// data = new byte[256]; +// rand.nextBytes(data); +// verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); +// +// data = new byte[0]; +// verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); +// +// data = new byte[1056]; +// rand.nextBytes(data); +// verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); +// +// data = null; +// verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,NullPointerException.class); +// +// // test AES +// data = new byte[0]; +// algorithm = CryptoAlgorithm.AES; +// verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,IllegalArgumentException.class); +// +// // test JNISHA256 +// algorithm = CryptoAlgorithm.JNISHA256; +// data = new byte[256]; +// rand.nextBytes(data); +// verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); +// +// data = new byte[0]; +// verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); +// +// data = new byte[1056]; +// rand.nextBytes(data); +// verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); +// +// data = null; +// verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,IllegalArgumentException.class); +// +// // test JNIRIPEMD160 +// algorithm = CryptoAlgorithm.JNIRIPEMD160; +// data=new byte[256]; +// rand.nextBytes(data); +// verifyGetFunction(hashCrypto, algorithm, data, 160 / 8,null); +// +// data = new byte[0]; +// verifyGetFunction(hashCrypto, algorithm, data, 160/ 8,null); +// +// data = new byte[1056]; +// rand.nextBytes(data); +// verifyGetFunction(hashCrypto, algorithm, data, 160 / 8,null); +// +// data = null; +// verifyGetFunction(hashCrypto, algorithm, data, 160 / 8,IllegalArgumentException.class); +// } +// +// private void verifyGetFunction(HashCryptography hashCrypto, CryptoAlgorithm algorithm, byte[] data, +// int expectedRawBytes,Class expectedException) { +// Exception actualEx = null; +// try { +// HashFunction hf = hashCrypto.getFunction(algorithm); +// assertNotNull(hf); +// +// HashDigest hd = hf.hash(data); +// +// assertEquals(algorithm, hd.getAlgorithm()); +// +// assertEquals(expectedRawBytes, hd.getRawDigest().length); +// +// // verify encoding; +// byte[] encodedHash = hd.toBytes(); +// assertEquals(expectedRawBytes + 1, encodedHash.length); +// +// +// assertEquals(algorithm.CODE, encodedHash[0]); +// +// //verify equals +// assertEquals(true, hd.equals(hf.hash(data))); +// +// //verify verify +// assertTrue( hf.verify(hd, data)); +// +// } catch (Exception e) { +// actualEx = e; +// } +// +// if(expectedException==null){ +// assertNull(actualEx); +// } +// else { +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// +// @Test +// public void testVerifyHashDigestByteArray() { +// HashCryptography hashCrypto = CryptoUtils.hashCrypto(); +// //test SHA256 +// byte[] data=new byte[256]; +// Random rand = new Random(); +// rand.nextBytes(data); +// CryptoAlgorithm algorithm=CryptoAlgorithm.SHA256; +// verifyHashDigestByteArray(hashCrypto,algorithm,data,null); +// data=null; +// verifyHashDigestByteArray(hashCrypto,algorithm,data,NullPointerException.class); +// +// //test RIPEMD160 +// algorithm=CryptoAlgorithm.RIPEMD160; +// data=new byte[896]; +// rand.nextBytes(data); +// verifyHashDigestByteArray(hashCrypto,algorithm,data,null); +// data=null; +// verifyHashDigestByteArray(hashCrypto,algorithm,data,NullPointerException.class); +// +// //test SM3 +// algorithm=CryptoAlgorithm.SM3; +// data=new byte[896]; +// rand.nextBytes(data); +// verifyHashDigestByteArray(hashCrypto,algorithm,data,null); +// data=null; +// verifyHashDigestByteArray(hashCrypto,algorithm,data,NullPointerException.class); +// +// +// //test AES +// algorithm=CryptoAlgorithm.AES; +// data=new byte[277]; +// rand.nextBytes(data); +// verifyHashDigestByteArray(hashCrypto,algorithm,data,IllegalArgumentException.class); +// +// //test JNISHA256 +// data=new byte[256]; +// rand = new Random(); +// rand.nextBytes(data); +// algorithm=CryptoAlgorithm.JNISHA256; +// verifyHashDigestByteArray(hashCrypto,algorithm,data,null); +// data=null; +// verifyHashDigestByteArray(hashCrypto,algorithm,data,IllegalArgumentException.class); +// +// //test JNIRIPEMD160 +// algorithm=CryptoAlgorithm.JNIRIPEMD160; +// data=new byte[896]; +// rand.nextBytes(data); +// verifyHashDigestByteArray(hashCrypto,algorithm,data,null); +// data=null; +// verifyHashDigestByteArray(hashCrypto,algorithm,data,IllegalArgumentException.class); +// } +// +// private void verifyHashDigestByteArray(HashCryptography hashCrypto,CryptoAlgorithm algorithm,byte[] data,Class expectedException){ +// Exception actualEx=null; +// try { +// HashFunction hf = hashCrypto.getFunction(algorithm); +// assertNotNull(hf); +// HashDigest hd = hf.hash(data); +// hashCrypto.verify(hd,data); +// }catch (Exception e) +// { +// actualEx=e; +// } +// if (expectedException==null) +// { +// assertNull(actualEx); +// } +// else{ +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// +// @Test +// public void testResolveHashDigest() { +// Random rand = new Random(); +// HashCryptography hashCrypto = CryptoUtils.hashCrypto(); +// +// //test SHA256 +// CryptoAlgorithm algorithm = CryptoAlgorithm.SHA256; +// byte[] data = new byte[256]; +// rand.nextBytes(data); +// byte[] hashDigestBytes = hashCrypto.getFunction(algorithm).hash(data).toBytes(); +// verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,32+1,null); +// +// byte[] truncatedHashDigestBytes = new byte[hashDigestBytes.length-2]; +// System.arraycopy(hashDigestBytes,0,truncatedHashDigestBytes,0,truncatedHashDigestBytes.length); +// verifyResolveHashDigest(algorithm, hashCrypto,truncatedHashDigestBytes,32+1,IllegalArgumentException.class); +// +// hashDigestBytes = null; +// verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,32+1,NullPointerException.class); +// +// +// //test RIPEMD160 +// algorithm = CryptoAlgorithm.RIPEMD160; +// data = new byte[256]; +// rand.nextBytes(data); +// hashDigestBytes = hashCrypto.getFunction(algorithm).hash(data).toBytes(); +// verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,20+1,null); +// +// truncatedHashDigestBytes = new byte[hashDigestBytes.length-2]; +// System.arraycopy(hashDigestBytes,0,truncatedHashDigestBytes,0,truncatedHashDigestBytes.length); +// verifyResolveHashDigest(algorithm, hashCrypto,truncatedHashDigestBytes,20+1,IllegalArgumentException.class); +// +// hashDigestBytes = null; +// verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,20+1,NullPointerException.class); +// +// +// //test SM3 +// algorithm = CryptoAlgorithm.SM3; +// data = new byte[256]; +// rand.nextBytes(data); +// hashDigestBytes = hashCrypto.getFunction(algorithm).hash(data).toBytes(); +// verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,32+1,null); +// +// truncatedHashDigestBytes = new byte[hashDigestBytes.length-2]; +// System.arraycopy(hashDigestBytes,0,truncatedHashDigestBytes,0,truncatedHashDigestBytes.length); +// verifyResolveHashDigest(algorithm, hashCrypto,truncatedHashDigestBytes,32+1,IllegalArgumentException.class); +// +// hashDigestBytes = null; +// verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,32+1,NullPointerException.class); +// +// +// //test JNISHA256 +// algorithm = CryptoAlgorithm.JNISHA256; +// data = new byte[256]; +// rand.nextBytes(data); +// hashDigestBytes = hashCrypto.getFunction(algorithm).hash(data).toBytes(); +// verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,32+1,null); +// +// truncatedHashDigestBytes = new byte[hashDigestBytes.length-2]; +// System.arraycopy(hashDigestBytes,0,truncatedHashDigestBytes,0,truncatedHashDigestBytes.length); +// verifyResolveHashDigest(algorithm, hashCrypto,truncatedHashDigestBytes,32+1,IllegalArgumentException.class); +// +// hashDigestBytes = null; +// verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,32+1,NullPointerException.class); +// +// //test JNIRIPEMD160 +// algorithm = CryptoAlgorithm.JNIRIPEMD160; +// data = new byte[256]; +// rand.nextBytes(data); +// hashDigestBytes = hashCrypto.getFunction(algorithm).hash(data).toBytes(); +// verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,20+1,null); +// +// truncatedHashDigestBytes = new byte[hashDigestBytes.length-2]; +// System.arraycopy(hashDigestBytes,0,truncatedHashDigestBytes,0,truncatedHashDigestBytes.length); +// verifyResolveHashDigest(algorithm, hashCrypto,truncatedHashDigestBytes,20+1,IllegalArgumentException.class); +// +// hashDigestBytes = null; +// verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,20+1,NullPointerException.class); +// } +// +// private void verifyResolveHashDigest(CryptoAlgorithm algorithm,HashCryptography +// hashCrypto,byte[] hashDigestBytes,int expectedLength,ClassexpectedException){ +// +// Exception actualEx=null; +// +// try { +// +// HashDigest hashDigest=hashCrypto.resolveHashDigest(hashDigestBytes); +// assertNotNull(hashDigest); +// assertEquals(algorithm,hashDigest.getAlgorithm()); +// byte[] algBytes = new byte[1]; +// algBytes[0] = algorithm.CODE; +// assertArrayEquals(hashDigestBytes,BytesUtils.concat(algBytes,hashDigest.getRawDigest())); +// assertEquals(expectedLength,hashDigestBytes.length); +// +// }catch (Exception e) +// { +// actualEx = e; +// } +// if (expectedException==null) +// { +// assertNull(actualEx); +// } +// else { +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// } diff --git a/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/symmetric/SymmetricCryptographyImplTest.java b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/symmetric/SymmetricCryptographyImplTest.java new file mode 100644 index 00000000..efcdd3d8 --- /dev/null +++ b/source/crypto/crypto-classic/src/test/java/test/com/jd/blockchain/crypto/symmetric/SymmetricCryptographyImplTest.java @@ -0,0 +1,471 @@ +//package test.com.jd.blockchain.crypto.symmetric; +// +//import com.jd.blockchain.crypto.Ciphertext; +//import com.jd.blockchain.crypto.CryptoAlgorithm; +//import com.jd.blockchain.crypto.SymmetricKey; +//import com.jd.blockchain.crypto.impl.SymmetricCryptographyImpl; +//import com.jd.blockchain.crypto.symmetric.SymmetricCryptography; +//import com.jd.blockchain.crypto.symmetric.SymmetricEncryptionFunction; +//import com.jd.blockchain.utils.io.BytesUtils; +// +//import org.junit.Test; +// +//import java.io.ByteArrayInputStream; +//import java.io.ByteArrayOutputStream; +//import java.io.InputStream; +//import java.io.OutputStream; +//import java.util.Random; +// +//import static com.jd.blockchain.crypto.CryptoKeyType.PRIV_KEY; +//import static com.jd.blockchain.crypto.CryptoKeyType.SYMMETRIC_KEY; +//import static org.junit.Assert.*; +// +//public class SymmetricCryptographyImplTest { +// +// @Test +// public void testGenerateKey() { +// +// SymmetricCryptography symmetricCrypto = new SymmetricCryptographyImpl(); +// +// //test AES +// CryptoAlgorithm algorithm = CryptoAlgorithm.AES; +// verifyGenerateKey(symmetricCrypto,algorithm); +// +// //test SM4 +// algorithm = CryptoAlgorithm.SM4; +// verifyGenerateKey(symmetricCrypto,algorithm); +// } +// +// private void verifyGenerateKey(SymmetricCryptography symmetricCrypto, CryptoAlgorithm algorithm){ +// +// SymmetricKey symmetricKey= symmetricCrypto.generateKey(algorithm); +// +// assertNotNull(symmetricKey); +// assertEquals(algorithm, symmetricKey.getAlgorithm()); +// assertEquals(128/8,symmetricKey.getRawKeyBytes().length); +// +// byte[] symmetricKeyBytes = symmetricKey.toBytes(); +// //判断密钥数据长度=算法标识长度+密钥掩码长度+原始密钥长度 +// assertEquals(1 + 1 + 128 / 8, symmetricKeyBytes.length); +// +// assertEquals(algorithm.CODE,symmetricKeyBytes[0]); +// assertEquals(algorithm,CryptoAlgorithm.valueOf(symmetricKeyBytes[0])); +// } +// +// @Test +// public void testGetSymmetricEncryptionFunction() { +// +// SymmetricCryptography symmetricCrypto = new SymmetricCryptographyImpl(); +// Random random = new Random(); +// +// +// //test AES +// CryptoAlgorithm algorithm = CryptoAlgorithm.AES; +// +// //Case 1: AES with 16 bytes data +// //刚好一个分组长度,随机生成明文数据 +// byte[] data = new byte[16]; +// random.nextBytes(data); +// verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 2*16, null); +// +// //Case 2: AES with 33 bytes data +// //明文长度大于两倍分组长度,生成的密文是三倍分组长度 +// data = new byte[33]; +// random.nextBytes(data); +// verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 3*16,null); +// +// //Case 3: AES with 3 bytes data +// //明文长度小于分组长度,生成的密文是一倍分组长度 +// data = new byte[3]; +// random.nextBytes(data); +// verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 16,null); +// +// //Case 4: AES with 0 bytes data +// //明文长度小于分组长度,生成的密文是一倍分组长度 +// data = new byte[0]; +// random.nextBytes(data); +// verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 16,null); +// +// //Case 5 AES with null +// //明文为空,可以捕获到异常异常 +// data = null; +// verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 16,IllegalArgumentException.class); +// +// +// //test ED25519 +// algorithm = CryptoAlgorithm.ED25519; +// data = new byte[16]; +// random.nextBytes(data); +// verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 16,IllegalArgumentException.class); +// +// +// //test SM4 +// algorithm = CryptoAlgorithm.SM4; +// +// //Case 1: SM4 with 16 bytes data +// data = new byte[16]; +// random.nextBytes(data); +// //密文长度 = IV长度 + 真实密文长度 +// verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 3*16, null); +// +// //Case 2: SM4 with 33 bytes data +// data = new byte[33]; +// random.nextBytes(data); +// verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 4*16,null); +// +// //Case 3: SM4 with 3 bytes data +// data = new byte[3]; +// random.nextBytes(data); +// verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 2*16,null); +// +// //Case 4: SM4 with 0 bytes data +// data = new byte[0]; +// random.nextBytes(data); +// verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 2*16,null); +// +// //Case 5 SM4 with null +// data = null; +// verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 16,IllegalArgumentException.class); +// } +// +// //不同明文输入下,用来简化加解密过程的method +// private void verifyGetSymmetricEncryptionFunction(SymmetricCryptography symmetricCrypto, CryptoAlgorithm algorithm, +// byte[] data, int expectedCiphertextLength, Class expectedException){ +// +// //初始化一个异常 +// Exception actualEx = null; +// +// try { +// SymmetricEncryptionFunction sef = symmetricCrypto.getSymmetricEncryptionFunction(algorithm); +// //验证获取的算法实例非空 +// assertNotNull(sef); +// +// SymmetricKey symmetricKey = (SymmetricKey) sef.generateSymmetricKey(); +// +// //验证SymmetricKey的getAlgorithm方法 +// assertEquals(algorithm, symmetricKey.getAlgorithm()); +// //验证SymmetricKey的getRawKeyBytes方法 +// assertEquals(16, symmetricKey.getRawKeyBytes().length); +// //验证SymmetricKey的toBytes方法 +// assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},new byte[]{SYMMETRIC_KEY.CODE},symmetricKey.getRawKeyBytes()), symmetricKey.toBytes()); +// +// +// Ciphertext ciphertext = sef.encrypt(symmetricKey,data); +// +// //Ciphertext中算法标识与入参算法一致 +// assertEquals(algorithm, ciphertext.getAlgorithm()); +// //验证原始密文长度与预期长度一致 +// assertEquals(expectedCiphertextLength, ciphertext.getRawCiphertext().length); +// //验证密文数据长度=算法标识长度+预期长度 +// byte[] ciphertextBytes = ciphertext.toBytes(); +// assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},ciphertext.getRawCiphertext()), ciphertextBytes); +// +// +// //验证equal +// assertTrue(ciphertext.equals(ciphertext)); +// assertEquals(ciphertext.hashCode(),ciphertext.hashCode()); +// +// //验证SymmetricEncryptionFunction的decrypt +// assertArrayEquals(data, sef.decrypt(symmetricKey,ciphertext)); +// +// //测试SymmetricEncryptionFunction的输入输出流的加解密方法 +// InputStream inPlaintext = new ByteArrayInputStream(data); +// //16字节的明文输入,将会产生32字节的密文 +// OutputStream outCiphertext = new ByteArrayOutputStream(ciphertext.toBytes().length); +// InputStream inCiphertext = new ByteArrayInputStream(ciphertext.toBytes()); +// OutputStream outPlaintext = new ByteArrayOutputStream(data.length); +// sef.encrypt(symmetricKey, inPlaintext, outCiphertext); +// sef.decrypt(symmetricKey, inCiphertext, outPlaintext); +// +// //验证SymmetricEncryptionFunction的supportCiphertext方法 +// assertTrue(sef.supportCiphertext(ciphertextBytes)); +// +// //验证SymmetricEncryptionFunction的resolveCiphertext方法 +// assertEquals(ciphertext, sef.resolveCiphertext(ciphertextBytes)); +// +// //验证SymmetricEncryptionFunction的supportSymmetricKey方法 +// assertTrue(sef.supportSymmetricKey(symmetricKey.toBytes())); +// +// //验证SymmetricEncryptionFunction的resolveSymmetricKey方法 +// assertEquals(symmetricKey, sef.resolveSymmetricKey(symmetricKey.toBytes())); +// +// //验证SymmetricEncryptionFunction的getAlgorithm +// assertEquals(algorithm, sef.getAlgorithm()); +// +// } catch (Exception e){ +// actualEx = e; +// } +// +// if (expectedException == null) { +// assertNull(actualEx); +// } +// else { +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// +// @Test +// public void testDecrypt() { +// +// SymmetricCryptography symmetricCrypto = new SymmetricCryptographyImpl(); +// Random randomData = new Random(); +// Random randomKey = new Random(); +// +// +// //test AES +// CryptoAlgorithm algorithm = CryptoAlgorithm.AES; +// SymmetricEncryptionFunction sef = symmetricCrypto.getSymmetricEncryptionFunction(algorithm); +// +// byte[] data = new byte[16]; +// randomData.nextBytes(data); +// byte[] key = new byte[16]; +// randomKey.nextBytes(key); +// +// SymmetricKey symmetricKey = new SymmetricKey(algorithm, key); +// byte[] ciphertextBytes = sef.encrypt(symmetricKey,data).toBytes(); +// +// verifyDecrypt(symmetricCrypto, algorithm, key, data, ciphertextBytes, null); +// +// //密钥的算法标识与密文的算法标识不一致情况 +// verifyDecrypt(symmetricCrypto, CryptoAlgorithm.SM4, key, data, ciphertextBytes, IllegalArgumentException.class); +// +// //密文末尾两个字节丢失情况下,抛出异常 +// byte[] truncatedCiphertextBytes = new byte[ciphertextBytes.length-2]; +// System.arraycopy(ciphertextBytes,0,truncatedCiphertextBytes,0,truncatedCiphertextBytes.length); +// verifyDecrypt(symmetricCrypto, algorithm, key, data, truncatedCiphertextBytes, IllegalArgumentException.class); +// +// byte[] ciphertextBytesWithWrongAlgCode = ciphertextBytes; +// ciphertextBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyDecrypt(symmetricCrypto,algorithm,key,data,ciphertextBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// ciphertextBytes = null; +// verifyDecrypt(symmetricCrypto,algorithm,key,data,ciphertextBytes,NullPointerException.class); +// +// +// //test SM4 +// algorithm = CryptoAlgorithm.SM4; +// sef = symmetricCrypto.getSymmetricEncryptionFunction(algorithm); +// symmetricKey = new SymmetricKey(algorithm, key); +// ciphertextBytes = sef.encrypt(symmetricKey,data).toBytes(); +// +// verifyDecrypt(symmetricCrypto, algorithm, key, data, ciphertextBytes, null); +// +// //密钥的算法标识与密文的算法标识不一致情况 +// verifyDecrypt(symmetricCrypto, CryptoAlgorithm.AES, key, data, ciphertextBytes, IllegalArgumentException.class); +// +// //密文末尾两个字节丢失情况下,抛出异常 +// truncatedCiphertextBytes = new byte[ciphertextBytes.length-2]; +// System.arraycopy(ciphertextBytes,0,truncatedCiphertextBytes,0,truncatedCiphertextBytes.length); +// verifyDecrypt(symmetricCrypto, algorithm, key, data, truncatedCiphertextBytes, IllegalArgumentException.class); +// +// ciphertextBytesWithWrongAlgCode = ciphertextBytes; +// ciphertextBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyDecrypt(symmetricCrypto,algorithm,key,data,ciphertextBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// ciphertextBytes = null; +// verifyDecrypt(symmetricCrypto,algorithm,key,data,ciphertextBytes,NullPointerException.class); +// } +// +// private void verifyDecrypt(SymmetricCryptography symmetricCrypto, CryptoAlgorithm algorithm, +// byte[] key, byte[] data, byte[] ciphertextBytes, Class expectedException) { +// +// Exception actualEx = null; +// +// try { +// SymmetricKey symmetricKey = new SymmetricKey(algorithm,key); +// +// byte[] plaintext = symmetricCrypto.decrypt(symmetricKey.toBytes(), ciphertextBytes); +// +// //解密后的明文与初始的明文一致 +// assertArrayEquals(data,plaintext); +// } +// catch (Exception e){ +// actualEx = e; +// } +// +// if (expectedException == null) { +// assertNull(actualEx); +// } +// else { +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// +// @Test +// public void testResolveCiphertext() { +// +// SymmetricCryptography symmetricCrypto = new SymmetricCryptographyImpl(); +// Random randomData = new Random(); +// Random randomKey = new Random(); +// +// //test AES +// CryptoAlgorithm algorithm = CryptoAlgorithm.AES; +// SymmetricEncryptionFunction sef = symmetricCrypto.getSymmetricEncryptionFunction(algorithm); +// +// byte[] data = new byte[16]; +// randomData.nextBytes(data); +// byte[] key = new byte[16]; +// randomKey.nextBytes(key); +// +// SymmetricKey symmetricKey = new SymmetricKey(algorithm, key); +// byte[] ciphertextBytes = sef.encrypt(symmetricKey,data).toBytes(); +// verifyResolveCiphertext(symmetricCrypto, algorithm, ciphertextBytes, null); +// +// byte[] truncatedCiphertextBytes = new byte[ciphertextBytes.length-2]; +// System.arraycopy(ciphertextBytes,0,truncatedCiphertextBytes,0,truncatedCiphertextBytes.length); +// verifyResolveCiphertext(symmetricCrypto,algorithm,truncatedCiphertextBytes,IllegalArgumentException.class); +// +// byte[] ciphertextBytesWithWrongAlgCode = ciphertextBytes; +// ciphertextBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyResolveCiphertext(symmetricCrypto,algorithm,ciphertextBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// ciphertextBytes = null; +// verifyResolveCiphertext(symmetricCrypto,algorithm,ciphertextBytes,NullPointerException.class); +// +// +// //test SM4 +// algorithm = CryptoAlgorithm.SM4; +// sef = symmetricCrypto.getSymmetricEncryptionFunction(algorithm); +// +// symmetricKey = new SymmetricKey(algorithm, key); +// ciphertextBytes = sef.encrypt(symmetricKey,data).toBytes(); +// +// verifyResolveCiphertext(symmetricCrypto, algorithm, ciphertextBytes, null); +// +// truncatedCiphertextBytes = new byte[ciphertextBytes.length-2]; +// System.arraycopy(ciphertextBytes,0,truncatedCiphertextBytes,0,truncatedCiphertextBytes.length); +// verifyResolveCiphertext(symmetricCrypto,algorithm,truncatedCiphertextBytes,IllegalArgumentException.class); +// +// ciphertextBytesWithWrongAlgCode = ciphertextBytes; +// ciphertextBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyResolveCiphertext(symmetricCrypto,algorithm,ciphertextBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// ciphertextBytes = null; +// verifyResolveCiphertext(symmetricCrypto,algorithm,ciphertextBytes,NullPointerException.class); +// } +// +// private void verifyResolveCiphertext(SymmetricCryptography symmetricCrypto, CryptoAlgorithm algorithm, byte[] ciphertextBytes, +// Class expectedException) { +// +// Exception actualEx = null; +// +// try { +// Ciphertext ciphertext = symmetricCrypto.resolveCiphertext(ciphertextBytes); +// +// assertNotNull(ciphertext); +// +// assertEquals(algorithm, ciphertext.getAlgorithm()); +// +// assertEquals(0, ciphertext.getRawCiphertext().length % 16); +// +// assertArrayEquals(ciphertextBytes, ciphertext.toBytes()); +// } +// catch (Exception e){ +// actualEx = e; +// } +// +// if (expectedException == null) { +// assertNull(actualEx); +// } +// else { +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// +// @Test +// public void testTryResolveCiphertext() { +// } +// +// +// +// @Test +// public void testResolveSymmetricKey() { +// +// SymmetricCryptography symmetricCrypto = new SymmetricCryptographyImpl(); +// +// //test AES +// CryptoAlgorithm algorithm = CryptoAlgorithm.AES; +// +// Random randomKey = new Random(); +// byte[] key = new byte[16]; +// randomKey.nextBytes(key); +// +// byte[] symmetricKeyBytes = BytesUtils.concat(new byte[]{algorithm.CODE},new byte[]{SYMMETRIC_KEY.CODE},key); +// verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytes,null); +// +// byte[] truncatedSymmetricKeyBytes = new byte[symmetricKeyBytes.length-2]; +// System.arraycopy(symmetricKeyBytes,0,truncatedSymmetricKeyBytes,0,truncatedSymmetricKeyBytes.length); +// verifyResolveSymmetricKey(symmetricCrypto,algorithm,truncatedSymmetricKeyBytes,IllegalArgumentException.class); +// +// byte[] symmetricKeyBytesWithWrongAlgCode = symmetricKeyBytes; +// symmetricKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// byte[] symmetricKeyBytesWithWrongKeyType= symmetricKeyBytes; +// System.arraycopy(symmetricKeyBytes,0,symmetricKeyBytesWithWrongKeyType,0,symmetricKeyBytesWithWrongKeyType.length); +// symmetricKeyBytesWithWrongKeyType[1] = PRIV_KEY.CODE; +// verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytesWithWrongKeyType,IllegalArgumentException.class); +// +// symmetricKeyBytes = null; +// verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytes,NullPointerException.class); +// +// +// //test SM4 +// algorithm = CryptoAlgorithm.SM4; +// symmetricKeyBytes = BytesUtils.concat(new byte[]{algorithm.CODE},new byte[]{SYMMETRIC_KEY.CODE},key); +// +// verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytes,null); +// +// truncatedSymmetricKeyBytes = new byte[symmetricKeyBytes.length-2]; +// System.arraycopy(symmetricKeyBytes,0,truncatedSymmetricKeyBytes,0,truncatedSymmetricKeyBytes.length); +// verifyResolveSymmetricKey(symmetricCrypto,algorithm,truncatedSymmetricKeyBytes,IllegalArgumentException.class); +// +// symmetricKeyBytesWithWrongAlgCode = symmetricKeyBytes; +// symmetricKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; +// verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytesWithWrongAlgCode,IllegalArgumentException.class); +// +// symmetricKeyBytesWithWrongKeyType= symmetricKeyBytes; +// System.arraycopy(symmetricKeyBytes,0,symmetricKeyBytesWithWrongKeyType,0,symmetricKeyBytesWithWrongKeyType.length); +// symmetricKeyBytesWithWrongKeyType[1] = PRIV_KEY.CODE; +// verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytesWithWrongKeyType,IllegalArgumentException.class); +// +// symmetricKeyBytes = null; +// verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytes,NullPointerException.class); +// } +// +// private void verifyResolveSymmetricKey(SymmetricCryptography symmetricCrypto, CryptoAlgorithm algorithm, byte[] symmetricKeyBytes, +// Class expectedException) { +// +// Exception actualEx = null; +// +// try { +// SymmetricKey symmetricKey = symmetricCrypto.resolveSymmetricKey(symmetricKeyBytes); +// +// assertNotNull(symmetricKey); +// +// assertEquals(algorithm, symmetricKey.getAlgorithm()); +// +// assertEquals(16, symmetricKey.getRawKeyBytes().length); +// +// assertArrayEquals(symmetricKeyBytes, symmetricKey.toBytes()); +// } +// catch (Exception e){ +// actualEx = e; +// } +// +// if (expectedException == null) { +// assertNull(actualEx); +// } +// else { +// assertNotNull(actualEx); +// assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); +// } +// } +// +// @Test +// public void testTryResolveSymmetricKey() { +// } +//} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressEncoding.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressEncoding.java index bc4a08a8..77db928b 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressEncoding.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressEncoding.java @@ -5,7 +5,6 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.io.BytesEncoding; import com.jd.blockchain.utils.io.BytesUtils; @@ -56,10 +55,10 @@ public class AddressEncoding { public static Bytes generateAddress(PubKey pubKey) { byte[] h1Bytes = ShaUtils.hash_256(pubKey.getRawKeyBytes()); byte[] h2Bytes = RipeMD160Utils.hash(h1Bytes); - byte[] xBytes = BytesUtils.concat(new byte[]{AddressVersion.V1.CODE, pubKey.getAlgorithm().CODE}, h2Bytes); + byte[] xBytes = BytesUtils.concat(new byte[] { AddressVersion.V1.CODE}, CryptoAlgorithm.toBytes(pubKey.getAlgorithm()), h2Bytes); byte[] checksum = Arrays.copyOf(ShaUtils.hash_256(ShaUtils.hash_256(xBytes)), 4); byte[] addressBytes = BytesUtils.concat(xBytes, checksum); - + return new Bytes(addressBytes); } diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressVersion.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressVersion.java index dff8877b..5e741abc 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressVersion.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressVersion.java @@ -1,9 +1,20 @@ package com.jd.blockchain.crypto; +/** + * The version of Blockchain Address generation rule;
+ * + * + * + * @author huanghaiquan + * + */ public enum AddressVersion { V1((byte) 0x91); + // Note: Implementor can only add new enum items, cann't remove or modify + // existing enum items; + public final byte CODE; AddressVersion(byte code) { diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/base/BaseCryptoBytes.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/BaseCryptoBytes.java similarity index 71% rename from source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/base/BaseCryptoBytes.java rename to source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/BaseCryptoBytes.java index 3fc2ac70..6ddfc545 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/base/BaseCryptoBytes.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/BaseCryptoBytes.java @@ -1,9 +1,7 @@ -package com.jd.blockchain.crypto.base; +package com.jd.blockchain.crypto; import java.util.Arrays; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoBytes; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.io.BytesSlice; import com.jd.blockchain.utils.io.BytesUtils; @@ -25,17 +23,22 @@ public abstract class BaseCryptoBytes extends Bytes implements CryptoBytes { super(cryptoBytes); CryptoAlgorithm algorithm = decodeAlgorithm(cryptoBytes); if (!support(algorithm)) { - throw new IllegalArgumentException("Not supported algorithm[" + algorithm.toString() + "]!"); + throw new CryptoException("Not supported algorithm[" + algorithm.toString() + "]!"); } this.algorithm = algorithm; } static byte[] encodeBytes(CryptoAlgorithm algorithm, byte[] rawCryptoBytes) { - return BytesUtils.concat(new byte[] { algorithm.CODE }, rawCryptoBytes); + return BytesUtils.concat(CryptoAlgorithm.toBytes(algorithm), rawCryptoBytes); } static CryptoAlgorithm decodeAlgorithm(byte[] cryptoBytes) { - return CryptoAlgorithm.valueOf(cryptoBytes[0]); + short algorithmCode = BytesUtils.toShort(cryptoBytes, 0); + CryptoAlgorithm algorithm = CryptoServiceProviders.getAlgorithm(algorithmCode); + if (algorithm == null) { + throw new CryptoException("The algorithm with code[" + algorithmCode + "] is not supported!"); + } + return algorithm; } protected abstract boolean support(CryptoAlgorithm algorithm); @@ -44,6 +47,7 @@ public abstract class BaseCryptoBytes extends Bytes implements CryptoBytes { return Arrays.copyOfRange(cryptoBytes, 1, cryptoBytes.length); } + @Override public CryptoAlgorithm getAlgorithm() { // return resolveAlgorithm(encodedBytes); return algorithm; diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/BaseCryptoKey.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/BaseCryptoKey.java new file mode 100644 index 00000000..db95dbd4 --- /dev/null +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/BaseCryptoKey.java @@ -0,0 +1,46 @@ +package com.jd.blockchain.crypto; + +import java.io.Serializable; + +import com.jd.blockchain.utils.io.BytesSlice; +import com.jd.blockchain.utils.io.BytesUtils; + +public abstract class BaseCryptoKey extends BaseCryptoBytes implements CryptoKey, Serializable { + + public static final int KEY_TYPE_BYTES = 1; + private static final long serialVersionUID = 4543074827807908363L; + +// public BaseCryptoKey() { +// super(); +// } + + protected BaseCryptoKey(CryptoAlgorithm algorithm, byte[] rawKeyBytes, CryptoKeyType keyType) { + super(algorithm, encodeKeyBytes(rawKeyBytes, keyType)); + } + + public BaseCryptoKey(byte[] cryptoBytes) { + super(cryptoBytes); + CryptoKeyType keyType = decodeKeyType(getRawCryptoBytes()); + if (getKeyType() != keyType) { + throw new CryptoException("CryptoKey doesn't support keyType[" + keyType + "]!"); + } + } + + private static byte[] encodeKeyBytes(byte[] rawKeyBytes, CryptoKeyType keyType) { + return BytesUtils.concat(new byte[] { keyType.CODE }, rawKeyBytes); + } + + private static CryptoKeyType decodeKeyType(BytesSlice cryptoBytes) { + return CryptoKeyType.valueOf(cryptoBytes.getByte()); + } + + @Override + protected boolean support(CryptoAlgorithm algorithm) { + return CryptoAlgorithm.hasAsymmetricKey(algorithm) || CryptoAlgorithm.hasSymmetricKey(algorithm); + } + + @Override + public byte[] getRawKeyBytes() { + return getRawCryptoBytes().getBytesCopy(1); + } +} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithm.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithm.java index 33a9c562..5837590b 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithm.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithm.java @@ -1,80 +1,110 @@ package com.jd.blockchain.crypto; -import com.jd.blockchain.base.data.TypeCodes; -import com.jd.blockchain.binaryproto.EnumContract; -import com.jd.blockchain.binaryproto.EnumField; +import com.jd.blockchain.binaryproto.DataContract; +import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.ValueType; +import com.jd.blockchain.utils.io.BytesUtils; +@DataContract(code = TypeCodes.CRYPTO_ALGORITHM) +public interface CryptoAlgorithm { -@EnumContract(code= TypeCodes.ENUM_TYPE_CRYPTO_ALGORITHM) -public enum CryptoAlgorithm { - - SHA256(CryptoAlgorithmType.HASH, (byte) 0x01, false, false), - - RIPEMD160(CryptoAlgorithmType.HASH, (byte) 0x02, false, false), - - SM3(CryptoAlgorithmType.HASH, (byte) 0x03, false, false), - - JNISHA256(CryptoAlgorithmType.HASH, (byte) 0x04, false, false), - - JNIRIPEMD160(CryptoAlgorithmType.HASH, (byte) 0x05, false, false), + /** + * 随机数算法标识; + */ + static final int RANDOM_ALGORITHM = 0x1000; - // 非对称签名/加密算法; + /** + * 哈希数算法标识; + */ + static final int HASH_ALGORITHM = 0x2000; /** - * RSA 签名算法;可签名,可加密; + * 签名算法标识; */ - RSA(CryptoAlgorithmType.ASYMMETRIC, (byte) 0x01, true, true), + static final int SIGNATURE_ALGORITHM = 0x4000; /** - * ED25519 签名算法;只用于签名,没有加密特性; + * 加密算法标识; */ - ED25519(CryptoAlgorithmType.ASYMMETRIC, (byte) 0x02, true, false), + static final int ENCRYPTION_ALGORITHM = 0x8000; /** - * ECDSA 签名算法;只用于签名,没有加密特性; + * 扩展密码算法标识;
+ * 表示除了 + * {@link #RANDOM_ALGORITHM}、{@link #HASH_ALGORITHM}、{@link #SIGNATURE_ALGORITHM}、{@link #ENCRYPTION_ALGORITHM} + * 之外的其它非标准分类的密码算法,诸如加法同态算法、多方求和算法等; */ - ECDSA(CryptoAlgorithmType.ASYMMETRIC, (byte) 0x03, true, false), + static final int EXT_ALGORITHM = 0x0000; /** - * 国密 SM2 算法;可签名,可加密; + * 非对称密钥标识; */ - SM2(CryptoAlgorithmType.ASYMMETRIC, (byte) 0x04, true, true), + static final int ASYMMETRIC_KEY = 0x0100; /** - * JNIED25519 签名算法;只用于签名,没有加密特性; + * 对称密钥标识; */ - JNIED25519(CryptoAlgorithmType.ASYMMETRIC, (byte) 0x05, true, false), + static final int SYMMETRIC_KEY = 0x0200; - // 对称加密; /** - * AES 算法;可加密; + * 算法编码的字节长度;等同于 {@link #toBytes(CryptoAlgorithm)} 返回的字节数组的长度; */ - AES(CryptoAlgorithmType.SYMMETRIC, (byte) 0x01, false, true), + static final int CODE_SIZE = 2; - SM4(CryptoAlgorithmType.SYMMETRIC, (byte) 0x02, false, true), + /** + * 密码算法的唯一编码; + *

+ * 长度16位,高4位标识算法类型(包括: {@link #RANDOM_ALGORITHM}, {@link #HASH_ALGORITHM}, + * {@link #SIGNATURE_ALGORITHM}, {@link #ENCRYPTION_ALGORITHM}, + * {@link #EXT_ALGORITHM}) 5 种); 接下来4位标识密钥类型(包括:{@link #SYMMETRIC_KEY}, + * {@link #ASYMMETRIC_KEY}); 最后8位是算法唯一ID; + */ + @DataField(primitiveType = ValueType.INT16, order = 0) + short code(); - // 随机性; /** - * 随机数算法,待定; + * 算法名称; + *

+ * + * 实现者应该遵循“英文字符大写”的命名规范,并确保唯一性;
+ * 例如,sha256 和 SHA256 将被视为相同的名称; + * + * @return */ - JAVA_SECURE(CryptoAlgorithmType.RANDOM, (byte) 0x01, false, false); + String name(); /** - * 密码算法的代号;
- * 注:只占16位; + * + * @return */ - @EnumField(type= ValueType.INT8) - public final byte CODE; + static byte[] toBytes(CryptoAlgorithm algorithm) { + return BytesUtils.toBytes(algorithm.code()); + } - private final boolean signable; + static short resolveCode(byte[] algorithmBytes) { + return BytesUtils.toShort(algorithmBytes, 0); + } - private final boolean encryptable; + static short resolveCode(byte[] algorithmBytes, int offset) { + return BytesUtils.toShort(algorithmBytes, offset); + } + + static boolean match(CryptoAlgorithm algorithm, byte[] algorithmBytes) { + return algorithm.code() == BytesUtils.toShort(algorithmBytes, 0); + } - private CryptoAlgorithm(byte algType, byte algId, boolean signable, boolean encryptable) { - this.CODE = (byte) (algType | algId); - this.signable = signable; - this.encryptable = encryptable; + static boolean match(CryptoAlgorithm algorithm, byte[] algorithmBytes, int offset) { + return algorithm.code() == BytesUtils.toShort(algorithmBytes, offset); + } + + /** + * 是否属于随机数算法; + * + * @return + */ + static boolean isRandomAlgorithm(CryptoAlgorithm algorithm) { + return RANDOM_ALGORITHM == (algorithm.code() & RANDOM_ALGORITHM); } /** @@ -82,69 +112,73 @@ public enum CryptoAlgorithm { * * @return */ - public boolean isHash() { - return (CODE & CryptoAlgorithmType.HASH) == CryptoAlgorithmType.HASH; + static boolean isHashAlgorithm(CryptoAlgorithm algorithm) { + return HASH_ALGORITHM == (algorithm.code() & HASH_ALGORITHM); } /** - * 是否属于非对称密码算法; + * 是否属于签名算法; * * @return */ - public boolean isAsymmetric() { - return (CODE & CryptoAlgorithmType.ASYMMETRIC) == CryptoAlgorithmType.ASYMMETRIC; + static boolean isSignatureAlgorithm(CryptoAlgorithm algorithm) { + return SIGNATURE_ALGORITHM == (algorithm.code() & SIGNATURE_ALGORITHM); } /** - * 是否属于对称密码算法; + * 是否属于加密算法; * * @return */ - public boolean isSymmetric() { - return (CODE & CryptoAlgorithmType.SYMMETRIC) == CryptoAlgorithmType.SYMMETRIC; + static boolean isEncryptionAlgorithm(CryptoAlgorithm algorithm) { + return ENCRYPTION_ALGORITHM == (algorithm.code() & ENCRYPTION_ALGORITHM); } /** - * 是否属于随机数算法; + * 是否属于扩展密码算法; * * @return */ - public boolean isRandom() { - return (CODE & CryptoAlgorithmType.RANDOM) == CryptoAlgorithmType.RANDOM; + static boolean isExtAlgorithm(CryptoAlgorithm algorithm) { + return EXT_ALGORITHM == (algorithm.code() & 0xF000); } /** - * 是否支持签名操作; + * 算法是否包含非对称密钥; * * @return */ - public boolean isSignable() { - return signable; + static boolean hasAsymmetricKey(CryptoAlgorithm algorithm) { + return ASYMMETRIC_KEY == (algorithm.code() & ASYMMETRIC_KEY); } /** - * 是否支持加密操作; + * 算法是否包含对称密钥; * * @return */ - public boolean isEncryptable() { - return encryptable; + static boolean hasSymmetricKey(CryptoAlgorithm algorithm) { + return SYMMETRIC_KEY == (algorithm.code() & SYMMETRIC_KEY); } /** - * 返回指定编码对应的枚举实例;
+ * 是否属于对称加密算法; * - * 如果不存在,则返回 null; + * @param algorithm + * @return + */ + static boolean isSymmetricEncryptionAlgorithm(CryptoAlgorithm algorithm) { + return isEncryptionAlgorithm(algorithm) && hasSymmetricKey(algorithm); + } + + /** + * 是否属于非对称加密算法; * - * @param code + * @param algorithm * @return */ - public static CryptoAlgorithm valueOf(byte code) { - for (CryptoAlgorithm alg : CryptoAlgorithm.values()) { - if (alg.CODE == code) { - return alg; - } - } - throw new IllegalArgumentException("CryptoAlgorithm doesn't support enum code[" + code + "]!"); + static boolean isAsymmetricEncryptionAlgorithm(CryptoAlgorithm algorithm) { + return isEncryptionAlgorithm(algorithm) && hasAsymmetricKey(algorithm); } + } diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithmDefinition.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithmDefinition.java new file mode 100644 index 00000000..642a27d0 --- /dev/null +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithmDefinition.java @@ -0,0 +1,118 @@ +package com.jd.blockchain.crypto; + +public final class CryptoAlgorithmDefinition implements CryptoAlgorithm { + + private short code; + + private String name; + + CryptoAlgorithmDefinition(String name, short code) { + this.code = code; + this.name = name; + } + + @Override + public short code() { + return this.code; + } + + @Override + public String name() { + return name; + } + + @Override + public String toString() { + return name + "[" + code + "]"; + } + + /** + * 声明一项哈希算法; + * + * @param name + * 算法名称; + * @param uid + * 算法ID;需要在同类算法中保持唯一性; + * @return + */ + public static CryptoAlgorithm defineHash(String name, byte uid) { + short code = (short) (HASH_ALGORITHM | (uid & 0x00FF)); + return new CryptoAlgorithmDefinition(name, code); + } + + /** + * 声明一项非对称密码算法; + * + * @param name + * 算法名称; + * @param uid + * 算法ID;需要在同类算法中保持唯一性; + * @return + */ + public static CryptoAlgorithm defineSignature(String name, boolean encryptable, byte uid) { + short code; + if (encryptable) { + code = (short) (SIGNATURE_ALGORITHM | ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | (uid & 0x00FF)); + } else { + code = (short) (SIGNATURE_ALGORITHM | ASYMMETRIC_KEY | (uid & 0x00FF)); + } + return new CryptoAlgorithmDefinition(name, code); + } + + /** + * 声明一项非对称加密算法; + * + * @param name + * 算法名称; + * @param uid + * 算法ID;需要在同类算法中保持唯一性; + * @return + */ + public static CryptoAlgorithm defineAsymmetricEncryption(String name, byte uid) { + short code = (short) (ENCRYPTION_ALGORITHM | ASYMMETRIC_KEY | (uid & 0x00FF)); + return new CryptoAlgorithmDefinition(name, code); + } + + /** + * 声明一项对称密码算法; + * + * @param name + * 算法名称; + * @param uid + * 算法ID;需要在同类算法中保持唯一性; + * @return + */ + public static CryptoAlgorithm defineSymmetricEncryption(String name, byte uid) { + short code = (short) (ENCRYPTION_ALGORITHM | SYMMETRIC_KEY | (uid & 0x00FF)); + return new CryptoAlgorithmDefinition(name, code); + } + + /** + * 声明一项随机数算法; + * + * @param name + * 算法名称; + * @param uid + * 算法ID;需要在同类算法中保持唯一性; + * @return + */ + public static CryptoAlgorithm defineRandom(String name, byte uid) { + short code = (short) (RANDOM_ALGORITHM | (uid & 0x00FF)); + return new CryptoAlgorithmDefinition(name, code); + } + + /** + * 声明一项扩展的密码算法; + * + * @param name + * 算法名称; + * @param uid + * 算法ID;需要在同类算法中保持唯一性; + * @return + */ + public static CryptoAlgorithm definExt(String name, byte uid) { + short code = (short) (EXT_ALGORITHM | (uid & 0x00FF)); + return new CryptoAlgorithmDefinition(name, code); + } + +} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithmType.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithmType.java index 10e38f77..35cb66ec 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithmType.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithmType.java @@ -1,24 +1,24 @@ -package com.jd.blockchain.crypto; - -public class CryptoAlgorithmType { - /** - * Hash 类算法的掩码; - */ - public static final byte HASH = 0x10; - - /** - * 非对称加密类算法的掩码; - */ - public static final byte ASYMMETRIC = 0x20; - - /** - * 对称加密类算法的掩码; - */ - public static final byte SYMMETRIC = 0x30; - - /** - * 随机数类算法的掩码; - */ - public static final byte RANDOM = 0x40; - -} +//package com.jd.blockchain.crypto; +// +//public class CryptoAlgorithmType { +// /** +// * Hash 类算法的掩码; +// */ +// public static final byte HASH = 0x10; +// +// /** +// * 非对称加密类算法的掩码; +// */ +// public static final byte ASYMMETRIC = 0x20; +// +// /** +// * 对称加密类算法的掩码; +// */ +// public static final byte SYMMETRIC = 0x30; +// +// /** +// * 随机数类算法的掩码; +// */ +// public static final byte RANDOM = 0x40; +// +//} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithm_Enum.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithm_Enum.java new file mode 100644 index 00000000..c9209b03 --- /dev/null +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoAlgorithm_Enum.java @@ -0,0 +1,150 @@ +//package com.jd.blockchain.crypto; +// +//import com.jd.blockchain.base.data.TypeCodes; +//import com.jd.blockchain.binaryproto.EnumContract; +//import com.jd.blockchain.binaryproto.EnumField; +//import com.jd.blockchain.utils.ValueType; +// +// +//@EnumContract(code= TypeCodes.CRYPTO_ALGORITHM) +//public enum CryptoAlgorithm_Enum { +// +// SHA256(CryptoAlgorithmType.HASH, (byte) 0x01, false, false), +// +// RIPEMD160(CryptoAlgorithmType.HASH, (byte) 0x02, false, false), +// +// SM3(CryptoAlgorithmType.HASH, (byte) 0x03, false, false), +// +// JNISHA256(CryptoAlgorithmType.HASH, (byte) 0x04, false, false), +// +// JNIRIPEMD160(CryptoAlgorithmType.HASH, (byte) 0x05, false, false), +// +// // 非对称签名/加密算法; +// +// /** +// * RSA 签名算法;可签名,可加密; +// */ +// RSA(CryptoAlgorithmType.ASYMMETRIC, (byte) 0x01, true, true), +// +// /** +// * ED25519 签名算法;只用于签名,没有加密特性; +// */ +// ED25519(CryptoAlgorithmType.ASYMMETRIC, (byte) 0x02, true, false), +// +// /** +// * ECDSA 签名算法;只用于签名,没有加密特性; +// */ +// ECDSA(CryptoAlgorithmType.ASYMMETRIC, (byte) 0x03, true, false), +// +// /** +// * 国密 SM2 算法;可签名,可加密; +// */ +// SM2(CryptoAlgorithmType.ASYMMETRIC, (byte) 0x04, true, true), +// +// /** +// * JNIED25519 签名算法;只用于签名,没有加密特性; +// */ +// JNIED25519(CryptoAlgorithmType.ASYMMETRIC, (byte) 0x05, true, false), +// +// // 对称加密; +// /** +// * AES 算法;可加密; +// */ +// AES(CryptoAlgorithmType.SYMMETRIC, (byte) 0x01, false, true), +// +// SM4(CryptoAlgorithmType.SYMMETRIC, (byte) 0x02, false, true), +// +// // 随机性; +// /** +// * 随机数算法,待定; +// */ +// JAVA_SECURE(CryptoAlgorithmType.RANDOM, (byte) 0x01, false, false); +// +// /** +// * 密码算法的代号;
+// * 注:只占16位; +// */ +// @EnumField(type= ValueType.INT8) +// public final byte CODE; +// +// private final boolean signable; +// +// private final boolean encryptable; +// +// private CryptoAlgorithm_Enum(byte algType, byte algId, boolean signable, boolean encryptable) { +// this.CODE = (byte) (algType | algId); +// this.signable = signable; +// this.encryptable = encryptable; +// } +// +// /** +// * 是否属于摘要算法; +// * +// * @return +// */ +// public boolean isHash() { +// return (CODE & CryptoAlgorithmType.HASH) == CryptoAlgorithmType.HASH; +// } +// +// /** +// * 是否属于非对称密码算法; +// * +// * @return +// */ +// public boolean isAsymmetric() { +// return (CODE & CryptoAlgorithmType.ASYMMETRIC) == CryptoAlgorithmType.ASYMMETRIC; +// } +// +// /** +// * 是否属于对称密码算法; +// * +// * @return +// */ +// public boolean isSymmetric() { +// return (CODE & CryptoAlgorithmType.SYMMETRIC) == CryptoAlgorithmType.SYMMETRIC; +// } +// +// /** +// * 是否属于随机数算法; +// * +// * @return +// */ +// public boolean isRandom() { +// return (CODE & CryptoAlgorithmType.RANDOM) == CryptoAlgorithmType.RANDOM; +// } +// +// /** +// * 是否支持签名操作; +// * +// * @return +// */ +// public boolean isSignable() { +// return signable; +// } +// +// /** +// * 是否支持加密操作; +// * +// * @return +// */ +// public boolean isEncryptable() { +// return encryptable; +// } +// +// /** +// * 返回指定编码对应的枚举实例;
+// * +// * 如果不存在,则返回 null; +// * +// * @param code +// * @return +// */ +// public static CryptoAlgorithm_Enum valueOf(byte code) { +// for (CryptoAlgorithm_Enum alg : CryptoAlgorithm_Enum.values()) { +// if (alg.CODE == code) { +// return alg; +// } +// } +// throw new IllegalArgumentException("CryptoAlgorithm doesn't support enum code[" + code + "]!"); +// } +//} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoBytes.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoBytes.java index 2da141ef..8950a1ee 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoBytes.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoBytes.java @@ -13,7 +13,7 @@ public interface CryptoBytes extends BytesSerializable { /** * 算法标识符的长度; */ - int ALGORYTHM_BYTES = 1; + int ALGORYTHM_CODE_SIZE = CryptoAlgorithm.CODE_SIZE; /** * 算法; @@ -25,10 +25,12 @@ public interface CryptoBytes extends BytesSerializable { /** * 返回编码后的摘要信息;
* - * 这是算法标识 {@link #getAlgorithm()} 与原始的摘要数据 {@link #getRawDigest()} + * 这是算法标识 {@link #getAlgorithm()} 与原始的摘要数据 * 按照特定的编码方式合并后的结果; */ @Override byte[] toBytes(); + + } diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoFactory.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoFactory.java index 5cf15bbf..0eeaaae5 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoFactory.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoFactory.java @@ -1,15 +1,15 @@ -package com.jd.blockchain.crypto; - -import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; -import com.jd.blockchain.crypto.hash.HashCryptography; -import com.jd.blockchain.crypto.symmetric.SymmetricCryptography; - -public interface CryptoFactory { - - HashCryptography hashCryptography(); - - AsymmetricCryptography asymmetricCryptography(); - - SymmetricCryptography symmetricCryptography(); - -} +//package com.jd.blockchain.crypto; +// +//import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; +//import com.jd.blockchain.crypto.hash.HashCryptography; +//import com.jd.blockchain.crypto.symmetric.SymmetricCryptography; +// +//public interface CryptoFactory { +// +// HashCryptography hashCryptography(); +// +// AsymmetricCryptography asymmetricCryptography(); +// +// SymmetricCryptography symmetricCryptography(); +// +//} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKeyPairGenerator.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKeyPairGenerator.java index 2e3c9da9..d2591cc2 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKeyPairGenerator.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKeyPairGenerator.java @@ -9,6 +9,4 @@ public interface CryptoKeyPairGenerator { */ CryptoKeyPair generateKeyPair(); - - } diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKeyType.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKeyType.java index 7c94d2df..61dcbe28 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKeyType.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKeyType.java @@ -3,17 +3,17 @@ package com.jd.blockchain.crypto; public enum CryptoKeyType { /** - * 非对称密码算法的公钥 + * 非对称密钥的公钥 */ PUB_KEY((byte)0x01), /** - * 非对称密码算法的私钥; + * 非对称密钥的私钥; */ PRIV_KEY((byte)0x02), /** - * 对称密码算法的密钥; + * 对称密钥; */ SYMMETRIC_KEY((byte)0x03); @@ -29,7 +29,7 @@ public enum CryptoKeyType { return alg; } } - throw new IllegalArgumentException("CryptoKeyType doesn't support enum code[" + code + "]!"); + throw new CryptoException("CryptoKeyType doesn't support enum code[" + code + "]!"); } public byte getCODE() { diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoService.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoService.java new file mode 100644 index 00000000..4a835a83 --- /dev/null +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoService.java @@ -0,0 +1,9 @@ +package com.jd.blockchain.crypto; + +import java.util.Collection; + +public interface CryptoService { + + Collection getFunctions(); + +} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoServiceProviders.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoServiceProviders.java new file mode 100644 index 00000000..1a185cf9 --- /dev/null +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoServiceProviders.java @@ -0,0 +1,213 @@ +package com.jd.blockchain.crypto; + +import java.util.Collection; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.jd.blockchain.crypto.asymmetric.AsymmetricEncryptionFunction; +import com.jd.blockchain.crypto.asymmetric.SignatureFunction; +import com.jd.blockchain.crypto.hash.HashFunction; +import com.jd.blockchain.crypto.symmetric.SymmetricEncryptionFunction; +import com.jd.blockchain.provider.Provider; +import com.jd.blockchain.provider.ProviderManager; + +/** + * 密码服务提供者的管理器; + * + * @author huanghaiquan + * + */ +public final class CryptoServiceProviders { + + private static Logger LOGGER = LoggerFactory.getLogger(CryptoServiceProviders.class); + + private static Map functions = new ConcurrentHashMap<>(); + + private static Map algorithms = new ConcurrentHashMap<>(); + + private static Map names = new ConcurrentHashMap<>(); + + private static ProviderManager pm = new ProviderManager(); + + static { + loadDefaultProviders(); + } + + private static void loadDefaultProviders() { + ClassLoader cl = CryptoServiceProviders.class.getClassLoader(); + pm.installAllProviders(CryptoService.class, cl); + + Iterable> providers = pm.getAllProviders(CryptoService.class); + for (Provider provider : providers) { + register(provider); + } + } + + private static void register(Provider provider) { + for (CryptoFunction cryptoFunction : provider.getService().getFunctions()) { + + String name = cryptoFunction.getAlgorithm().name().toUpperCase(); + short code = cryptoFunction.getAlgorithm().code(); + CryptoAlgorithm algorithm = new CryptoAlgorithmDefinition(name, code); + if (CryptoAlgorithm.isRandomAlgorithm(algorithm) && !(cryptoFunction instanceof RandomFunction)) { + LOGGER.error(String.format( + "The random algorithm \"%s\" declared by provider[%s] does not implement the interface \"%s\"!", + algorithm.toString(), provider.getFullName(), RandomFunction.class.getName())); + continue; + } + if (CryptoAlgorithm.isAsymmetricEncryptionAlgorithm(algorithm) + && !(cryptoFunction instanceof AsymmetricEncryptionFunction)) { + LOGGER.error(String.format( + "The asymmetric encryption algorithm \"%s\" declared by the provider[%s] does not implement the interface \"%s\"!", + algorithm.toString(), provider.getFullName(), AsymmetricEncryptionFunction.class.getName())); + continue; + } + if (CryptoAlgorithm.isSignatureAlgorithm(algorithm) && !(cryptoFunction instanceof SignatureFunction)) { + LOGGER.error(String.format( + "The signature algorithm \"%s\" declared by the provider[%s] does not implement the interface \"%s\"!", + algorithm.toString(), provider.getFullName(), SignatureFunction.class.getName())); + continue; + } + if (CryptoAlgorithm.isSymmetricEncryptionAlgorithm(algorithm) + && !(cryptoFunction instanceof SymmetricEncryptionFunction)) { + LOGGER.error(String.format( + "The symmetric encryption algorithm \"%s\" declared by the provider[%s] does not implement the interface \"%s\"!", + algorithm.toString(), provider.getFullName(), SymmetricEncryptionFunction.class.getName())); + continue; + } + if (CryptoAlgorithm.isHashAlgorithm(algorithm) && !(cryptoFunction instanceof HashFunction)) { + LOGGER.error(String.format( + "The hash encryption algorithm \"%s\" declared by the provider[%s] does not implement the interface \"%s\"!", + algorithm.toString(), provider.getFullName(), HashFunction.class.getName())); + continue; + } + if (CryptoAlgorithm.isExtAlgorithm(algorithm) && (cryptoFunction instanceof RandomFunction + || cryptoFunction instanceof AsymmetricEncryptionFunction + || cryptoFunction instanceof SignatureFunction + || cryptoFunction instanceof SymmetricEncryptionFunction + || cryptoFunction instanceof HashFunction)) { + LOGGER.error(String.format( + "The ext algorithm \"%s\" declared by the provider[%s] can not implement the standard algorithm interface!", + algorithm.toString(), provider.getFullName())); + continue; + } + + if (functions.containsKey(algorithm.code()) || names.containsKey(algorithm.name())) { + LOGGER.error(String.format("The algorithm \"%s\" declared by the provider[%s] already exists!", + algorithm.toString(), provider.getFullName())); + continue; + } + + functions.put(algorithm.code(), cryptoFunction); + algorithms.put(algorithm.code(), algorithm); + names.put(algorithm.name(), algorithm.code()); + } + } + + private CryptoServiceProviders() { + } + + public static Collection getAllAlgorithms() { + return algorithms.values(); + } + + /** + * 返回指定编码的算法;
+ * 如果不存在,则返回 null; + * + * @param code + * @return + */ + public static CryptoAlgorithm getAlgorithm(short code) { + return algorithms.get(code); + } + + public static CryptoAlgorithm getAlgorithm(String name) { + Short code = names.get(name.toUpperCase()); + return code == null ? null : algorithms.get(code); + } + + public static RandomFunction getRandomFunction(CryptoAlgorithm algorithm) { + if (!CryptoAlgorithm.isRandomAlgorithm(algorithm)) { + throw new CryptoException("The specified algorithm " + algorithm.name() + "[" + algorithm.code() + + "] is not a random function!"); + } + CryptoFunction func = functions.get(algorithm.code()); + if (func == null) { + throw new CryptoException( + "Algorithm " + algorithm.name() + "[" + algorithm.code() + "] has no service provider!"); + } + + return (RandomFunction) func; + } + + public static HashFunction getHashFunction(CryptoAlgorithm algorithm) { + if (!CryptoAlgorithm.isHashAlgorithm(algorithm)) { + throw new CryptoException("The specified algorithm " + algorithm.name() + "[" + algorithm.code() + + "] is not a hash function!"); + } + CryptoFunction func = functions.get(algorithm.code()); + if (func == null) { + throw new CryptoException( + "Algorithm " + algorithm.name() + "[" + algorithm.code() + "] has no service provider!"); + } + + return (HashFunction) func; + } + + public static AsymmetricEncryptionFunction getAsymmetricEncryptionFunction(CryptoAlgorithm algorithm) { + if (!CryptoAlgorithm.isAsymmetricEncryptionAlgorithm(algorithm)) { + throw new CryptoException("The specified algorithm " + algorithm.name() + "[" + algorithm.code() + + "] is not a asymmetric encryption function!"); + } + CryptoFunction func = functions.get(algorithm.code()); + if (func == null) { + throw new CryptoException( + "Algorithm " + algorithm.name() + "[" + algorithm.code() + "] has no service provider!"); + } + + return (AsymmetricEncryptionFunction) func; + } + + public static SignatureFunction getSignatureFunction(CryptoAlgorithm algorithm) { + if (!CryptoAlgorithm.isSignatureAlgorithm(algorithm)) { + throw new CryptoException("The specified algorithm " + algorithm.name() + "[" + algorithm.code() + + "] is not a signature function!"); + } + CryptoFunction func = functions.get(algorithm.code()); + if (func == null) { + throw new CryptoException( + "Algorithm " + algorithm.name() + "[" + algorithm.code() + "] has no service provider!"); + } + + return (SignatureFunction) func; + } + + public static SymmetricEncryptionFunction getSymmetricEncryptionFunction(CryptoAlgorithm algorithm) { + if (!CryptoAlgorithm.isSymmetricEncryptionAlgorithm(algorithm)) { + throw new CryptoException("The specified algorithm " + algorithm.name() + "[" + algorithm.code() + + "] is not a symmetric encryption function!"); + } + CryptoFunction func = functions.get(algorithm.code()); + if (func == null) { + throw new CryptoException( + "Algorithm " + algorithm.name() + "[" + algorithm.code() + "] has no service provider!"); + } + + return (SymmetricEncryptionFunction) func; + } + + public static CryptoFunction getCryptoFunction(CryptoAlgorithm algorithm) { + CryptoFunction func = functions.get(algorithm.code()); + if (func == null) { + throw new CryptoException( + "Algorithm " + algorithm.name() + "[" + algorithm.code() + "] has no service provider!"); + } + + return func; + } + +} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoUtils.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoUtils.java index 4493a681..5bea9f61 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoUtils.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoUtils.java @@ -1,51 +1,73 @@ -package com.jd.blockchain.crypto; - -import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; -import com.jd.blockchain.crypto.asymmetric.AsymmetricEncryptionFunction; -import com.jd.blockchain.crypto.asymmetric.SignatureFunction; -import com.jd.blockchain.crypto.hash.HashCryptography; -import com.jd.blockchain.crypto.hash.HashFunction; -import com.jd.blockchain.crypto.impl.CryptoFactoryImpl; -import com.jd.blockchain.crypto.symmetric.SymmetricCryptography; -import com.jd.blockchain.crypto.symmetric.SymmetricEncryptionFunction; - -public class CryptoUtils { - - private static CryptoFactory CRYPTO_FACTORY = new CryptoFactoryImpl(); - - public static CryptoFactory crypto() { - return CRYPTO_FACTORY; - } - - - public static HashCryptography hashCrypto() { - return crypto().hashCryptography(); - } - - public static HashFunction hash(CryptoAlgorithm alg) { - return hashCrypto().getFunction(alg); - } - - - public static AsymmetricCryptography asymmCrypto() { - return crypto().asymmetricCryptography(); - } - - public static SignatureFunction sign(CryptoAlgorithm alg) { - return asymmCrypto().getSignatureFunction(alg); - } - - public static AsymmetricEncryptionFunction asymmEncrypt(CryptoAlgorithm alg) { - return asymmCrypto().getAsymmetricEncryptionFunction(alg); - } - - - public static SymmetricCryptography symmCrypto() { - return crypto().symmetricCryptography(); - } - - public static SymmetricEncryptionFunction symmEncrypt(CryptoAlgorithm alg) { - return symmCrypto().getSymmetricEncryptionFunction(alg); - } - -} +//package com.jd.blockchain.crypto; +// +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +//import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; +//import com.jd.blockchain.crypto.asymmetric.AsymmetricEncryptionFunction; +//import com.jd.blockchain.crypto.asymmetric.SignatureFunction; +//import com.jd.blockchain.crypto.hash.HashCryptography; +//import com.jd.blockchain.crypto.hash.HashFunction; +//import com.jd.blockchain.crypto.symmetric.SymmetricCryptography; +//import com.jd.blockchain.crypto.symmetric.SymmetricEncryptionFunction; +// +//public class CryptoUtils { +// +// private static Logger LOGGER = LoggerFactory.getLogger(CryptoUtils.class); +// +// private static final Object MUTEX = new Object(); +// +// private static final String STD = "com.jd.blockchain.crypto.impl.CryptoFactoryImpl"; +// +// private static volatile CryptoFactory STD_FACTORY; +// +// public static CryptoFactory crypto() { +// if (STD_FACTORY == null) { +// synchronized (MUTEX) { +// if (STD_FACTORY == null) { +// try { +// Class stdFactoryClass = Class.forName(STD); +// STD_FACTORY = (CryptoFactory) stdFactoryClass.newInstance(); +// } catch (ClassNotFoundException e) { +// LOGGER.error("STD crypto provider is not found!", e); +// throw new CryptoException("STD crypto provider is not found!", e); +// } catch (InstantiationException | IllegalAccessException e) { +// LOGGER.error("Fail to init STD crypto provider!", e); +// throw new CryptoException("Fail to init STD crypto provider!", e); +// } +// } +// return STD_FACTORY; +// } +// } +// return STD_FACTORY; +// } +// +// public static HashCryptography hashCrypto() { +// return crypto().hashCryptography(); +// } +// +// public static HashFunction hash(CryptoAlgorithm alg) { +// return hashCrypto().getFunction(alg); +// } +// +// public static AsymmetricCryptography asymmCrypto() { +// return crypto().asymmetricCryptography(); +// } +// +// public static SignatureFunction sign(CryptoAlgorithm alg) { +// return asymmCrypto().getSignatureFunction(alg); +// } +// +// public static AsymmetricEncryptionFunction asymmEncrypt(CryptoAlgorithm alg) { +// return asymmCrypto().getAsymmetricEncryptionFunction(alg); +// } +// +// public static SymmetricCryptography symmCrypto() { +// return crypto().symmetricCryptography(); +// } +// +// public static SymmetricEncryptionFunction symmEncrypt(CryptoAlgorithm alg) { +// return symmCrypto().getSymmetricEncryptionFunction(alg); +// } +// +//} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/PrivKey.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/PrivKey.java similarity index 54% rename from source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/PrivKey.java rename to source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/PrivKey.java index b756b9f2..96c622f3 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/PrivKey.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/PrivKey.java @@ -1,8 +1,4 @@ -package com.jd.blockchain.crypto.asymmetric; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoKeyType; -import com.jd.blockchain.crypto.base.BaseCryptoKey; +package com.jd.blockchain.crypto; /** * 私钥; @@ -20,9 +16,9 @@ public class PrivKey extends BaseCryptoKey { public PrivKey(byte[] cryptoBytes) { super(cryptoBytes); } - + @Override - protected boolean support(CryptoKeyType keyType) { - return CryptoKeyType.PRIV_KEY == keyType; + public CryptoKeyType getKeyType() { + return CryptoKeyType.PRIV_KEY; } } \ No newline at end of file diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/PubKey.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/PubKey.java similarity index 53% rename from source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/PubKey.java rename to source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/PubKey.java index 328b0751..ed228888 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/PubKey.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/PubKey.java @@ -1,8 +1,4 @@ -package com.jd.blockchain.crypto.asymmetric; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoKeyType; -import com.jd.blockchain.crypto.base.BaseCryptoKey; +package com.jd.blockchain.crypto; /** * 公钥; @@ -17,16 +13,13 @@ public class PubKey extends BaseCryptoKey { public PubKey(CryptoAlgorithm algorithm, byte[] rawCryptoBytes) { super(algorithm, rawCryptoBytes, CryptoKeyType.PUB_KEY); } - public PubKey() { - super(); - } public PubKey(byte[] cryptoBytes) { super(cryptoBytes); } - + @Override - protected boolean support(CryptoKeyType keyType) { - return CryptoKeyType.PUB_KEY == keyType; + public CryptoKeyType getKeyType() { + return CryptoKeyType.PUB_KEY; } } \ No newline at end of file diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/RandomFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/RandomFunction.java new file mode 100644 index 00000000..a4aa748c --- /dev/null +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/RandomFunction.java @@ -0,0 +1,7 @@ +package com.jd.blockchain.crypto; + +public interface RandomFunction extends CryptoFunction { + + RandomGenerator generate(byte[] seed); + +} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/RandomGenerator.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/RandomGenerator.java new file mode 100644 index 00000000..92421570 --- /dev/null +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/RandomGenerator.java @@ -0,0 +1,9 @@ +package com.jd.blockchain.crypto; + +public interface RandomGenerator { + + byte[] nextBytes(int size); + + void nextBytes(byte[] buffer); + +} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricKey.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricKey.java similarity index 60% rename from source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricKey.java rename to source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricKey.java index c226dfd3..5dc9f1f4 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricKey.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/SymmetricKey.java @@ -1,11 +1,13 @@ -package com.jd.blockchain.crypto.symmetric; +package com.jd.blockchain.crypto; import static com.jd.blockchain.crypto.CryptoKeyType.SYMMETRIC_KEY; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoKeyType; -import com.jd.blockchain.crypto.base.BaseCryptoKey; - +/** + * 单密钥; + * + * @author huanghaiquan + * + */ public class SymmetricKey extends BaseCryptoKey { private static final long serialVersionUID = 5055547663903904933L; @@ -17,11 +19,6 @@ public class SymmetricKey extends BaseCryptoKey { public SymmetricKey(byte[] keyBytes) { super(keyBytes); } - - @Override - protected boolean support(CryptoKeyType keyType) { - return SYMMETRIC_KEY == keyType; - } @Override public CryptoKeyType getKeyType() { diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/AsymmetricCiphertext.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/AsymmetricCiphertext.java index f28d3d83..b6c1a2cf 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/AsymmetricCiphertext.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/AsymmetricCiphertext.java @@ -1,8 +1,8 @@ package com.jd.blockchain.crypto.asymmetric; +import com.jd.blockchain.crypto.BaseCryptoBytes; import com.jd.blockchain.crypto.Ciphertext; import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.base.BaseCryptoBytes; public class AsymmetricCiphertext extends BaseCryptoBytes implements Ciphertext { @@ -13,10 +13,10 @@ public class AsymmetricCiphertext extends BaseCryptoBytes implements Ciphertext public AsymmetricCiphertext(byte[] cryptoBytes) { super(cryptoBytes); } - + @Override protected boolean support(CryptoAlgorithm algorithm) { - return algorithm.isAsymmetric() && algorithm.isEncryptable(); + return CryptoAlgorithm.isAsymmetricEncryptionAlgorithm(algorithm); } @Override diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/AsymmetricCryptography.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/AsymmetricCryptography.java index 2ca708f1..21b855e1 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/AsymmetricCryptography.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/AsymmetricCryptography.java @@ -1,82 +1,84 @@ -package com.jd.blockchain.crypto.asymmetric; - -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.CryptoAlgorithm; - -public interface AsymmetricCryptography { - - /** - * 生成密钥对; - * - * @param algorithm - * @return - */ - CryptoKeyPair generateKeyPair(CryptoAlgorithm algorithm); - - /** - * 获取签名方法; - * - * @param algorithm - * @return - */ - SignatureFunction getSignatureFunction(CryptoAlgorithm algorithm); - - /** - * 校验签名摘要和数据是否一致; - * - * @param digestBytes 签名摘要数据 - * @param pubKeyBytes 公钥数据 - * @param data 被签名数据 - * @return - */ - boolean verify(byte[] digestBytes, byte[] pubKeyBytes, byte[] data); - - /** - * 获取非对称加密方法; - * - * @param algorithm - * @return - */ - AsymmetricEncryptionFunction getAsymmetricEncryptionFunction(CryptoAlgorithm algorithm); - - /** - * 解密; - * - * @param privKeyBytes - * @param ciphertextBytes - * @return - */ - byte[] decrypt(byte[] privKeyBytes, byte[] ciphertextBytes); - - - Ciphertext resolveCiphertext(byte[] ciphertextBytes); - - Ciphertext tryResolveCiphertext(byte[] ciphertextBytes); - - /** - * @param digestBytes 待解析签名摘要 - * @return - */ - SignatureDigest resolveSignatureDigest(byte[] digestBytes); - - SignatureDigest tryResolveSignatureDigest(byte[] digestBytes); - - /** - * 由私钥恢复公钥; - * - * @param privKeyBytes 包含算法标识、密钥掩码和私钥的字节数组 - * @return 包含算法标识、密钥掩码和公钥的字节数组 - */ - byte[] retrievePubKeyBytes(byte[] privKeyBytes); - - byte[] tryRetrievePubKeyBytes(byte[] privKeyBytes); - - PubKey resolvePubKey(byte[] pubKeyBytes); - - PubKey tryResolvePubKey(byte[] pubKeyBytes); - - PrivKey resolvePrivKey(byte[] privKeyBytes); - - PrivKey tryResolvePrivKey(byte[] privKeyBytes); - -} +//package com.jd.blockchain.crypto.asymmetric; +// +//import com.jd.blockchain.crypto.Ciphertext; +//import com.jd.blockchain.crypto.CryptoAlgorithm; +//import com.jd.blockchain.crypto.PrivKey; +//import com.jd.blockchain.crypto.PubKey; +// +//public interface AsymmetricCryptography { +// +// /** +// * 生成密钥对; +// * +// * @param algorithm +// * @return +// */ +// CryptoKeyPair generateKeyPair(CryptoAlgorithm algorithm); +// +// /** +// * 获取签名方法; +// * +// * @param algorithm +// * @return +// */ +// SignatureFunction getSignatureFunction(CryptoAlgorithm algorithm); +// +// /** +// * 校验签名摘要和数据是否一致; +// * +// * @param digestBytes 签名摘要数据 +// * @param pubKeyBytes 公钥数据 +// * @param data 被签名数据 +// * @return +// */ +// boolean verify(byte[] digestBytes, byte[] pubKeyBytes, byte[] data); +// +// /** +// * 获取非对称加密方法; +// * +// * @param algorithm +// * @return +// */ +// AsymmetricEncryptionFunction getAsymmetricEncryptionFunction(CryptoAlgorithm algorithm); +// +// /** +// * 解密; +// * +// * @param privKeyBytes +// * @param ciphertextBytes +// * @return +// */ +// byte[] decrypt(byte[] privKeyBytes, byte[] ciphertextBytes); +// +// +// Ciphertext resolveCiphertext(byte[] ciphertextBytes); +// +// Ciphertext tryResolveCiphertext(byte[] ciphertextBytes); +// +// /** +// * @param digestBytes 待解析签名摘要 +// * @return +// */ +// SignatureDigest resolveSignatureDigest(byte[] digestBytes); +// +// SignatureDigest tryResolveSignatureDigest(byte[] digestBytes); +// +// /** +// * 由私钥恢复公钥; +// * +// * @param privKeyBytes 包含算法标识、密钥掩码和私钥的字节数组 +// * @return 包含算法标识、密钥掩码和公钥的字节数组 +// */ +// byte[] retrievePubKeyBytes(byte[] privKeyBytes); +// +// byte[] tryRetrievePubKeyBytes(byte[] privKeyBytes); +// +// PubKey resolvePubKey(byte[] pubKeyBytes); +// +// PubKey tryResolvePubKey(byte[] pubKeyBytes); +// +// PrivKey resolvePrivKey(byte[] privKeyBytes); +// +// PrivKey tryResolvePrivKey(byte[] privKeyBytes); +// +//} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/AsymmetricEncryptionFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/AsymmetricEncryptionFunction.java index 93216fe3..04d8d525 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/AsymmetricEncryptionFunction.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/AsymmetricEncryptionFunction.java @@ -3,6 +3,8 @@ package com.jd.blockchain.crypto.asymmetric; import com.jd.blockchain.crypto.Ciphertext; import com.jd.blockchain.crypto.CryptoFunction; import com.jd.blockchain.crypto.CryptoKeyPairGenerator; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; public interface AsymmetricEncryptionFunction extends CryptoKeyPairGenerator, CryptoFunction { diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/CryptoKeyPair.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/CryptoKeyPair.java index 1dd023b2..df2e1017 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/CryptoKeyPair.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/CryptoKeyPair.java @@ -1,5 +1,8 @@ package com.jd.blockchain.crypto.asymmetric; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; + public class CryptoKeyPair { private PubKey pubKey; diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/SignatureDigest.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/SignatureDigest.java index 9e6e17de..342d8c61 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/SignatureDigest.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/SignatureDigest.java @@ -1,8 +1,8 @@ package com.jd.blockchain.crypto.asymmetric; +import com.jd.blockchain.crypto.BaseCryptoBytes; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoDigest; -import com.jd.blockchain.crypto.base.BaseCryptoBytes; public class SignatureDigest extends BaseCryptoBytes implements CryptoDigest { public SignatureDigest() { @@ -16,10 +16,10 @@ public class SignatureDigest extends BaseCryptoBytes implements CryptoDigest { public SignatureDigest(byte[] cryptoBytes) { super(cryptoBytes); } - + @Override protected boolean support(CryptoAlgorithm algorithm) { - return algorithm.isAsymmetric() && algorithm.isSignable(); + return CryptoAlgorithm.isSignatureAlgorithm(algorithm); } /** diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/SignatureFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/SignatureFunction.java index 2f534a15..355f6df7 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/SignatureFunction.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/asymmetric/SignatureFunction.java @@ -2,6 +2,8 @@ package com.jd.blockchain.crypto.asymmetric; import com.jd.blockchain.crypto.CryptoFunction; import com.jd.blockchain.crypto.CryptoKeyPairGenerator; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; public interface SignatureFunction extends CryptoKeyPairGenerator, CryptoFunction { diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/base/BaseCryptoKey.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/base/BaseCryptoKey.java deleted file mode 100644 index de6eeabf..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/base/BaseCryptoKey.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.jd.blockchain.crypto.base; - -import java.io.Serializable; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.CryptoKey; -import com.jd.blockchain.crypto.CryptoKeyType; -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.io.BytesUtils; - -public abstract class BaseCryptoKey extends BaseCryptoBytes implements CryptoKey,Serializable { - - public static final int KEY_TYPE_BYTES = 1; - private static final long serialVersionUID = 4543074827807908363L; - - private CryptoKeyType keyType; - - public BaseCryptoKey() { - super(); - } - - public BaseCryptoKey(CryptoAlgorithm algorithm, byte[] rawCryptoBytes, CryptoKeyType keyType) { - super(algorithm, encodeKeyBytes(rawCryptoBytes, keyType)); - this.keyType = keyType; - } - - public BaseCryptoKey(byte[] cryptoBytes) { - super(cryptoBytes); - CryptoKeyType keyType = decodeKeyType(getRawCryptoBytes()); - if (!support(keyType)) { - throw new CryptoException("CryptoKey doesn't support keyType[" + keyType + "]!"); - } - this.keyType = keyType; - } - - @Override - public CryptoKeyType getKeyType() { - return keyType; - } - - private static byte[] encodeKeyBytes(byte[] rawCryptoBytes, CryptoKeyType keyType ) { - return BytesUtils.concat(new byte[] {keyType.CODE }, rawCryptoBytes); - } - - private static CryptoKeyType decodeKeyType(BytesSlice cryptoBytes) { - return CryptoKeyType.valueOf(cryptoBytes.getByte()); - } - - protected abstract boolean support(CryptoKeyType keyType); - - @Override - protected boolean support(CryptoAlgorithm algorithm) { - return algorithm.isSymmetric() || algorithm.isAsymmetric(); - } - - - @Override - public byte[] getRawKeyBytes() { - return getRawCryptoBytes().getBytesCopy(1); - } -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/hash/HashCryptography.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/hash/HashCryptography.java index 52c8240d..85107ffc 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/hash/HashCryptography.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/hash/HashCryptography.java @@ -1,50 +1,50 @@ -package com.jd.blockchain.crypto.hash; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoException; - -public interface HashCryptography { - - /** - * return HashFunction instance of the specified hash alg; - * - * - * if alg out of hash alg,then throws {@link IllegalArgumentException} - * - * @param algorithm - * @return - */ - HashFunction getFunction(CryptoAlgorithm algorithm); - - /** - * 校验 hash 摘要与指定的数据是否匹配; - * - * @param digestBytes - * @param data - * @return - */ - boolean verify(byte[] digestBytes, byte[] data); - - boolean verify(HashDigest digest, byte[] data); - - /** - * 解析指定的 hash 摘要;
- * - * 如果不符合哈希摘要的编码格式,则引发 {@link CryptoException} 异常; - * - * @param digestBytes - * @return - */ - HashDigest resolveHashDigest(byte[] digestBytes); - - /** - * 解析指定的 hash 摘要;
- * - * 如果不符合哈希摘要的编码格式,则返回 null; - * - * @param digestBytes - * @return - */ - HashDigest tryResolveHashDigest(byte[] digestBytes); - -} +//package com.jd.blockchain.crypto.hash; +// +//import com.jd.blockchain.crypto.CryptoAlgorithm; +//import com.jd.blockchain.crypto.CryptoException; +// +//public interface HashCryptography { +// +// /** +// * return HashFunction instance of the specified hash alg; +// * +// * +// * if alg out of hash alg,then throws {@link IllegalArgumentException} +// * +// * @param algorithm +// * @return +// */ +// HashFunction getFunction(CryptoAlgorithm algorithm); +// +// /** +// * 校验 hash 摘要与指定的数据是否匹配; +// * +// * @param digestBytes +// * @param data +// * @return +// */ +// boolean verify(byte[] digestBytes, byte[] data); +// +// boolean verify(HashDigest digest, byte[] data); +// +// /** +// * 解析指定的 hash 摘要;
+// * +// * 如果不符合哈希摘要的编码格式,则引发 {@link CryptoException} 异常; +// * +// * @param digestBytes +// * @return +// */ +// HashDigest resolveHashDigest(byte[] digestBytes); +// +// /** +// * 解析指定的 hash 摘要;
+// * +// * 如果不符合哈希摘要的编码格式,则返回 null; +// * +// * @param digestBytes +// * @return +// */ +// HashDigest tryResolveHashDigest(byte[] digestBytes); +// +//} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/hash/HashDigest.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/hash/HashDigest.java index e19ff3fb..99cf37bb 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/hash/HashDigest.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/hash/HashDigest.java @@ -2,9 +2,9 @@ package com.jd.blockchain.crypto.hash; import java.io.Serializable; +import com.jd.blockchain.crypto.BaseCryptoBytes; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoDigest; -import com.jd.blockchain.crypto.base.BaseCryptoBytes; public class HashDigest extends BaseCryptoBytes implements CryptoDigest,Serializable { @@ -24,7 +24,7 @@ public class HashDigest extends BaseCryptoBytes implements CryptoDigest,Serializ @Override protected boolean support(CryptoAlgorithm algorithm) { - return algorithm.isHash(); + return CryptoAlgorithm.isHashAlgorithm(algorithm); } @Override diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/AsymmtricCryptographyImpl.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/AsymmtricCryptographyImpl.java deleted file mode 100644 index 1b55da0f..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/AsymmtricCryptographyImpl.java +++ /dev/null @@ -1,218 +0,0 @@ -package com.jd.blockchain.crypto.impl; - -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.*; -import com.jd.blockchain.crypto.impl.def.asymmetric.ED25519SignatureFunction; -import com.jd.blockchain.crypto.impl.jni.asymmetric.JNIED25519SignatureFunction; -import com.jd.blockchain.crypto.impl.sm.asymmetric.SM2CryptoFunction; - -public class AsymmtricCryptographyImpl implements AsymmetricCryptography { - - private static final SignatureFunction ED25519_SIGF = new ED25519SignatureFunction(); - - private static final SignatureFunction SM2_SIGF = new SM2CryptoFunction(); - - private static final SignatureFunction JNIED25519_SIGF = new JNIED25519SignatureFunction(); - - private static final AsymmetricEncryptionFunction SM2_ENCF = new SM2CryptoFunction(); - - /** - * 封装了非对称密码算法对应的密钥生成算法 - */ - @Override - public CryptoKeyPair generateKeyPair(CryptoAlgorithm algorithm) { - - //判断算法是签名算法还是非对称加密算法,并根据算法生成密钥对,否则抛出异常 - if (algorithm.isSignable() && algorithm.isAsymmetric()){ - return getSignatureFunction(algorithm).generateKeyPair(); - } - else if (algorithm.isEncryptable() && algorithm.isAsymmetric()){ - return getAsymmetricEncryptionFunction(algorithm).generateKeyPair(); - } - else throw new IllegalArgumentException("The specified algorithm is not signature or asymmetric encryption algorithm!"); - } - - @Override - public SignatureFunction getSignatureFunction(CryptoAlgorithm algorithm) { - //遍历签名算法,如果满足,则返回实例 - switch (algorithm) { - case ED25519: - return ED25519_SIGF; - case SM2: - return SM2_SIGF; - case JNIED25519: - return JNIED25519_SIGF; - default: - break; - } - throw new IllegalArgumentException("The specified algorithm is not signature algorithm!"); - } - - @Override - public boolean verify(byte[] digestBytes, byte[] pubKeyBytes, byte[] data) { - - //得到SignatureDigest类型的签名摘要,并得到算法标识 - SignatureDigest signatureDigest = resolveSignatureDigest(digestBytes); - CryptoAlgorithm algorithm = signatureDigest.getAlgorithm(); - PubKey pubKey = resolvePubKey(pubKeyBytes); - - //验证两个输入中算法标识一致,否则抛出异常 - if (algorithm != signatureDigest.getAlgorithm()) - throw new IllegalArgumentException("Digest's algorithm and key's are not matching!"); - - //根据算法标识,调用对应算法实例来验证签名摘要 - return getSignatureFunction(algorithm).verify(signatureDigest,pubKey,data); - } - - @Override - public AsymmetricEncryptionFunction getAsymmetricEncryptionFunction(CryptoAlgorithm algorithm) { - //遍历非对称加密算法,如果满足,则返回实例 - switch (algorithm) { - case SM2: - return SM2_ENCF; - default: - break; - } - throw new IllegalArgumentException("The specified algorithm is not asymmetric encryption algorithm!"); - } - - @Override - public byte[] decrypt(byte[] privKeyBytes, byte[] ciphertextBytes) { - - //分别得到PrivKey和Ciphertext类型的密钥和密文,以及privKey对应的算法 - PrivKey privKey = resolvePrivKey(privKeyBytes); - Ciphertext ciphertext = resolveCiphertext(ciphertextBytes); - CryptoAlgorithm algorithm = privKey.getAlgorithm(); - - //验证两个输入中算法标识一致,否则抛出异常 - if (algorithm != ciphertext.getAlgorithm()) - throw new IllegalArgumentException("Ciphertext's algorithm and key's are not matching!"); - - //根据算法标识,调用对应算法实例来计算返回明文 - return getAsymmetricEncryptionFunction(algorithm).decrypt(privKey,ciphertext); - } - - @Override - public Ciphertext resolveCiphertext(byte[] ciphertextBytes) { - Ciphertext ciphertext = tryResolveCiphertext(ciphertextBytes); - if (ciphertext == null) - throw new IllegalArgumentException("This ciphertextBytes cannot be resolved!"); - else return ciphertext; - } - - @Override - public Ciphertext tryResolveCiphertext(byte[] ciphertextBytes) { - //遍历非对称加密算法,如果满足,则返回解析结果 - if (SM2_ENCF.supportCiphertext(ciphertextBytes)){ - return SM2_ENCF.resolveCiphertext(ciphertextBytes); - } - //否则返回null - return null; - } - - @Override - public SignatureDigest resolveSignatureDigest(byte[] digestBytes) { - SignatureDigest signatureDigest = tryResolveSignatureDigest(digestBytes); - if (signatureDigest == null) - throw new IllegalArgumentException("This digestBytes cannot be resolved!"); - else return signatureDigest; - } - - @Override - public SignatureDigest tryResolveSignatureDigest(byte[] digestBytes) { - //遍历签名算法,如果满足,则返回解析结果 - if (ED25519_SIGF.supportDigest(digestBytes)){ - return ED25519_SIGF.resolveDigest(digestBytes); - } - if (SM2_SIGF.supportDigest(digestBytes)){ - return SM2_SIGF.resolveDigest(digestBytes); - } - if (JNIED25519_SIGF.supportDigest(digestBytes)){ - return JNIED25519_SIGF.resolveDigest(digestBytes); - } - //否则返回null - return null; - } - - @Override - public byte[] retrievePubKeyBytes(byte[] privKeyBytes) { - byte[] pubKeyBytes = tryRetrievePubKeyBytes(privKeyBytes); - if (pubKeyBytes == null) - throw new IllegalArgumentException("The specified algorithm in privKeyBytes is not signature or asymmetric encryption algorithm!"); - else return pubKeyBytes; - } - - @Override - public byte[] tryRetrievePubKeyBytes(byte[] privKeyBytes) { - //解析私钥获得算法标识 - CryptoAlgorithm algorithm = resolvePrivKey(privKeyBytes).getAlgorithm(); - - //判断算法是签名算法还是非对称加密算法,并根据算法生成密钥对,否则抛出异常 - if (algorithm.isSignable() && algorithm.isAsymmetric()){ - return getSignatureFunction(algorithm).retrievePubKeyBytes(privKeyBytes); - } - else if (algorithm.isEncryptable() && algorithm.isAsymmetric()){ - return getAsymmetricEncryptionFunction(algorithm).retrievePubKeyBytes(privKeyBytes); - } - //否则返回null - return null; - } - - @Override - public PubKey resolvePubKey(byte[] pubKeyBytes) { - PubKey pubKey = tryResolvePubKey(pubKeyBytes); - if (pubKey == null) - throw new IllegalArgumentException("This pubKeyBytes cannot be resolved!"); - else return pubKey; - - } - - @Override - public PubKey tryResolvePubKey(byte[] pubKeyBytes) { - //遍历签名算法,如果满足,则返回解析结果 - if (ED25519_SIGF.supportPubKey(pubKeyBytes)){ - return ED25519_SIGF.resolvePubKey(pubKeyBytes); - } - if (SM2_SIGF.supportPubKey(pubKeyBytes)){ - return SM2_SIGF.resolvePubKey(pubKeyBytes); - } - if (JNIED25519_SIGF.supportPubKey(pubKeyBytes)){ - return JNIED25519_SIGF.resolvePubKey(pubKeyBytes); - } - //遍历非对称加密算法,如果满足,则返回解析结果 - if (SM2_ENCF.supportPubKey(pubKeyBytes)){ - return SM2_ENCF.resolvePubKey(pubKeyBytes); - } - //否则返回null - return null; - } - - @Override - public PrivKey resolvePrivKey(byte[] privKeyBytes) { - PrivKey privKey = tryResolvePrivKey(privKeyBytes); - if (privKey == null) - throw new IllegalArgumentException("This privKeyBytes cannot be resolved!"); - else return privKey; - } - - @Override - public PrivKey tryResolvePrivKey(byte[] privKeyBytes) { - //遍历签名算法,如果满足,则返回解析结果 - if (ED25519_SIGF.supportPrivKey(privKeyBytes)){ - return ED25519_SIGF.resolvePrivKey(privKeyBytes); - } - if (SM2_SIGF.supportPrivKey(privKeyBytes)){ - return SM2_SIGF.resolvePrivKey(privKeyBytes); - } - if (JNIED25519_SIGF.supportPrivKey(privKeyBytes)){ - return JNIED25519_SIGF.resolvePrivKey(privKeyBytes); - } - //遍历非对称加密算法,如果满足,则返回解析结果 - if (SM2_ENCF.supportPrivKey(privKeyBytes)){ - return SM2_ENCF.resolvePrivKey(privKeyBytes); - } - //否则返回null - return null; - } -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/CryptoFactoryImpl.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/CryptoFactoryImpl.java deleted file mode 100644 index 90a6d719..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/CryptoFactoryImpl.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jd.blockchain.crypto.impl; - -import com.jd.blockchain.crypto.CryptoFactory; -import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; -import com.jd.blockchain.crypto.hash.HashCryptography; -import com.jd.blockchain.crypto.symmetric.SymmetricCryptography; - -public class CryptoFactoryImpl implements CryptoFactory { - - //Field; - private static HashCryptography hashCryptography = new HashCryptographyImpl(); - private static AsymmetricCryptography asymmetricCryptography = new AsymmtricCryptographyImpl(); - private static SymmetricCryptography symmetricCryptography = new SymmetricCryptographyImpl(); - - @Override - public HashCryptography hashCryptography() { - return hashCryptography; - } - - @Override - public AsymmetricCryptography asymmetricCryptography() { - return asymmetricCryptography; - } - - @Override - public SymmetricCryptography symmetricCryptography() { - return symmetricCryptography; - } - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/HashCryptographyImpl.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/HashCryptographyImpl.java deleted file mode 100644 index ae1772c5..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/HashCryptographyImpl.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.jd.blockchain.crypto.impl; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.hash.HashCryptography; -import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.hash.HashFunction; -import com.jd.blockchain.crypto.impl.def.hash.RIPEMD160HashFunction; -import com.jd.blockchain.crypto.impl.def.hash.SHA256HashFunction; -import com.jd.blockchain.crypto.impl.jni.hash.JNIRIPEMD160HashFunction; -import com.jd.blockchain.crypto.impl.jni.hash.JNISHA256HashFunction; -import com.jd.blockchain.crypto.impl.sm.hash.SM3HashFunction; - -public class HashCryptographyImpl implements HashCryptography { - - private static final HashFunction SHA256_FUNC = new SHA256HashFunction(); - private static final HashFunction RIPEMD160_FUNC = new RIPEMD160HashFunction(); - private static final HashFunction SM3_FUNC = new SM3HashFunction(); - - private static final HashFunction JNISHA256_FUNC = new JNISHA256HashFunction(); - private static final HashFunction JNIRIPEMD160_FUNC = new JNIRIPEMD160HashFunction(); - - @Override - public HashFunction getFunction(CryptoAlgorithm algorithm) { - - // 遍历哈希算法,如果满足,则返回实例 - switch (algorithm) { - case SHA256: - return SHA256_FUNC; - case RIPEMD160: - return RIPEMD160_FUNC; - case SM3: - return SM3_FUNC; - case JNISHA256: - return JNISHA256_FUNC; - case JNIRIPEMD160: - return JNIRIPEMD160_FUNC; - default: - break; - } - throw new IllegalArgumentException("The specified algorithm is not hash algorithm!"); - } - - @Override - public boolean verify(byte[] digestBytes, byte[] data) { - HashDigest hashDigest = resolveHashDigest(digestBytes); - return verify(hashDigest,data); - } - - @Override - public boolean verify(HashDigest digest, byte[] data) { - CryptoAlgorithm algorithm = digest.getAlgorithm(); - return getFunction(algorithm).verify(digest, data); - } - - @Override - public HashDigest resolveHashDigest(byte[] digestBytes) { - HashDigest hashDigest = tryResolveHashDigest(digestBytes); - if (hashDigest == null) - throw new IllegalArgumentException("This digestBytes cannot be resolved!"); - else return hashDigest; - } - - @Override - public HashDigest tryResolveHashDigest(byte[] digestBytes) { - //遍历哈希函数,如果满足,则返回解析结果 - if (SHA256_FUNC.supportHashDigest(digestBytes)) { - return SHA256_FUNC.resolveHashDigest(digestBytes); - } - if (RIPEMD160_FUNC.supportHashDigest(digestBytes)) { - return RIPEMD160_FUNC.resolveHashDigest(digestBytes); - } - if (SM3_FUNC.supportHashDigest(digestBytes)) { - return SM3_FUNC.resolveHashDigest(digestBytes); - } - if (JNISHA256_FUNC.supportHashDigest(digestBytes)) { - return JNISHA256_FUNC.resolveHashDigest(digestBytes); - } - if (JNIRIPEMD160_FUNC.supportHashDigest(digestBytes)) { - return JNIRIPEMD160_FUNC.resolveHashDigest(digestBytes); - } - //否则返回null - return null; - } -} \ No newline at end of file diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/SymmetricCryptographyImpl.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/SymmetricCryptographyImpl.java deleted file mode 100644 index ce787511..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/SymmetricCryptographyImpl.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.jd.blockchain.crypto.impl; - -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.impl.def.symmetric.AESSymmetricEncryptionFunction; -import com.jd.blockchain.crypto.impl.sm.symmetric.SM4SymmetricEncryptionFunction; -import com.jd.blockchain.crypto.symmetric.SymmetricCryptography; -import com.jd.blockchain.crypto.symmetric.SymmetricEncryptionFunction; -import com.jd.blockchain.crypto.symmetric.SymmetricKey; - -public class SymmetricCryptographyImpl implements SymmetricCryptography { - - private static final SymmetricEncryptionFunction AES_ENCF = new AESSymmetricEncryptionFunction(); - private static final SymmetricEncryptionFunction SM4_ENCF = new SM4SymmetricEncryptionFunction(); - - /** - * 封装了对称密码算法对应的密钥生成算法 - */ - @Override - public SymmetricKey generateKey(CryptoAlgorithm algorithm) { - - //验证算法标识是对称加密算法,并根据算法生成对称密钥,否则抛出异常 - if (algorithm.isEncryptable() && algorithm.isSymmetric() ){ - return (SymmetricKey) getSymmetricEncryptionFunction(algorithm).generateSymmetricKey(); - } - else throw new IllegalArgumentException("The specified algorithm is not symmetric encryption algorithm!"); - } - - @Override - public SymmetricEncryptionFunction getSymmetricEncryptionFunction(CryptoAlgorithm algorithm) { - - // 遍历对称加密算法,如果满足,则返回实例 - switch (algorithm) { - case AES: - return AES_ENCF; - case SM4: - return SM4_ENCF; - default: - break; - } - throw new IllegalArgumentException("The specified algorithm is not symmetric encryption algorithm!"); - } - - @Override - public byte[] decrypt(byte[] symmetricKeyBytes, byte[] ciphertextBytes) { - - //分别得到SymmetricKey和Ciphertext类型的密钥和密文,以及symmetricKey对应的算法 - SymmetricKey symmetricKey = resolveSymmetricKey(symmetricKeyBytes); - Ciphertext ciphertext = resolveCiphertext(ciphertextBytes); - CryptoAlgorithm algorithm = symmetricKey.getAlgorithm(); - - //验证两个输入中算法标识一致,否则抛出异常 - if (algorithm != ciphertext.getAlgorithm()) - throw new IllegalArgumentException("Ciphertext's algorithm and key's are not matching!"); - - //根据算法标识,调用对应算法实例来计算返回明文 - return getSymmetricEncryptionFunction(algorithm).decrypt(symmetricKey,ciphertext); - } - - @Override - public Ciphertext resolveCiphertext(byte[] ciphertextBytes) { - Ciphertext ciphertext = tryResolveCiphertext(ciphertextBytes); - if (ciphertext == null) - throw new IllegalArgumentException("This ciphertextBytes cannot be resolved!"); - else return ciphertext; - } - - @Override - public Ciphertext tryResolveCiphertext(byte[] ciphertextBytes) { - //遍历对称加密算法,如果满足,则返回解析结果 - if (AES_ENCF.supportCiphertext(ciphertextBytes)) { - return AES_ENCF.resolveCiphertext(ciphertextBytes); - } - if (SM4_ENCF.supportCiphertext(ciphertextBytes)) { - return SM4_ENCF.resolveCiphertext(ciphertextBytes); - } - //否则返回null - return null; - } - - @Override - public SymmetricKey resolveSymmetricKey(byte[] symmetricKeyBytes) { - SymmetricKey symmetricKey = tryResolveSymmetricKey(symmetricKeyBytes); - if (symmetricKey == null) - throw new IllegalArgumentException("This symmetricKeyBytes cannot be resolved!"); - else return symmetricKey; - } - - @Override - public SymmetricKey tryResolveSymmetricKey(byte[] symmetricKeyBytes) { - //遍历对称加密算法,如果满足,则返回解析结果 - if(AES_ENCF.supportSymmetricKey(symmetricKeyBytes)) { - return AES_ENCF.resolveSymmetricKey(symmetricKeyBytes); - } - if(SM4_ENCF.supportSymmetricKey(symmetricKeyBytes)) { - return SM4_ENCF.resolveSymmetricKey(symmetricKeyBytes); - } - //否则返回null - return null; - } -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/symmetric/AESSymmetricEncryptionFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/symmetric/AESSymmetricEncryptionFunction.java deleted file mode 100644 index 64b7cf82..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/def/symmetric/AESSymmetricEncryptionFunction.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.jd.blockchain.crypto.impl.def.symmetric; - -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoKey; -import com.jd.blockchain.crypto.symmetric.SymmetricCiphertext; -import com.jd.blockchain.crypto.symmetric.SymmetricEncryptionFunction; -import com.jd.blockchain.crypto.symmetric.SymmetricKey; -import com.jd.blockchain.utils.security.AESUtils; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.AES; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_BYTES; -import static com.jd.blockchain.crypto.CryptoKeyType.SYMMETRIC_KEY; -import static com.jd.blockchain.crypto.base.BaseCryptoKey.KEY_TYPE_BYTES; - -public class AESSymmetricEncryptionFunction implements SymmetricEncryptionFunction { - - private static final int KEY_SIZE = 16; - private static final int BLOCK_SIZE = 16; - - private static final int SYMMETRICKEY_LENGTH = ALGORYTHM_BYTES + KEY_TYPE_BYTES + KEY_SIZE; - - public AESSymmetricEncryptionFunction() { - } - - @Override - public Ciphertext encrypt(SymmetricKey key, byte[] data) { - - byte[] rawKeyBytes = key.getRawKeyBytes(); - - // 验证原始密钥长度为128比特,即16字节 - if (rawKeyBytes.length != KEY_SIZE) - throw new IllegalArgumentException("This key has wrong format!"); - - // 验证密钥数据的算法标识对应AES算法 - if (key.getAlgorithm() != AES) - throw new IllegalArgumentException("The is not AES symmetric key!"); - - // 调用底层AES128算法并计算密文数据 - return new SymmetricCiphertext(AES, AESUtils.encrypt(data, rawKeyBytes)); - } - - @Override - public void encrypt(SymmetricKey key, InputStream in, OutputStream out) { - - // 读输入流得到明文,加密,密文数据写入输出流 - try { - byte[] aesData = new byte[in.available()]; - in.read(aesData); - in.close(); - - out.write(encrypt(key, aesData).toBytes()); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public byte[] decrypt(SymmetricKey key, Ciphertext ciphertext) { - - byte[] rawKeyBytes = key.getRawKeyBytes(); - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - - // 验证原始密钥长度为128比特,即16字节 - if (rawKeyBytes.length != KEY_SIZE) - throw new IllegalArgumentException("This key has wrong format!"); - - // 验证密钥数据的算法标识对应AES算法 - if (key.getAlgorithm().CODE != AES.CODE) - throw new IllegalArgumentException("The is not AES symmetric key!"); - - // 验证原始密文长度为分组长度的整数倍 - if (rawCiphertextBytes.length % BLOCK_SIZE != 0) - throw new IllegalArgumentException("This ciphertext has wrong format!"); - - // 验证密文数据算法标识对应AES算法 - if (ciphertext.getAlgorithm() != AES) - throw new IllegalArgumentException("This is not AES ciphertext!"); - - // 调用底层AES128算法解密,得到明文 - return AESUtils.decrypt(rawCiphertextBytes, rawKeyBytes); - } - - @Override - public void decrypt(SymmetricKey key, InputStream in, OutputStream out) { - - // 读输入流得到密文数据,解密,明文写入输出流 - try { - byte[] aesData = new byte[in.available()]; - in.read(aesData); - in.close(); - - if (!supportCiphertext(aesData)) - throw new IllegalArgumentException("InputStream is not valid AES ciphertext!"); - - out.write(decrypt(key, resolveCiphertext(aesData))); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public boolean supportSymmetricKey(byte[] symmetricKeyBytes) { - //验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,字节数组的算法标识对应AES算法且密钥密钥类型是对称密钥 - return symmetricKeyBytes.length == SYMMETRICKEY_LENGTH && symmetricKeyBytes[0] == AES.CODE && symmetricKeyBytes[1] == SYMMETRIC_KEY.CODE; - } - - @Override - public SymmetricKey resolveSymmetricKey(byte[] symmetricKeyBytes) { - // 由框架调用 support 方法检查有效性,在此不做重复检查; - return new SymmetricKey(symmetricKeyBytes); - } - - @Override - public boolean supportCiphertext(byte[] ciphertextBytes) { - // 验证(输入字节数组长度-算法标识长度)是分组长度的整数倍,字节数组的算法标识对应AES算法 - return (ciphertextBytes.length - ALGORYTHM_BYTES) % BLOCK_SIZE == 0 && ciphertextBytes[0] == AES.CODE; - } - - @Override - public SymmetricCiphertext resolveCiphertext(byte[] ciphertextBytes) { - // 由框架调用 support 方法检查有效性,在此不做重复检查; - return new SymmetricCiphertext(ciphertextBytes); - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return AES; - } - - @Override - public CryptoKey generateSymmetricKey() { - // 根据对应的标识和原始密钥生成相应的密钥数据 - return new SymmetricKey(AES, AESUtils.generateKey128_Bytes()); - } -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/jni/asymmetric/JNIED25519SignatureFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/jni/asymmetric/JNIED25519SignatureFunction.java deleted file mode 100644 index c03f8e93..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/jni/asymmetric/JNIED25519SignatureFunction.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.jd.blockchain.crypto.impl.jni.asymmetric; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.*; -import com.jd.blockchain.crypto.jniutils.asymmetric.JNIED25519Utils; -import com.jd.blockchain.utils.io.BytesUtils; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.JNIED25519; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_BYTES; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIV_KEY; -import static com.jd.blockchain.crypto.CryptoKeyType.PUB_KEY; -import static com.jd.blockchain.crypto.base.BaseCryptoKey.KEY_TYPE_BYTES; - -public class JNIED25519SignatureFunction implements SignatureFunction { - - private static final int PUBKEY_SIZE = 32; - private static final int PRIVKEY_SIZE = 32; - private static final int DIGEST_SIZE = 64; - - private static final int PUBKEY_LENGTH = ALGORYTHM_BYTES + KEY_TYPE_BYTES + PUBKEY_SIZE; - private static final int PRIVKEY_LENGTH = ALGORYTHM_BYTES + KEY_TYPE_BYTES + PRIVKEY_SIZE; - private static final int SIGNATUREDIGEST_LENGTH = ALGORYTHM_BYTES + DIGEST_SIZE; - - public JNIED25519SignatureFunction() { - } - - @Override - public SignatureDigest sign(PrivKey privKey, byte[] data) { - - if (data == null) - throw new IllegalArgumentException("This data is null!"); - - JNIED25519Utils ed25519 = new JNIED25519Utils(); - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - byte[] rawPubKeyBytes = ed25519.getPubKey(rawPrivKeyBytes); - - // 验证原始私钥长度为256比特,即32字节 - if (rawPrivKeyBytes.length != PRIVKEY_SIZE) - throw new IllegalArgumentException("This key has wrong format!"); - - // 验证密钥数据的算法标识对应JNIED25519签名算法 - if (privKey.getAlgorithm() != JNIED25519) - throw new IllegalArgumentException("This key is not ED25519 private key!"); - - // 调用JNIED25519签名算法计算签名结果 - return new SignatureDigest(JNIED25519, ed25519.sign(data, rawPrivKeyBytes, rawPubKeyBytes)); - } - - @Override - public boolean verify(SignatureDigest digest, PubKey pubKey, byte[] data) { - - JNIED25519Utils ed25519 = new JNIED25519Utils(); - - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawDigestBytes = digest.getRawDigest(); - - // 验证原始公钥长度为256比特,即32字节 - if (rawPubKeyBytes.length != PUBKEY_SIZE) - throw new IllegalArgumentException("This key has wrong format!"); - - // 验证密钥数据的算法标识对应JNIED25519签名算法 - if (pubKey.getAlgorithm() != JNIED25519) - throw new IllegalArgumentException("This key is not ED25519 public key!"); - - // 验证密文数据的算法标识对应JNIED25519签名算法,并且原始摘要长度为64字节 - if (digest.getAlgorithm() != JNIED25519 || rawDigestBytes.length != DIGEST_SIZE) - throw new IllegalArgumentException("This is not ED25519 signature digest!"); - - // 调用JNIED25519验签算法验证签名结果 - return ed25519.verify(data, rawPubKeyBytes, rawDigestBytes); - } - - @Override - public byte[] retrievePubKeyBytes(byte[] privKeyBytes) { - - JNIED25519Utils ed25519 = new JNIED25519Utils(); - byte[] rawPrivKeyBytes = resolvePrivKey(privKeyBytes).getRawKeyBytes(); - byte[] rawPubKeyBytes = ed25519.getPubKey(rawPrivKeyBytes); - return new PubKey(JNIED25519,rawPubKeyBytes).toBytes(); - } - - @Override - public boolean supportPrivKey(byte[] privKeyBytes) { - // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,密钥数据的算法标识对应JNIED25519签名算法,并且密钥类型是私钥 - return privKeyBytes.length == PRIVKEY_LENGTH - && privKeyBytes[0] == JNIED25519.CODE && privKeyBytes[1] == PRIV_KEY.CODE; - } - - @Override - public PrivKey resolvePrivKey(byte[] privKeyBytes) { - // 由框架调用 support 方法检查有效性,在此不做重复检查; - return new PrivKey(privKeyBytes); - } - - @Override - public boolean supportPubKey(byte[] pubKeyBytes) { - // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,密钥数据的算法标识对应JNIED25519签名算法,并且密钥类型是公钥 - return pubKeyBytes.length == PUBKEY_LENGTH && - pubKeyBytes[0] == JNIED25519.CODE && pubKeyBytes[1] == PUB_KEY.CODE; - - } - - @Override - public PubKey resolvePubKey(byte[] pubKeyBytes) { - // 由框架调用 support 方法检查有效性,在此不做重复检查; - return new PubKey(pubKeyBytes); - } - - @Override - public boolean supportDigest(byte[] digestBytes) { - // 验证输入字节数组长度=算法标识长度+摘要长度,字节数组的算法标识对应JNIED25519算法 - return digestBytes.length == SIGNATUREDIGEST_LENGTH && digestBytes[0] == JNIED25519.CODE; - } - - @Override - public SignatureDigest resolveDigest(byte[] digestBytes) { - // 由框架调用 support 方法检查有效性,在此不做重复检查; - return new SignatureDigest(digestBytes); - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return JNIED25519; - } - - @Override - public CryptoKeyPair generateKeyPair() { - - JNIED25519Utils ed25519 = new JNIED25519Utils(); - byte[] rawPrivKeyBytes = new byte[PRIVKEY_SIZE]; - byte[] rawPubKeyBytes = new byte[PUBKEY_SIZE]; - - // 调用JNIED25519算法的密钥生成算法生成公私钥对 - ed25519.generateKeyPair(rawPrivKeyBytes, rawPubKeyBytes); - - return new CryptoKeyPair(new PubKey(JNIED25519, rawPubKeyBytes), new PrivKey(JNIED25519, rawPrivKeyBytes)); - - } -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/jni/hash/JNIRIPEMD160HashFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/jni/hash/JNIRIPEMD160HashFunction.java deleted file mode 100644 index 72d0777e..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/jni/hash/JNIRIPEMD160HashFunction.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.jd.blockchain.crypto.impl.jni.hash; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.hash.HashFunction; -import com.jd.blockchain.crypto.jniutils.hash.JNIRIPEMD160Utils; - -import java.util.Arrays; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.JNIRIPEMD160; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_BYTES; - -public class JNIRIPEMD160HashFunction implements HashFunction { - - private static final int DIGEST_BYTES = 160 / 8; - - private static final int DIGEST_LENGTH = ALGORYTHM_BYTES + DIGEST_BYTES; - - @Override - public CryptoAlgorithm getAlgorithm() { - return JNIRIPEMD160; - } - - @Override - public HashDigest hash(byte[] data) { - - if (data == null) - throw new IllegalArgumentException("This data is null!"); - - JNIRIPEMD160Utils ripemd160 = new JNIRIPEMD160Utils(); - byte[] digestBytes = ripemd160.hash(data); - return new HashDigest(JNIRIPEMD160, digestBytes); - } - - @Override - public boolean verify(HashDigest digest, byte[] data) { - HashDigest hashDigest = hash(data); - return Arrays.equals(hashDigest.toBytes(), digest.toBytes()); - } - - @Override - public boolean supportHashDigest(byte[] digestBytes) { - // 验证输入字节数组长度=算法标识长度+摘要长度,字节数组的算法标识对应JNIRIPEMD160算法 - return digestBytes.length == DIGEST_LENGTH && JNIRIPEMD160.CODE == digestBytes[0]; - } - - @Override - public HashDigest resolveHashDigest(byte[] digestBytes) { - // 由框架调用 support 方法检查有效性,在此不做重复检查; - return new HashDigest(digestBytes); - } -} - diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/jni/hash/JNISHA256HashFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/jni/hash/JNISHA256HashFunction.java deleted file mode 100644 index bb6e84f0..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/jni/hash/JNISHA256HashFunction.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.jd.blockchain.crypto.impl.jni.hash; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.hash.HashFunction; -import com.jd.blockchain.crypto.jniutils.hash.JNISHA256Utils; - -import java.util.Arrays; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.JNISHA256; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_BYTES; - -public class JNISHA256HashFunction implements HashFunction { - - private static final int DIGEST_BYTES = 256/8; - - private static final int DIGEST_LENGTH = ALGORYTHM_BYTES + DIGEST_BYTES; - - @Override - public CryptoAlgorithm getAlgorithm() { - return JNISHA256; - } - - @Override - public HashDigest hash(byte[] data) { - - if (data == null) - throw new IllegalArgumentException("This data is null!"); - - JNISHA256Utils sha256 = new JNISHA256Utils(); - byte[] digestBytes = sha256.hash(data); - return new HashDigest(JNISHA256,digestBytes); - } - - @Override - public boolean verify(HashDigest digest, byte[] data) { - HashDigest hashDigest=hash(data); - return Arrays.equals(hashDigest.toBytes(),digest.toBytes()); - } - - @Override - public boolean supportHashDigest(byte[] digestBytes) { - // 验证输入字节数组长度=算法标识长度+摘要长度,字节数组的算法标识对应JNISHA256算法 - return digestBytes.length == DIGEST_LENGTH && JNISHA256.CODE == digestBytes[0]; - } - - @Override - public HashDigest resolveHashDigest(byte[] hashDigestBytes) { - // 由框架调用 support 方法检查有效性,在此不做重复检查; - return new HashDigest(hashDigestBytes); - } - -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/sm/asymmetric/SM2CryptoFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/sm/asymmetric/SM2CryptoFunction.java deleted file mode 100644 index 3e9097f5..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/sm/asymmetric/SM2CryptoFunction.java +++ /dev/null @@ -1,192 +0,0 @@ -package com.jd.blockchain.crypto.impl.sm.asymmetric; - -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.*; -import com.jd.blockchain.crypto.smutils.asymmetric.SM2Utils; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.SM2; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_BYTES; -import static com.jd.blockchain.crypto.CryptoKeyType.PRIV_KEY; -import static com.jd.blockchain.crypto.CryptoKeyType.PUB_KEY; -import static com.jd.blockchain.crypto.base.BaseCryptoKey.KEY_TYPE_BYTES; - -public class SM2CryptoFunction implements AsymmetricEncryptionFunction, SignatureFunction { - - private static final int ECPOINT_SIZE = 65; - private static final int PRIVKEY_SIZE = 32; - private static final int SIGNATUREDIGEST_SIZE = 64; - private static final int HASHDIGEST_SIZE = 32; - - private static final int PUBKEY_LENGTH = ALGORYTHM_BYTES + KEY_TYPE_BYTES + ECPOINT_SIZE; - private static final int PRIVKEY_LENGTH = ALGORYTHM_BYTES + KEY_TYPE_BYTES + PRIVKEY_SIZE; - private static final int SIGNATUREDIGEST_LENGTH = ALGORYTHM_BYTES + SIGNATUREDIGEST_SIZE; - - @Override - public Ciphertext encrypt(PubKey pubKey, byte[] data) { - - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - - // 验证原始公钥长度为65字节 - if (rawPubKeyBytes.length != ECPOINT_SIZE) - throw new IllegalArgumentException("This key has wrong format!"); - - // 验证密钥数据的算法标识对应SM2算法 - if (pubKey.getAlgorithm() != SM2) - throw new IllegalArgumentException("The is not sm2 public key!"); - - // 调用SM2加密算法计算密文 - return new AsymmetricCiphertext(SM2, SM2Utils.encrypt(data, rawPubKeyBytes)); - } - - @Override - public byte[] decrypt(PrivKey privKey, Ciphertext ciphertext) { - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - - // 验证原始私钥长度为32字节 - if (rawPrivKeyBytes.length != PRIVKEY_SIZE) - throw new IllegalArgumentException("This key has wrong format!"); - - // 验证密钥数据的算法标识对应SM2算法 - if (privKey.getAlgorithm() != SM2) - throw new IllegalArgumentException("This key is not SM2 private key!"); - - // 验证密文数据的算法标识对应SM2签名算法,并且原始摘要长度为64字节 - if (ciphertext.getAlgorithm() != SM2 || rawCiphertextBytes.length < ECPOINT_SIZE + HASHDIGEST_SIZE) - throw new IllegalArgumentException("This is not SM2 ciphertext!"); - - // 调用SM2解密算法得到明文结果 - return SM2Utils.decrypt(rawCiphertextBytes,rawPrivKeyBytes); - } - - @Override - public byte[] retrievePubKeyBytes(byte[] privKeyBytes) { - - byte[] rawPrivKeyBytes = resolvePrivKey(privKeyBytes).getRawKeyBytes(); - byte[] rawPubKeyBytes = SM2Utils.retrievePublicKey(rawPrivKeyBytes); - return new PubKey(SM2,rawPubKeyBytes).toBytes(); - } - - @Override - public boolean supportPrivKey(byte[] privKeyBytes) { - // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,密钥数据的算法标识对应SM2算法,并且密钥类型是私钥 - return privKeyBytes.length == PRIVKEY_LENGTH && privKeyBytes[0] == SM2.CODE && privKeyBytes[1] == PRIV_KEY.CODE; - } - - @Override - public PrivKey resolvePrivKey(byte[] privKeyBytes) { - // 由框架调用 support 方法检查有效性,在此不做重复检查; - return new PrivKey(privKeyBytes); - } - - @Override - public boolean supportPubKey(byte[] pubKeyBytes) { - // 验证输入字节数组长度=算法标识长度+密钥类型长度+椭圆曲线点长度,密钥数据的算法标识对应SM2算法,并且密钥类型是公钥 - return pubKeyBytes.length == PUBKEY_LENGTH && pubKeyBytes[0] == SM2.CODE && pubKeyBytes[1] == PUB_KEY.CODE; - } - - @Override - public PubKey resolvePubKey(byte[] pubKeyBytes) { - // 由框架调用 support 方法检查有效性,在此不做重复检查; - return new PubKey(pubKeyBytes); - } - - @Override - public boolean supportCiphertext(byte[] ciphertextBytes) { - // 验证输入字节数组长度>=算法标识长度+椭圆曲线点长度+哈希长度,字节数组的算法标识对应SM2算法 - return ciphertextBytes.length >= ALGORYTHM_BYTES + ECPOINT_SIZE + HASHDIGEST_SIZE && ciphertextBytes[0] == SM2.CODE; - } - - @Override - public AsymmetricCiphertext resolveCiphertext(byte[] ciphertextBytes) { - // 由框架调用 support 方法检查有效性,在此不做重复检查; - return new AsymmetricCiphertext(ciphertextBytes); - } - - @Override - public SignatureDigest sign(PrivKey privKey, byte[] data) { - - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - - // 验证原始私钥长度为256比特,即32字节 - if (rawPrivKeyBytes.length != PRIVKEY_SIZE) - throw new IllegalArgumentException("This key has wrong format!"); - - // 验证密钥数据的算法标识对应SM2签名算法 - if (privKey.getAlgorithm() != SM2) - throw new IllegalArgumentException("This key is not SM2 private key!"); - - // 调用SM2签名算法计算签名结果 - return new SignatureDigest(SM2, SM2Utils.sign(data,rawPrivKeyBytes)); - } - - @Override - public boolean verify(SignatureDigest digest, PubKey pubKey, byte[] data) { - - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawDigestBytes = digest.getRawDigest(); - - // 验证原始公钥长度为520比特,即65字节 - if (rawPubKeyBytes.length != ECPOINT_SIZE) - throw new IllegalArgumentException("This key has wrong format!"); - - // 验证密钥数据的算法标识对应SM2签名算法 - if (pubKey.getAlgorithm() != SM2) - throw new IllegalArgumentException("This key is not SM2 public key!"); - - // 验证签名数据的算法标识对应SM2签名算法,并且原始签名长度为64字节 - if (digest.getAlgorithm() != SM2 || rawDigestBytes.length != SIGNATUREDIGEST_SIZE) - throw new IllegalArgumentException("This is not SM2 signature digest!"); - - // 调用SM2验签算法验证签名结果 - return SM2Utils.verify(data, rawPubKeyBytes, rawDigestBytes); - } - - @Override - public boolean supportDigest(byte[] digestBytes) { - // 验证输入字节数组长度=算法标识长度+签名长度,字节数组的算法标识对应SM2算法 - return digestBytes.length == SIGNATUREDIGEST_LENGTH && digestBytes[0] == SM2.CODE; - } - - @Override - public SignatureDigest resolveDigest(byte[] digestBytes) { - // 由框架调用 support 方法检查有效性,在此不做重复检查; - return new SignatureDigest(digestBytes); - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return SM2; - } - - @Override - public CryptoKeyPair generateKeyPair() { - - // 调用SM2算法的密钥生成算法生成公私钥对priKey和pubKey,返回密钥对 - AsymmetricCipherKeyPair keyPair = SM2Utils.generateKeyPair(); - ECPrivateKeyParameters ecPriv = (ECPrivateKeyParameters) keyPair.getPrivate(); - ECPublicKeyParameters ecPub = (ECPublicKeyParameters) keyPair.getPublic(); - - byte[] privKeyBytesD = ecPriv.getD().toByteArray(); - byte[] privKeyBytes = new byte[PRIVKEY_SIZE]; - if (privKeyBytesD.length > PRIVKEY_SIZE) - System.arraycopy(privKeyBytesD,privKeyBytesD.length-PRIVKEY_SIZE,privKeyBytes,0,PRIVKEY_SIZE); - else System.arraycopy(privKeyBytesD,0,privKeyBytes,PRIVKEY_SIZE-privKeyBytesD.length,privKeyBytesD.length); - -// byte[] pubKeyBytesX = ecPub.getQ().getAffineXCoord().getEncoded(); -// byte[] pubKeyBytesY = ecPub.getQ().getAffineYCoord().getEncoded(); -// byte[] pubKeyBytes = new byte[ECPOINT_SIZE]; -// System.arraycopy(Hex.decode("04"),0,pubKeyBytes,0,1); -// System.arraycopy(pubKeyBytesX,0,pubKeyBytes,1,32); -// System.arraycopy(pubKeyBytesY,0,pubKeyBytes,1+32,32); - byte[] pubKeyBytes = ecPub.getQ().getEncoded(false); - - return new CryptoKeyPair(new PubKey(SM2,pubKeyBytes),new PrivKey(SM2,privKeyBytes)); - } -} - diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/sm/symmetric/SM4SymmetricEncryptionFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/sm/symmetric/SM4SymmetricEncryptionFunction.java deleted file mode 100644 index 3bba6efa..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/sm/symmetric/SM4SymmetricEncryptionFunction.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.jd.blockchain.crypto.impl.sm.symmetric; - -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoKey; -import com.jd.blockchain.crypto.smutils.symmetric.SM4Utils; -import com.jd.blockchain.crypto.symmetric.SymmetricCiphertext; -import com.jd.blockchain.crypto.symmetric.SymmetricEncryptionFunction; -import com.jd.blockchain.crypto.symmetric.SymmetricKey; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.SM4; -import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_BYTES; -import static com.jd.blockchain.crypto.CryptoKeyType.SYMMETRIC_KEY; -import static com.jd.blockchain.crypto.base.BaseCryptoKey.KEY_TYPE_BYTES; - -public class SM4SymmetricEncryptionFunction implements SymmetricEncryptionFunction { - - private static final int KEY_SIZE = 16; - private static final int BLOCK_SIZE = 16; - - private static final int SYMMETRICKEY_LENGTH = ALGORYTHM_BYTES + KEY_TYPE_BYTES + KEY_SIZE; - - @Override - public Ciphertext encrypt(SymmetricKey key, byte[] data) { - - byte[] rawKeyBytes = key.getRawKeyBytes(); - - // 验证原始密钥长度为128比特,即16字节 - if (rawKeyBytes.length != KEY_SIZE) - throw new IllegalArgumentException("This key has wrong format!"); - - // 验证密钥数据的算法标识对应SM4算法 - if (key.getAlgorithm() != SM4) - throw new IllegalArgumentException("The is not SM4 symmetric key!"); - - // 调用底层SM4算法并计算密文数据 - return new SymmetricCiphertext(SM4, SM4Utils.encrypt(data, rawKeyBytes)); - } - - @Override - public void encrypt(SymmetricKey key, InputStream in, OutputStream out) { - - // 读输入流得到明文,加密,密文数据写入输出流 - try { - byte[] sm4Data = new byte[in.available()]; - in.read(sm4Data); - in.close(); - - out.write(encrypt(key, sm4Data).toBytes()); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public byte[] decrypt(SymmetricKey key, Ciphertext ciphertext) { - - byte[] rawKeyBytes = key.getRawKeyBytes(); - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - - // 验证原始密钥长度为128比特,即16字节 - if (rawKeyBytes.length != KEY_SIZE) - throw new IllegalArgumentException("This key has wrong format!"); - - // 验证密钥数据的算法标识对应SM4算法 - if (key.getAlgorithm().CODE != SM4.CODE) - throw new IllegalArgumentException("The is not SM4 symmetric key!"); - - // 验证原始密文长度为分组长度的整数倍 - if (rawCiphertextBytes.length % BLOCK_SIZE != 0) - throw new IllegalArgumentException("This ciphertext has wrong format!"); - - // 验证密文数据算法标识对应SM4算法 - if (ciphertext.getAlgorithm() != SM4) - throw new IllegalArgumentException("This is not SM4 ciphertext!"); - - // 调用底层SM4算法解密,得到明文 - try { - return SM4Utils.decrypt(rawCiphertextBytes, rawKeyBytes); - } catch (Exception e) { - e.printStackTrace(); - } - - throw new IllegalArgumentException("Decrypting process fails!"); - } - - @Override - public void decrypt(SymmetricKey key, InputStream in, OutputStream out) { - - // 读输入流得到密文数据,解密,明文写入输出流 - try { - byte[] sm4Data = new byte[in.available()]; - in.read(sm4Data); - in.close(); - - if (!supportCiphertext(sm4Data)) - throw new IllegalArgumentException("InputStream is not valid SM4 ciphertext!"); - - out.write(decrypt(key, resolveCiphertext(sm4Data))); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public boolean supportSymmetricKey(byte[] symmetricKeyBytes) { - //验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,字节数组的算法标识对应SM4算法且密钥密钥类型是对称密钥 - return symmetricKeyBytes.length == SYMMETRICKEY_LENGTH && symmetricKeyBytes[0] == SM4.CODE && symmetricKeyBytes[1] == SYMMETRIC_KEY.CODE; - } - - @Override - public SymmetricKey resolveSymmetricKey(byte[] symmetricKeyBytes) { - // 由框架调用 support 方法检查有效性,在此不做重复检查; - return new SymmetricKey(symmetricKeyBytes); - } - - @Override - public boolean supportCiphertext(byte[] ciphertextBytes) { - // 验证(输入字节数组长度-算法标识长度)是分组长度的整数倍,字节数组的算法标识对应SM4算法 - return (ciphertextBytes.length - ALGORYTHM_BYTES) % BLOCK_SIZE == 0 && ciphertextBytes[0] == SM4.CODE; - } - - @Override - public SymmetricCiphertext resolveCiphertext(byte[] ciphertextBytes) { - // 由框架调用 support 方法检查有效性,在此不做重复检查; - return new SymmetricCiphertext(ciphertextBytes); - } - - @Override - public CryptoAlgorithm getAlgorithm() { - return SM4; - } - - @Override - public CryptoKey generateSymmetricKey() { - // 根据对应的标识和原始密钥生成相应的密钥数据 - return new SymmetricKey(SM4, SM4Utils.generateKey()); - } -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/jniutils/asymmetric/JNIED25519Utils.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/jniutils/asymmetric/JNIED25519Utils.java deleted file mode 100644 index e1b4bb3b..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/jniutils/asymmetric/JNIED25519Utils.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jd.blockchain.crypto.jniutils.asymmetric; - - -import com.jd.blockchain.crypto.jniutils.hash.JNISHA256Utils; - -import java.util.Objects; - -public class JNIED25519Utils { - - /* load c library */ - static { - //differentiate OS - String osName = System.getProperty("os.name").toLowerCase(); - String path=""; - // Windows OS - if (osName.startsWith("windows")){ - path = Objects.requireNonNull(JNIED25519Utils.class.getClassLoader().getResource("com/jd/blockchain/crypto/jniutils/asymmetric/c_ed25519.dll")).getPath(); - } - // Linux OS - else if (osName.contains("linux")){ - path = Objects.requireNonNull(JNIED25519Utils.class.getClassLoader().getResource("com/jd/blockchain/crypto/jniutils/asymmetric/libc_ed25519.so")).getPath(); - } - // Mac OS - else if (osName.contains("mac")){ - path = Objects.requireNonNull(JNISHA256Utils.class.getClassLoader().getResource("com/jd/blockchain/crypto/jniutils/asymmetric/libc_ed25519.jnilib")).getPath(); - } - - System.load(path); - } - - /* define java native method */ - public native void generateKeyPair(byte[] privKey, byte[] pubKey); - public native byte[] getPubKey(byte[] privKey); - public native byte[] sign(byte[] msg, byte[] privKey, byte[] pubKey); - public native boolean verify(byte[] msg, byte[] pubKey, byte[] signature); - } - diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/jniutils/hash/JNIMBSHA256Utils.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/jniutils/hash/JNIMBSHA256Utils.java deleted file mode 100644 index 5518117d..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/jniutils/hash/JNIMBSHA256Utils.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.jd.blockchain.crypto.jniutils.hash; - -import java.util.Objects; - -public class JNIMBSHA256Utils { - /* load c library */ - static{ - //differentiate OS - String osName = System.getProperty("os.name").toLowerCase(); - String pathOfSo; - String pathOfSo2; - if (osName.contains("linux")){ - pathOfSo = Objects.requireNonNull(JNIMBSHA256Utils.class.getClassLoader().getResource("com/jd/blockchain/crypto/jniutils/hash/libc_mbsha256.so")).getPath(); - pathOfSo2 = Objects.requireNonNull(JNIMBSHA256Utils.class.getClassLoader().getResource("com/jd/blockchain/crypto/jniutils/hash/libisal_crypto.so.2")).getPath(); - } - else throw new IllegalArgumentException("The JNIMBSHA256 implementation is not supported in this Operation System!"); - - System.load(pathOfSo2); - System.load(pathOfSo); - } - - /* define java native method */ - public native byte[][] multiBufferHash(byte[][] multiMsgs); -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/jniutils/hash/JNIRIPEMD160Utils.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/jniutils/hash/JNIRIPEMD160Utils.java deleted file mode 100644 index d9e0ac7a..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/jniutils/hash/JNIRIPEMD160Utils.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jd.blockchain.crypto.jniutils.hash; - -import java.util.Objects; - -public class JNIRIPEMD160Utils { - - /* load c library */ - static { - //differentiate OS - String osName = System.getProperty("os.name").toLowerCase(); - String path=""; - // Windows OS - if (osName.startsWith("windows")){ - path = Objects.requireNonNull(JNIRIPEMD160Utils.class.getClassLoader().getResource("com/jd/blockchain/crypto/jniutils/hash/c_ripemd160.dll")).getPath(); - } - // Linux OS - else if (osName.contains("linux")){ - path = Objects.requireNonNull(JNIRIPEMD160Utils.class.getClassLoader().getResource("com/jd/blockchain/crypto/jniutils/hash/libc_ripemd160.so")).getPath(); - } - // Mac OS - else if (osName.contains("mac")){ - path = Objects.requireNonNull(JNISHA256Utils.class.getClassLoader().getResource("com/jd/blockchain/crypto/jniutils/hash/libc_ripemd160.jnilib")).getPath(); - } - - System.load(path); - } - - /* define java native method */ - public native byte[] hash(byte[] msg); -} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/jniutils/hash/JNISHA256Utils.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/jniutils/hash/JNISHA256Utils.java deleted file mode 100644 index a26ef912..00000000 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/jniutils/hash/JNISHA256Utils.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.jd.blockchain.crypto.jniutils.hash; - -import java.util.Objects; - -public class JNISHA256Utils { - - /* load c library */ - static { - //differentiate OS - String osName = System.getProperty("os.name").toLowerCase(); - String path=""; - // Windows OS - if (osName.startsWith("windows")){ - path = Objects.requireNonNull(JNISHA256Utils.class.getClassLoader().getResource("com/jd/blockchain/crypto/jniutils/hash/c_sha256.dll")).getPath(); - } - // Linux OS - else if (osName.contains("linux")){ - path = Objects.requireNonNull(JNISHA256Utils.class.getClassLoader().getResource("com/jd/blockchain/crypto/jniutils/hash/libc_sha256.so")).getPath(); - } - // Mac OS - else if (osName.contains("mac")){ - path = Objects.requireNonNull(JNISHA256Utils.class.getClassLoader().getResource("com/jd/blockchain/crypto/jniutils/hash/libc_sha256.jnilib")).getPath(); - } - - System.load(path); - } - - /* define java native method */ - public native byte[] hash(byte[] msg); -} diff --git a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectJsonDeserializer.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/serialize/ByteArrayObjectDeserializer.java similarity index 63% rename from source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectJsonDeserializer.java rename to source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/serialize/ByteArrayObjectDeserializer.java index dc8cb119..dcbaf0e8 100644 --- a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectJsonDeserializer.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/serialize/ByteArrayObjectDeserializer.java @@ -1,10 +1,10 @@ -package com.jd.blockchain.web.serializes; +package com.jd.blockchain.crypto.serialize; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.utils.Bytes; @@ -15,22 +15,22 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.util.Map; -public class ByteArrayObjectJsonDeserializer extends JavaBeanDeserializer { +public class ByteArrayObjectDeserializer extends JavaBeanDeserializer { - private ByteArrayObjectJsonDeserializer(Class clazz) { + private ByteArrayObjectDeserializer(Class clazz) { super(ParserConfig.global, clazz); } - public static ByteArrayObjectJsonDeserializer getInstance(Class clazz) { - return new ByteArrayObjectJsonDeserializer(clazz); + public static ByteArrayObjectDeserializer getInstance(Class clazz) { + return new ByteArrayObjectDeserializer(clazz); } @SuppressWarnings("unchecked") @Override public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { if (type instanceof Class && clazz.isAssignableFrom((Class) type)) { - String parseText = parser.parseObject(String.class); - byte[] hashBytes = Base58Utils.decode(parseText); + String base58Str = parser.parseObject(String.class); + byte[] hashBytes = Base58Utils.decode(base58Str); if (clazz == HashDigest.class) { return (T) new HashDigest(hashBytes); } else if (clazz == PubKey.class) { @@ -42,29 +42,6 @@ public class ByteArrayObjectJsonDeserializer extends JavaBeanDeserializer { } else if (clazz == BytesSlice.class) { return (T) new BytesSlice(hashBytes); } - -// else if (clazz == BytesValue.class) { -// ByteArrayObjectJsonSerializer.BytesValueJson valueJson = JSON.parseObject(parseText, ByteArrayObjectJsonSerializer.BytesValueJson.class); -// DataType dataType = valueJson.getType(); -// Object dataVal = valueJson.getValue(); -// byte[] bytes = null; -// switch (dataType) { -// case BYTES: -// bytes = ByteArray.fromHex((String) dataVal); -// break; -// case TEXT: -// bytes = ((String) dataVal).getBytes(); -// break; -// case INT64: -// bytes = BytesUtils.toBytes((Long) dataVal); -// break; -// case JSON: -// bytes = ((String) dataVal).getBytes(); -// break; -// } -// BytesValue bytesValue = new BytesValueImpl(dataType, bytes); -// return (T) bytesValue; -// } } return (T) parser.parse(fieldName); } @@ -77,7 +54,7 @@ public class ByteArrayObjectJsonDeserializer extends JavaBeanDeserializer { for (Map.Entry entry : map.entrySet()) { Object value = entry.getValue(); if (value instanceof String) { - byte[] hashBytes = Base58Utils.decode((String) value); + byte[] hashBytes = Base58Utils.decode((String)value); if (clazz == HashDigest.class) { return new HashDigest(hashBytes); } else if (clazz == PubKey.class) { diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/serialize/ByteArrayObjectSerializer.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/serialize/ByteArrayObjectSerializer.java new file mode 100644 index 00000000..cab05ffa --- /dev/null +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/serialize/ByteArrayObjectSerializer.java @@ -0,0 +1,62 @@ +package com.jd.blockchain.crypto.serialize; + +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import com.jd.blockchain.crypto.PubKey; +import com.jd.blockchain.crypto.asymmetric.SignatureDigest; +import com.jd.blockchain.crypto.hash.HashDigest; +import com.jd.blockchain.utils.Bytes; +import com.jd.blockchain.utils.io.BytesSlice; + +import java.io.IOException; +import java.lang.reflect.Type; + +public class ByteArrayObjectSerializer implements ObjectSerializer { + + private Class clazz; + + private ByteArrayObjectSerializer(Class clazz) { + this.clazz = clazz; + } + + public static ByteArrayObjectSerializer getInstance(Class clazz) { + return new ByteArrayObjectSerializer(clazz); + } + + @Override + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) { + if (object.getClass() != clazz) { + serializer.writeNull(); + return; + } + if (object instanceof HashDigest) { + serializer.write(new HashDigestJson(((HashDigest) object).toBase58())); + } else if (object instanceof PubKey) { + serializer.write(new HashDigestJson(((PubKey) object).toBase58())); + } else if (object instanceof SignatureDigest) { + serializer.write(new HashDigestJson(((SignatureDigest) object).toBase58())); + } else if (object instanceof Bytes) { + serializer.write(new HashDigestJson(((Bytes) object).toBase58())); + } else if (object instanceof BytesSlice) { + byte[] bytes = ((BytesSlice) object).toBytes(); + serializer.write(new HashDigestJson(new String(bytes))); + } + } + + private static class HashDigestJson { + + String value; + + public HashDigestJson(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } +} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricCiphertext.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricCiphertext.java index 39878e38..b5b3834a 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricCiphertext.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricCiphertext.java @@ -1,8 +1,8 @@ package com.jd.blockchain.crypto.symmetric; +import com.jd.blockchain.crypto.BaseCryptoBytes; import com.jd.blockchain.crypto.Ciphertext; import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.base.BaseCryptoBytes; public class SymmetricCiphertext extends BaseCryptoBytes implements Ciphertext { @@ -23,7 +23,7 @@ public class SymmetricCiphertext extends BaseCryptoBytes implements Ciphertext { @Override protected boolean support(CryptoAlgorithm algorithm) { - return algorithm.isSymmetric(); + return CryptoAlgorithm.isEncryptionAlgorithm(algorithm) && CryptoAlgorithm.hasSymmetricKey(algorithm); } @Override diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricCryptography.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricCryptography.java index 4de371a2..89f587c8 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricCryptography.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricCryptography.java @@ -1,34 +1,35 @@ -package com.jd.blockchain.crypto.symmetric; - -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.CryptoAlgorithm; - -public interface SymmetricCryptography { - - /** - * 生成秘钥对; - * - * @param algorithm - * @return - */ - SymmetricKey generateKey(CryptoAlgorithm algorithm); - - /** - * 获取签名方法; - * - * @param algorithm - * @return - */ - SymmetricEncryptionFunction getSymmetricEncryptionFunction(CryptoAlgorithm algorithm); - - byte[] decrypt(byte[] symmetricKeyBytes,byte[] ciphertextBytes); - - Ciphertext resolveCiphertext(byte[] ciphertextBytes); - - Ciphertext tryResolveCiphertext(byte[] ciphertextBytes); - - SymmetricKey resolveSymmetricKey(byte[] symmetricKeyBytes); - - SymmetricKey tryResolveSymmetricKey(byte[] symmetricKeyBytes); - -} +//package com.jd.blockchain.crypto.symmetric; +// +//import com.jd.blockchain.crypto.Ciphertext; +//import com.jd.blockchain.crypto.CryptoAlgorithm; +//import com.jd.blockchain.crypto.SymmetricKey; +// +//public interface SymmetricCryptography { +// +// /** +// * 生成密钥对; +// * +// * @param algorithm +// * @return +// */ +// SymmetricKey generateKey(CryptoAlgorithm algorithm); +// +// /** +// * 获取签名方法; +// * +// * @param algorithm +// * @return +// */ +// SymmetricEncryptionFunction getSymmetricEncryptionFunction(CryptoAlgorithm algorithm); +// +// byte[] decrypt(byte[] symmetricKeyBytes,byte[] ciphertextBytes); +// +// Ciphertext resolveCiphertext(byte[] ciphertextBytes); +// +// Ciphertext tryResolveCiphertext(byte[] ciphertextBytes); +// +// SymmetricKey resolveSymmetricKey(byte[] symmetricKeyBytes); +// +// SymmetricKey tryResolveSymmetricKey(byte[] symmetricKeyBytes); +// +//} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricEncryptionFunction.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricEncryptionFunction.java index 5e97958c..856975ae 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricEncryptionFunction.java +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/symmetric/SymmetricEncryptionFunction.java @@ -6,6 +6,7 @@ import java.io.OutputStream; import com.jd.blockchain.crypto.Ciphertext; import com.jd.blockchain.crypto.CryptoFunction; import com.jd.blockchain.crypto.CryptoSymmetricKeyGenerator; +import com.jd.blockchain.crypto.SymmetricKey; public interface SymmetricEncryptionFunction extends CryptoSymmetricKeyGenerator, CryptoFunction { @@ -37,7 +38,9 @@ public interface SymmetricEncryptionFunction extends CryptoSymmetricKeyGenerator byte[] decrypt(SymmetricKey key, Ciphertext ciphertext); /** - * 解密密文的输入流,把明文写入输出流; + * 解密密文的输入流,把明文写入输出流;
+ * + * 注:实现者不应在方法内部关闭参数指定的输入输出流; * * @param key 密钥; * @param in 密文的输入流; @@ -45,7 +48,6 @@ public interface SymmetricEncryptionFunction extends CryptoSymmetricKeyGenerator */ void decrypt(SymmetricKey key, InputStream in, OutputStream out); - /** * 校验对称密钥格式是否满足要求; * diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/asymmetric/AsymmtricCryptographyImplTest.java b/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/asymmetric/AsymmtricCryptographyImplTest.java deleted file mode 100644 index eee63899..00000000 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/asymmetric/AsymmtricCryptographyImplTest.java +++ /dev/null @@ -1,946 +0,0 @@ -package test.com.jd.blockchain.crypto.asymmetric; - -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.CryptoException; -import com.jd.blockchain.crypto.CryptoKeyType; -import com.jd.blockchain.crypto.asymmetric.*; -import com.jd.blockchain.crypto.impl.AsymmtricCryptographyImpl; -import com.jd.blockchain.utils.io.BytesUtils; - -import org.junit.Test; - -import java.util.Random; - -import static com.jd.blockchain.crypto.CryptoKeyType.PRIV_KEY; -import static com.jd.blockchain.crypto.CryptoKeyType.PUB_KEY; -import static org.junit.Assert.*; -import static org.junit.Assert.assertNotNull; - -public class AsymmtricCryptographyImplTest { - - @Test - public void testGenerateKeyPair() { - - AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); - - //test ED25519 - CryptoAlgorithm algorithm = CryptoAlgorithm.ED25519; - CryptoKeyPair keyPair = asymmetricCrypto.generateKeyPair(algorithm); - - assertNotNull(keyPair); - - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - - assertNotNull(pubKey); - assertNotNull(privKey); - - assertEquals(algorithm,pubKey.getAlgorithm()); - assertEquals(algorithm,privKey.getAlgorithm()); - - assertEquals(32,pubKey.getRawKeyBytes().length); - assertEquals(32,privKey.getRawKeyBytes().length); - - byte[] pubKeyBytes = pubKey.toBytes(); - byte[] privKeyBytes = privKey.toBytes(); - - assertEquals(32+1+1,pubKeyBytes.length); - assertEquals(32+1+1,privKeyBytes.length); - - assertEquals(CryptoAlgorithm.ED25519.CODE,pubKeyBytes[0]); - assertEquals(CryptoAlgorithm.ED25519.CODE,privKeyBytes[0]); - assertEquals(CryptoAlgorithm.ED25519, CryptoAlgorithm.valueOf(pubKey.getAlgorithm().CODE)); - assertEquals(CryptoAlgorithm.ED25519, CryptoAlgorithm.valueOf(privKey.getAlgorithm().CODE)); - - assertEquals(pubKey.getKeyType().CODE,pubKeyBytes[1]); - assertEquals(privKey.getKeyType().CODE,privKeyBytes[1]); - - - //test SM2 - algorithm = CryptoAlgorithm.SM2; - keyPair = asymmetricCrypto.generateKeyPair(algorithm); - - assertNotNull(keyPair); - - pubKey = keyPair.getPubKey(); - privKey = keyPair.getPrivKey(); - - assertNotNull(pubKey); - assertNotNull(privKey); - - assertEquals(algorithm,pubKey.getAlgorithm()); - assertEquals(algorithm,privKey.getAlgorithm()); - - assertEquals(65,pubKey.getRawKeyBytes().length); - assertEquals(32,privKey.getRawKeyBytes().length); - - pubKeyBytes = pubKey.toBytes(); - privKeyBytes = privKey.toBytes(); - - assertEquals(32+1+1,privKeyBytes.length); - assertEquals(65+1+1,pubKeyBytes.length); - - assertEquals(CryptoAlgorithm.SM2.CODE,pubKeyBytes[0]); - assertEquals(CryptoAlgorithm.SM2.CODE,privKeyBytes[0]); - assertEquals(CryptoAlgorithm.SM2, CryptoAlgorithm.valueOf(pubKey.getAlgorithm().CODE)); - assertEquals(CryptoAlgorithm.SM2, CryptoAlgorithm.valueOf(privKey.getAlgorithm().CODE)); - - assertEquals(pubKey.getKeyType().CODE,pubKeyBytes[1]); - assertEquals(privKey.getKeyType().CODE,privKeyBytes[1]); - - - //test JNIED25519 - algorithm = CryptoAlgorithm.JNIED25519; - keyPair = asymmetricCrypto.generateKeyPair(algorithm); - - assertNotNull(keyPair); - - pubKey = keyPair.getPubKey(); - privKey = keyPair.getPrivKey(); - - assertNotNull(pubKey); - assertNotNull(privKey); - - assertEquals(algorithm,pubKey.getAlgorithm()); - assertEquals(algorithm,privKey.getAlgorithm()); - - assertEquals(32,pubKey.getRawKeyBytes().length); - assertEquals(32,privKey.getRawKeyBytes().length); - - pubKeyBytes = pubKey.toBytes(); - privKeyBytes = privKey.toBytes(); - - assertEquals(32+1+1,pubKeyBytes.length); - assertEquals(32+1+1,privKeyBytes.length); - - assertEquals(CryptoAlgorithm.JNIED25519.CODE,pubKeyBytes[0]); - assertEquals(CryptoAlgorithm.JNIED25519.CODE,privKeyBytes[0]); - assertEquals(CryptoAlgorithm.JNIED25519, CryptoAlgorithm.valueOf(pubKey.getAlgorithm().CODE)); - assertEquals(CryptoAlgorithm.JNIED25519, CryptoAlgorithm.valueOf(privKey.getAlgorithm().CODE)); - - assertEquals(pubKey.getKeyType().CODE,pubKeyBytes[1]); - assertEquals(privKey.getKeyType().CODE,privKeyBytes[1]); - } - - @Test - public void testGetSignatureFunction() { - - AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); - Random random = new Random(); - - - //test ED25519 - CryptoAlgorithm algorithm = CryptoAlgorithm.ED25519; - - // 测试256字节的消息进行签名 - byte[] data = new byte[256]; - random.nextBytes(data); - verifyGetSignatureFunction(asymmetricCrypto,algorithm,data,32,32,64,null); - - //错误的算法标识 - verifyGetSignatureFunction(asymmetricCrypto,CryptoAlgorithm.AES,data,32,32,64,IllegalArgumentException.class); - - data = null; - verifyGetSignatureFunction(asymmetricCrypto,algorithm,data,32,32,64,NullPointerException.class); - - - //test SM2 - algorithm = CryptoAlgorithm.SM2; - - // 测试256字节的消息进行签名 - data = new byte[256]; - random.nextBytes(data); - verifyGetSignatureFunction(asymmetricCrypto,algorithm,data,65,32,64,null); - - //错误的算法标识 - verifyGetSignatureFunction(asymmetricCrypto,CryptoAlgorithm.AES,data,65,32,64,IllegalArgumentException.class); - - data = null; - verifyGetSignatureFunction(asymmetricCrypto,algorithm,data,65,32,64,NullPointerException.class); - - - //test JNNIED25519 - algorithm = CryptoAlgorithm.JNIED25519; - - // 测试256字节的消息进行签名 - data = new byte[256]; - random.nextBytes(data); - verifyGetSignatureFunction(asymmetricCrypto,algorithm,data,32,32,64,null); - - //错误的算法标识 - verifyGetSignatureFunction(asymmetricCrypto,CryptoAlgorithm.AES,data,32,32,64,IllegalArgumentException.class); - - data = null; - verifyGetSignatureFunction(asymmetricCrypto,algorithm,data,32,32,64,IllegalArgumentException.class); - } - - private void verifyGetSignatureFunction(AsymmetricCryptography asymmetricCrypto, CryptoAlgorithm algorithm, byte[] data, - int expectedPubKeyLength, int expectedPrivKeyLength, - int expectedSignatureDigestLength, Class expectedException){ - - //初始化一个异常 - Exception actualEx = null; - - try { - SignatureFunction sf = asymmetricCrypto.getSignatureFunction(algorithm); - - assertNotNull(sf); - - CryptoKeyPair keyPair = sf.generateKeyPair(); - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - byte[] pubKeyBytes = pubKey.toBytes(); - byte[] privKeyBytes = privKey.toBytes(); - - assertEquals(algorithm, pubKey.getAlgorithm()); - assertEquals(algorithm, privKey.getAlgorithm()); - assertEquals(expectedPubKeyLength,rawPubKeyBytes.length); - assertEquals(expectedPrivKeyLength,rawPrivKeyBytes.length); - - assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},new byte[]{CryptoKeyType.PUB_KEY.CODE},rawPubKeyBytes), pubKeyBytes); - assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},new byte[]{CryptoKeyType.PRIV_KEY.CODE},rawPrivKeyBytes), privKeyBytes); - - SignatureDigest signatureDigest = sf.sign(privKey,data); - byte[] rawDigest = signatureDigest.getRawDigest(); - - assertEquals(algorithm,signatureDigest.getAlgorithm()); - assertEquals(expectedSignatureDigestLength,rawDigest.length); - byte[] signatureDigestBytes = signatureDigest.toBytes(); - assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},rawDigest),signatureDigestBytes); - - assertTrue(signatureDigest.equals(signatureDigest)); - assertEquals(signatureDigest.hashCode(),signatureDigest.hashCode()); - - assertTrue(sf.verify(signatureDigest,pubKey,data)); - - assertTrue(sf.supportPubKey(pubKeyBytes)); - assertTrue(sf.supportPrivKey(privKeyBytes)); - assertTrue(sf.supportDigest(signatureDigestBytes)); - - assertEquals(pubKey,sf.resolvePubKey(pubKeyBytes)); - assertEquals(privKey,sf.resolvePrivKey(privKeyBytes)); - assertEquals(signatureDigest,sf.resolveDigest(signatureDigestBytes)); - - assertEquals(algorithm,sf.getAlgorithm()); - - } catch (Exception e){ - actualEx = e; - } - - if (expectedException == null) { - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - - @Test - public void testVerify() { - - AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); - Random randomData = new Random(); - - //test ED25519 - CryptoAlgorithm algorithm = CryptoAlgorithm.ED25519; - - // 测试256字节的消息进行签名 - byte[] data = new byte[256]; - randomData.nextBytes(data); - SignatureFunction sf = asymmetricCrypto.getSignatureFunction(algorithm); - CryptoKeyPair keyPair = sf.generateKeyPair(); - byte[] pubKeyBytes = keyPair.getPubKey().toBytes(); - - byte[] signatureDigestBytes = sf.sign(keyPair.getPrivKey(),data).toBytes(); - verifyVerify(asymmetricCrypto,true,data,pubKeyBytes,signatureDigestBytes,null); - - //签名数据末尾两个字节丢失情况下,抛出异常 - byte[] truncatedSignatureDigestBytes = new byte[signatureDigestBytes.length-2]; - System.arraycopy(signatureDigestBytes,0,truncatedSignatureDigestBytes,0,truncatedSignatureDigestBytes.length); - verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,truncatedSignatureDigestBytes,IllegalArgumentException.class); - - byte[] signatureDigestBytesWithWrongAlgCode = signatureDigestBytes; - signatureDigestBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,signatureDigestBytesWithWrongAlgCode,IllegalArgumentException.class); - - signatureDigestBytes = null; - verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,signatureDigestBytes,NullPointerException.class); - - - //test SM2 - algorithm = CryptoAlgorithm.SM2; - - // 测试256字节的消息进行签名 - data = new byte[256]; - randomData.nextBytes(data); - sf = asymmetricCrypto.getSignatureFunction(algorithm); - keyPair = sf.generateKeyPair(); - pubKeyBytes = keyPair.getPubKey().toBytes(); - - signatureDigestBytes = sf.sign(keyPair.getPrivKey(),data).toBytes(); - verifyVerify(asymmetricCrypto,true,data,pubKeyBytes,signatureDigestBytes,null); - - //签名数据末尾两个字节丢失情况下,抛出异常 - truncatedSignatureDigestBytes = new byte[signatureDigestBytes.length-2]; - System.arraycopy(signatureDigestBytes,0,truncatedSignatureDigestBytes,0,truncatedSignatureDigestBytes.length); - verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,truncatedSignatureDigestBytes,IllegalArgumentException.class); - - signatureDigestBytesWithWrongAlgCode = signatureDigestBytes; - signatureDigestBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,signatureDigestBytesWithWrongAlgCode,IllegalArgumentException.class); - - signatureDigestBytes = null; - verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,signatureDigestBytes,NullPointerException.class); - - //test JNIED25519 - algorithm = CryptoAlgorithm.JNIED25519; - - // 测试256字节的消息进行签名 - data = new byte[256]; - randomData.nextBytes(data); - sf = asymmetricCrypto.getSignatureFunction(algorithm); - keyPair = sf.generateKeyPair(); - pubKeyBytes = keyPair.getPubKey().toBytes(); - - signatureDigestBytes = sf.sign(keyPair.getPrivKey(),data).toBytes(); - verifyVerify(asymmetricCrypto,true,data,pubKeyBytes,signatureDigestBytes,null); - - //签名数据末尾两个字节丢失情况下,抛出异常 - truncatedSignatureDigestBytes = new byte[signatureDigestBytes.length-2]; - System.arraycopy(signatureDigestBytes,0,truncatedSignatureDigestBytes,0,truncatedSignatureDigestBytes.length); - verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,truncatedSignatureDigestBytes,IllegalArgumentException.class); - - signatureDigestBytesWithWrongAlgCode = signatureDigestBytes; - signatureDigestBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,signatureDigestBytesWithWrongAlgCode,IllegalArgumentException.class); - - signatureDigestBytes = null; - verifyVerify(asymmetricCrypto,false,data,pubKeyBytes,signatureDigestBytes,NullPointerException.class); - } - - private void verifyVerify(AsymmetricCryptography asymmetricCrypto,boolean expectedResult,byte[] data, - byte[] pubKeyBytes, byte[] signatureDigestBytes, Class expectedException){ - - //初始化一个异常 - Exception actualEx = null; - boolean pass = false; - - try { - - pass = asymmetricCrypto.verify(signatureDigestBytes,pubKeyBytes,data); - - } - catch (Exception e){ - actualEx = e; - } - - assertEquals(expectedResult, pass); - - if (expectedException == null) { - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - - @Test - public void testGetAsymmetricEncryptionFunction() { - - AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); - Random random = new Random(); - - - //test SM2 - CryptoAlgorithm algorithm = CryptoAlgorithm.SM2; - - //Case 1: SM2Encryption with 16 bytes data - byte[] data = new byte[16]; - random.nextBytes(data); - verifyGetAsymmetricEncryptionFunction(asymmetricCrypto, algorithm,65,32,65+16+32,data,null); - - //Case 2: SM2Encryption with 256 bytes data - data = new byte[256]; - random.nextBytes(data); - verifyGetAsymmetricEncryptionFunction(asymmetricCrypto, algorithm,65,32,65+256+32,data,null); - - //Case 3: SM2Encryption with 1 bytes data - data = new byte[3]; - random.nextBytes(data); - verifyGetAsymmetricEncryptionFunction(asymmetricCrypto, algorithm,65,32,65+3+32,data,null); - - //Case 4: SM2Encryption with wrong algorithm - verifyGetAsymmetricEncryptionFunction(asymmetricCrypto,CryptoAlgorithm.AES,65,32,65+3+32,data,IllegalArgumentException.class); - - //Case 5: SM2Encryption with null data - data = null; - verifyGetAsymmetricEncryptionFunction(asymmetricCrypto,algorithm,65,32,65+32,data,NullPointerException.class); - } - - private void verifyGetAsymmetricEncryptionFunction(AsymmetricCryptography asymmetricCrypto, CryptoAlgorithm algorithm, - int expectedPubKeyLength, int expectedPrivKeyLength, - int expectedCiphertextLength, byte[] data, Class expectedException){ - - //初始化一个异常 - Exception actualEx = null; - - try { - AsymmetricEncryptionFunction aef = asymmetricCrypto.getAsymmetricEncryptionFunction(algorithm); - //验证获取的算法实例非空 - assertNotNull(aef); - - CryptoKeyPair keyPair = aef.generateKeyPair(); - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - byte[] pubKeyBytes = pubKey.toBytes(); - byte[] privKeyBytes = privKey.toBytes(); - - assertEquals(algorithm, pubKey.getAlgorithm()); - assertEquals(algorithm, privKey.getAlgorithm()); - assertEquals(expectedPubKeyLength,rawPubKeyBytes.length); - assertEquals(expectedPrivKeyLength,rawPrivKeyBytes.length); - - assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},new byte[]{CryptoKeyType.PUB_KEY.CODE},rawPubKeyBytes), pubKeyBytes); - assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},new byte[]{CryptoKeyType.PRIV_KEY.CODE},rawPrivKeyBytes), privKeyBytes); - - Ciphertext ciphertext = aef.encrypt(pubKey,data); - byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); - - assertEquals(algorithm,ciphertext.getAlgorithm()); - assertEquals(expectedCiphertextLength,rawCiphertextBytes.length); - byte[] ciphertextBytes = ciphertext.toBytes(); - assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},rawCiphertextBytes),ciphertextBytes); - - assertArrayEquals(data,aef.decrypt(privKey,ciphertext)); - - assertTrue(aef.supportPubKey(pubKeyBytes)); - assertTrue(aef.supportPrivKey(privKeyBytes)); - assertTrue(aef.supportCiphertext(ciphertextBytes)); - - assertEquals(pubKey,aef.resolvePubKey(pubKeyBytes)); - assertEquals(privKey,aef.resolvePrivKey(privKeyBytes)); - assertEquals(ciphertext,aef.resolveCiphertext(ciphertextBytes)); - - assertEquals(algorithm,aef.getAlgorithm()); - - - }catch (Exception e){ - actualEx = e; - } - - if(expectedException == null){ - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - - @Test - public void testDecrypt() { - - AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); - Random random = new Random(); - - byte[] data = new byte[16]; - random.nextBytes(data); - - //test SM2 - CryptoAlgorithm algorithm = CryptoAlgorithm.SM2; - AsymmetricEncryptionFunction aef = asymmetricCrypto.getAsymmetricEncryptionFunction(algorithm); - CryptoKeyPair keyPair = aef.generateKeyPair(); - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - Ciphertext ciphertext = aef.encrypt(pubKey,data); - byte[] ciphertextBytes = ciphertext.toBytes(); - - verifyDecrypt(asymmetricCrypto, algorithm, rawPrivKeyBytes, data, ciphertextBytes, null); - - //密钥的算法标识与密文的算法标识不一致情况 - verifyDecrypt(asymmetricCrypto, CryptoAlgorithm.AES, rawPrivKeyBytes, data, ciphertextBytes, IllegalArgumentException.class); - - //密文末尾两个字节丢失情况下,抛出异常 - byte[] truncatedCiphertextBytes = new byte[ciphertextBytes.length-2]; - System.arraycopy(ciphertextBytes,0,truncatedCiphertextBytes,0,truncatedCiphertextBytes.length); - verifyDecrypt(asymmetricCrypto, algorithm, rawPrivKeyBytes, data, truncatedCiphertextBytes, com.jd.blockchain.crypto.CryptoException.class); - - byte[] ciphertextBytesWithWrongAlgCode = ciphertextBytes; - ciphertextBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyDecrypt(asymmetricCrypto,algorithm,rawPrivKeyBytes,data,ciphertextBytesWithWrongAlgCode,IllegalArgumentException.class); - - ciphertextBytes = null; - verifyDecrypt(asymmetricCrypto,algorithm,rawPrivKeyBytes,data,ciphertextBytes,NullPointerException.class); - } - - private void verifyDecrypt(AsymmetricCryptography asymmetricCrypto, CryptoAlgorithm algorithm, - byte[] key, byte[] data, byte[] ciphertextBytes, Class expectedException){ - Exception actualEx = null; - - try { - PrivKey privKey = new PrivKey(algorithm,key); - - byte[] plaintext = asymmetricCrypto.decrypt(privKey.toBytes(), ciphertextBytes); - - //解密后的明文与初始的明文一致 - assertArrayEquals(data,plaintext); - } - catch (Exception e){ - actualEx = e; - } - - if (expectedException == null) { - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - - @Test - public void testResolveCiphertext() { - - - AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); - Random random = new Random(); - - byte[] data = new byte[16]; - random.nextBytes(data); - - //test SM2 - CryptoAlgorithm algorithm = CryptoAlgorithm.SM2; - AsymmetricEncryptionFunction aef = asymmetricCrypto.getAsymmetricEncryptionFunction(algorithm); - CryptoKeyPair keyPair = aef.generateKeyPair(); - PubKey pubKey = keyPair.getPubKey(); - PrivKey privKey = keyPair.getPrivKey(); - byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); - Ciphertext ciphertext = aef.encrypt(pubKey,data); - byte[] ciphertextBytes = ciphertext.toBytes(); - - verifyResolveCiphertext(asymmetricCrypto, algorithm, ciphertextBytes, null); - - - //密文末尾两个字节丢失情况下,抛出异常 - byte[] truncatedCiphertextBytes = new byte[ciphertextBytes.length-2]; - System.arraycopy(ciphertextBytes,0,truncatedCiphertextBytes,0,truncatedCiphertextBytes.length); - verifyDecrypt(asymmetricCrypto, algorithm, rawPrivKeyBytes, data, truncatedCiphertextBytes, CryptoException.class); - - byte[] ciphertextBytesWithWrongAlgCode = ciphertextBytes; - ciphertextBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyResolveCiphertext(asymmetricCrypto,algorithm,ciphertextBytesWithWrongAlgCode,IllegalArgumentException.class); - - ciphertextBytes = null; - verifyResolveCiphertext(asymmetricCrypto,algorithm,ciphertextBytes,NullPointerException.class); - } - - private void verifyResolveCiphertext(AsymmetricCryptography asymmetricCrypto, CryptoAlgorithm algorithm, byte[] ciphertextBytes, - Class expectedException){ - Exception actualEx = null; - - try { - - Ciphertext ciphertext = asymmetricCrypto.resolveCiphertext(ciphertextBytes); - - assertNotNull(ciphertext); - - assertEquals(algorithm, ciphertext.getAlgorithm()); - - assertArrayEquals(ciphertextBytes, ciphertext.toBytes()); - } - catch (Exception e){ - actualEx = e; - } - - if (expectedException == null) { - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - - @Test - public void testTryResolveCiphertext() { - } - - @Test - public void testResolveSignatureDigest() { - - AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); - Random randomData = new Random(); - - //test ED25519 - CryptoAlgorithm algorithm = CryptoAlgorithm.ED25519; - - // 测试256字节的消息进行签名 - byte[] data = new byte[256]; - randomData.nextBytes(data); - SignatureFunction sf = asymmetricCrypto.getSignatureFunction(algorithm); - CryptoKeyPair keyPair = sf.generateKeyPair(); - - byte[] signatureDigestBytes = sf.sign(keyPair.getPrivKey(),data).toBytes(); - verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,signatureDigestBytes,null); - - //签名数据末尾两个字节丢失情况下,抛出异常 - byte[] truncatedSignatureDigestBytes = new byte[signatureDigestBytes.length-2]; - System.arraycopy(signatureDigestBytes,0,truncatedSignatureDigestBytes,0,truncatedSignatureDigestBytes.length); - verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,truncatedSignatureDigestBytes,IllegalArgumentException.class); - - signatureDigestBytes = null; - verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,signatureDigestBytes,NullPointerException.class); - - - //test SM2 - algorithm = CryptoAlgorithm.SM2; - - // 测试256字节的消息进行签名 - data = new byte[256]; - randomData.nextBytes(data); - sf = asymmetricCrypto.getSignatureFunction(algorithm); - keyPair = sf.generateKeyPair(); - - signatureDigestBytes = sf.sign(keyPair.getPrivKey(),data).toBytes(); - verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,signatureDigestBytes,null); - - //签名数据末尾两个字节丢失情况下,抛出异常 - truncatedSignatureDigestBytes = new byte[signatureDigestBytes.length-2]; - System.arraycopy(signatureDigestBytes,0,truncatedSignatureDigestBytes,0,truncatedSignatureDigestBytes.length); - verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,truncatedSignatureDigestBytes,IllegalArgumentException.class); - - signatureDigestBytes = null; - verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,signatureDigestBytes,NullPointerException.class); - - //test JNIED25519 - algorithm = CryptoAlgorithm.JNIED25519; - - // 测试256字节的消息进行签名 - data = new byte[256]; - randomData.nextBytes(data); - sf = asymmetricCrypto.getSignatureFunction(algorithm); - keyPair = sf.generateKeyPair(); - - signatureDigestBytes = sf.sign(keyPair.getPrivKey(),data).toBytes(); - verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,signatureDigestBytes,null); - - //签名数据末尾两个字节丢失情况下,抛出异常 - truncatedSignatureDigestBytes = new byte[signatureDigestBytes.length-2]; - System.arraycopy(signatureDigestBytes,0,truncatedSignatureDigestBytes,0,truncatedSignatureDigestBytes.length); - verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,truncatedSignatureDigestBytes,IllegalArgumentException.class); - - signatureDigestBytes = null; - verifyResolveSignatureDigest(asymmetricCrypto,algorithm,64,signatureDigestBytes,NullPointerException.class); - } - - private void verifyResolveSignatureDigest(AsymmetricCryptography asymmetricCrypto, CryptoAlgorithm algorithm, - int expectedSignatureDigestLength, - byte[] signatureDigestBytes, Class expectedException){ - - //初始化一个异常 - Exception actualEx = null; - - try { - - SignatureDigest signatureDigest = asymmetricCrypto.resolveSignatureDigest(signatureDigestBytes); - - assertNotNull(signatureDigest); - - assertEquals(algorithm,signatureDigest.getAlgorithm()); - - assertEquals(expectedSignatureDigestLength,signatureDigest.getRawDigest().length); - - assertArrayEquals(signatureDigestBytes,signatureDigest.toBytes()); - - } - catch (Exception e){ - actualEx = e; - } - - if (expectedException == null) { - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - - @Test - public void testTryResolveSignatureDigest() { - } - - @Test - public void testRetrievePubKeyBytes() { - - AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); - - //test ED25519 - CryptoAlgorithm algorithm = CryptoAlgorithm.ED25519; - - CryptoKeyPair keyPair = asymmetricCrypto.generateKeyPair(algorithm); - - byte[] expectedPrivKeyBytes = keyPair.getPrivKey().toBytes(); - byte[] expectedPubKeyBytes = keyPair.getPubKey().toBytes(); - - byte[] pubKeyBytes = asymmetricCrypto.retrievePubKeyBytes(expectedPrivKeyBytes); - - assertArrayEquals(expectedPubKeyBytes,pubKeyBytes); - - - //test SM2 - algorithm = CryptoAlgorithm.SM2; - - keyPair = asymmetricCrypto.generateKeyPair(algorithm); - - expectedPrivKeyBytes = keyPair.getPrivKey().toBytes(); - expectedPubKeyBytes = keyPair.getPubKey().toBytes(); - - pubKeyBytes = asymmetricCrypto.retrievePubKeyBytes(expectedPrivKeyBytes); - - assertArrayEquals(expectedPubKeyBytes,pubKeyBytes); - - - //test JNIED25519 - algorithm = CryptoAlgorithm.JNIED25519; - - keyPair = asymmetricCrypto.generateKeyPair(algorithm); - - expectedPrivKeyBytes = keyPair.getPrivKey().toBytes(); - expectedPubKeyBytes = keyPair.getPubKey().toBytes(); - - pubKeyBytes = asymmetricCrypto.retrievePubKeyBytes(expectedPrivKeyBytes); - - assertArrayEquals(expectedPubKeyBytes,pubKeyBytes); - - } - - - @Test - public void testResolvePubKey() { - - AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); - - //test ED25519 - CryptoAlgorithm algorithm = CryptoAlgorithm.ED25519; - - CryptoKeyPair keyPair = asymmetricCrypto.generateKeyPair(algorithm); - - byte[] pubKeyBytes = keyPair.getPubKey().toBytes(); - verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytes,null); - - byte[] truncatedPubKeyBytes = new byte[pubKeyBytes.length-2]; - System.arraycopy(pubKeyBytes,0,truncatedPubKeyBytes,0,truncatedPubKeyBytes.length); - verifyResolvePubKey(asymmetricCrypto,algorithm,32,truncatedPubKeyBytes,IllegalArgumentException.class); - - byte[] pubKeyBytesWithWrongAlgCode = pubKeyBytes; - pubKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytesWithWrongAlgCode,IllegalArgumentException.class); - - byte[] pubKeyBytesWithWrongKeyType= pubKeyBytes; - pubKeyBytesWithWrongKeyType[1] = PRIV_KEY.CODE; - verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytesWithWrongKeyType,IllegalArgumentException.class); - - pubKeyBytes = null; - verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytes,NullPointerException.class); - - - //test SM2 - algorithm = CryptoAlgorithm.SM2; - - keyPair = asymmetricCrypto.generateKeyPair(algorithm); - - pubKeyBytes = keyPair.getPubKey().toBytes(); - verifyResolvePubKey(asymmetricCrypto,algorithm,65,pubKeyBytes,null); - - truncatedPubKeyBytes = new byte[pubKeyBytes.length-2]; - System.arraycopy(pubKeyBytes,0,truncatedPubKeyBytes,0,truncatedPubKeyBytes.length); - verifyResolvePubKey(asymmetricCrypto,algorithm,65,truncatedPubKeyBytes,IllegalArgumentException.class); - - pubKeyBytesWithWrongAlgCode = pubKeyBytes; - pubKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyResolvePubKey(asymmetricCrypto,algorithm,65,pubKeyBytesWithWrongAlgCode,IllegalArgumentException.class); - - pubKeyBytesWithWrongKeyType= pubKeyBytes; - pubKeyBytesWithWrongKeyType[1] = PRIV_KEY.CODE; - verifyResolvePubKey(asymmetricCrypto,algorithm,65,pubKeyBytesWithWrongKeyType,IllegalArgumentException.class); - - pubKeyBytes = null; - verifyResolvePubKey(asymmetricCrypto,algorithm,65,pubKeyBytes,NullPointerException.class); - - //test JNIED25519 - algorithm = CryptoAlgorithm.JNIED25519; - - keyPair = asymmetricCrypto.generateKeyPair(algorithm); - - pubKeyBytes = keyPair.getPubKey().toBytes(); - verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytes,null); - - truncatedPubKeyBytes = new byte[pubKeyBytes.length-2]; - System.arraycopy(pubKeyBytes,0,truncatedPubKeyBytes,0,truncatedPubKeyBytes.length); - verifyResolvePubKey(asymmetricCrypto,algorithm,32,truncatedPubKeyBytes,IllegalArgumentException.class); - - pubKeyBytesWithWrongAlgCode = pubKeyBytes; - pubKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytesWithWrongAlgCode,IllegalArgumentException.class); - - pubKeyBytesWithWrongKeyType= pubKeyBytes; - pubKeyBytesWithWrongKeyType[1] = PRIV_KEY.CODE; - verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytesWithWrongKeyType,IllegalArgumentException.class); - - pubKeyBytes = null; - verifyResolvePubKey(asymmetricCrypto,algorithm,32,pubKeyBytes,NullPointerException.class); - } - - private void verifyResolvePubKey(AsymmetricCryptography asymmetricCrypto, CryptoAlgorithm algorithm, - int expectedPubKeyLength, byte[] pubKeyBytes,Class expectedException){ - - Exception actualEx = null; - - try { - PubKey pubKey = asymmetricCrypto.resolvePubKey(pubKeyBytes); - - assertNotNull(pubKey); - - assertEquals(algorithm, pubKey.getAlgorithm()); - - assertEquals(expectedPubKeyLength, pubKey.getRawKeyBytes().length); - - assertArrayEquals(pubKeyBytes, pubKey.toBytes()); - - } - catch (Exception e){ - actualEx = e; - } - - if (expectedException == null) { - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - - @Test - public void testTryResolvePubKey() { - } - - @Test - public void testResolvePrivKey() { - - AsymmetricCryptography asymmetricCrypto = new AsymmtricCryptographyImpl(); - - //test ED25519 - CryptoAlgorithm algorithm = CryptoAlgorithm.ED25519; - - CryptoKeyPair keyPair = asymmetricCrypto.generateKeyPair(algorithm); - - byte[] privKeyBytes = keyPair.getPrivKey().toBytes(); - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytes,null); - - byte[] truncatedPrivKeyBytes = new byte[privKeyBytes.length-2]; - System.arraycopy(privKeyBytes,0,truncatedPrivKeyBytes,0,truncatedPrivKeyBytes.length); - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,truncatedPrivKeyBytes,IllegalArgumentException.class); - - byte[] privKeyBytesWithWrongAlgCode = privKeyBytes; - privKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytesWithWrongAlgCode,IllegalArgumentException.class); - - byte[] privKeyBytesWithWrongKeyType = privKeyBytes; - privKeyBytesWithWrongKeyType[1] = PUB_KEY.CODE; - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytesWithWrongKeyType,IllegalArgumentException.class); - - privKeyBytes = null; - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytes,NullPointerException.class); - - - //test SM2 - algorithm = CryptoAlgorithm.SM2; - - keyPair = asymmetricCrypto.generateKeyPair(algorithm); - - privKeyBytes = keyPair.getPrivKey().toBytes(); - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytes,null); - - truncatedPrivKeyBytes = new byte[privKeyBytes.length-2]; - System.arraycopy(privKeyBytes,0,truncatedPrivKeyBytes,0,truncatedPrivKeyBytes.length); - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,truncatedPrivKeyBytes,IllegalArgumentException.class); - - privKeyBytesWithWrongAlgCode = privKeyBytes; - privKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytesWithWrongAlgCode,IllegalArgumentException.class); - - privKeyBytesWithWrongKeyType = privKeyBytes; - privKeyBytesWithWrongKeyType[1] = PUB_KEY.CODE; - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytesWithWrongKeyType,IllegalArgumentException.class); - - privKeyBytes = null; - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytes,NullPointerException.class); - - //test JNIED25519 - algorithm = CryptoAlgorithm.JNIED25519; - - keyPair = asymmetricCrypto.generateKeyPair(algorithm); - - privKeyBytes = keyPair.getPrivKey().toBytes(); - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytes,null); - - truncatedPrivKeyBytes = new byte[privKeyBytes.length-2]; - System.arraycopy(privKeyBytes,0,truncatedPrivKeyBytes,0,truncatedPrivKeyBytes.length); - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,truncatedPrivKeyBytes,IllegalArgumentException.class); - - privKeyBytesWithWrongAlgCode = privKeyBytes; - privKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytesWithWrongAlgCode,IllegalArgumentException.class); - - privKeyBytesWithWrongKeyType = privKeyBytes; - privKeyBytesWithWrongKeyType[1] = PUB_KEY.CODE; - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytesWithWrongKeyType,IllegalArgumentException.class); - - privKeyBytes = null; - verifyResolvePrivKey(asymmetricCrypto,algorithm,32,privKeyBytes,NullPointerException.class); - } - - private void verifyResolvePrivKey(AsymmetricCryptography asymmetricCrypto, CryptoAlgorithm algorithm, - int expectedPrivKeyLength, byte[] privKeyBytes,Class expectedException){ - - Exception actualEx = null; - - try { - PrivKey privKey = asymmetricCrypto.resolvePrivKey(privKeyBytes); - - assertNotNull(privKey); - - assertEquals(algorithm, privKey.getAlgorithm()); - - assertEquals(expectedPrivKeyLength, privKey.getRawKeyBytes().length); - - assertArrayEquals(privKeyBytes, privKey.toBytes()); - - } - catch (Exception e){ - actualEx = e; - } - - if (expectedException == null) { - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - - @Test - public void testTryResolvePrivKey() { - } -} \ No newline at end of file diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/hash/HashCryptographyImplTest.java b/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/hash/HashCryptographyImplTest.java deleted file mode 100644 index 513cb577..00000000 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/hash/HashCryptographyImplTest.java +++ /dev/null @@ -1,333 +0,0 @@ -package test.com.jd.blockchain.crypto.hash; - -import static org.junit.Assert.*; - -import java.util.Random; - -import com.jd.blockchain.crypto.smutils.hash.SM3Utils; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.security.RipeMD160Utils; -import com.jd.blockchain.utils.security.ShaUtils; - -import org.junit.Test; - -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.hash.HashCryptography; -import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.hash.HashFunction; -import com.jd.blockchain.crypto.impl.HashCryptographyImpl; - -public class HashCryptographyImplTest { - - @Test - public void testGetFunction() { - HashCryptography hashCrypto = new HashCryptographyImpl(); - Random rand = new Random(); - // test SHA256 - CryptoAlgorithm algorithm = CryptoAlgorithm.SHA256; - byte[] data = new byte[256]; - rand.nextBytes(data); - verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); - - data = new byte[0]; - verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); - - data = new byte[1056]; - rand.nextBytes(data); - verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); - - data = null; - verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,NullPointerException.class); - - - // test RIPEMD160 - algorithm = CryptoAlgorithm.RIPEMD160; - data=new byte[256]; - rand.nextBytes(data); - verifyGetFunction(hashCrypto, algorithm, data, 160 / 8,null); - - data = new byte[0]; - verifyGetFunction(hashCrypto, algorithm, data, 160/ 8,null); - - data = new byte[1056]; - rand.nextBytes(data); - verifyGetFunction(hashCrypto, algorithm, data, 160 / 8,null); - - data = null; - verifyGetFunction(hashCrypto, algorithm, data, 160 / 8,NullPointerException.class); - - // test SM3 - algorithm = CryptoAlgorithm.SM3; - data = new byte[256]; - rand.nextBytes(data); - verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); - - data = new byte[0]; - verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); - - data = new byte[1056]; - rand.nextBytes(data); - verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); - - data = null; - verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,NullPointerException.class); - - // test AES - data = new byte[0]; - algorithm = CryptoAlgorithm.AES; - verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,IllegalArgumentException.class); - - // test JNISHA256 - algorithm = CryptoAlgorithm.JNISHA256; - data = new byte[256]; - rand.nextBytes(data); - verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); - - data = new byte[0]; - verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); - - data = new byte[1056]; - rand.nextBytes(data); - verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,null); - - data = null; - verifyGetFunction(hashCrypto, algorithm, data, 256 / 8,IllegalArgumentException.class); - - // test JNIRIPEMD160 - algorithm = CryptoAlgorithm.JNIRIPEMD160; - data=new byte[256]; - rand.nextBytes(data); - verifyGetFunction(hashCrypto, algorithm, data, 160 / 8,null); - - data = new byte[0]; - verifyGetFunction(hashCrypto, algorithm, data, 160/ 8,null); - - data = new byte[1056]; - rand.nextBytes(data); - verifyGetFunction(hashCrypto, algorithm, data, 160 / 8,null); - - data = null; - verifyGetFunction(hashCrypto, algorithm, data, 160 / 8,IllegalArgumentException.class); - } - - private void verifyGetFunction(HashCryptography hashCrypto, CryptoAlgorithm algorithm, byte[] data, - int expectedRawBytes,Class expectedException) { - Exception actualEx = null; - try { - HashFunction hf = hashCrypto.getFunction(algorithm); - assertNotNull(hf); - - HashDigest hd = hf.hash(data); - - assertEquals(algorithm, hd.getAlgorithm()); - - assertEquals(expectedRawBytes, hd.getRawDigest().length); - - // verify encoding; - byte[] encodedHash = hd.toBytes(); - assertEquals(expectedRawBytes + 1, encodedHash.length); - - - assertEquals(algorithm.CODE, encodedHash[0]); - - //verify equals - assertEquals(true, hd.equals(hf.hash(data))); - - //verify verify - assertTrue( hf.verify(hd, data)); - - } catch (Exception e) { - actualEx = e; - } - - if(expectedException==null){ - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - - @Test - public void testVerifyHashDigestByteArray() { - HashCryptography hashCrypto = new HashCryptographyImpl(); - //test SHA256 - byte[] data=new byte[256]; - Random rand = new Random(); - rand.nextBytes(data); - CryptoAlgorithm algorithm=CryptoAlgorithm.SHA256; - verifyHashDigestByteArray(hashCrypto,algorithm,data,null); - data=null; - verifyHashDigestByteArray(hashCrypto,algorithm,data,NullPointerException.class); - - //test RIPEMD160 - algorithm=CryptoAlgorithm.RIPEMD160; - data=new byte[896]; - rand.nextBytes(data); - verifyHashDigestByteArray(hashCrypto,algorithm,data,null); - data=null; - verifyHashDigestByteArray(hashCrypto,algorithm,data,NullPointerException.class); - - //test SM3 - algorithm=CryptoAlgorithm.SM3; - data=new byte[896]; - rand.nextBytes(data); - verifyHashDigestByteArray(hashCrypto,algorithm,data,null); - data=null; - verifyHashDigestByteArray(hashCrypto,algorithm,data,NullPointerException.class); - - - //test AES - algorithm=CryptoAlgorithm.AES; - data=new byte[277]; - rand.nextBytes(data); - verifyHashDigestByteArray(hashCrypto,algorithm,data,IllegalArgumentException.class); - - //test JNISHA256 - data=new byte[256]; - rand = new Random(); - rand.nextBytes(data); - algorithm=CryptoAlgorithm.JNISHA256; - verifyHashDigestByteArray(hashCrypto,algorithm,data,null); - data=null; - verifyHashDigestByteArray(hashCrypto,algorithm,data,IllegalArgumentException.class); - - //test JNIRIPEMD160 - algorithm=CryptoAlgorithm.JNIRIPEMD160; - data=new byte[896]; - rand.nextBytes(data); - verifyHashDigestByteArray(hashCrypto,algorithm,data,null); - data=null; - verifyHashDigestByteArray(hashCrypto,algorithm,data,IllegalArgumentException.class); - } - - private void verifyHashDigestByteArray(HashCryptography hashCrypto,CryptoAlgorithm algorithm,byte[] data,Class expectedException){ - Exception actualEx=null; - try { - HashFunction hf = hashCrypto.getFunction(algorithm); - assertNotNull(hf); - HashDigest hd = hf.hash(data); - hashCrypto.verify(hd,data); - }catch (Exception e) - { - actualEx=e; - } - if (expectedException==null) - { - assertNull(actualEx); - } - else{ - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - - @Test - public void testResolveHashDigest() { - Random rand = new Random(); - HashCryptography hashCrypto = new HashCryptographyImpl(); - - //test SHA256 - CryptoAlgorithm algorithm = CryptoAlgorithm.SHA256; - byte[] data = new byte[256]; - rand.nextBytes(data); - byte[] hashDigestBytes = hashCrypto.getFunction(algorithm).hash(data).toBytes(); - verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,32+1,null); - - byte[] truncatedHashDigestBytes = new byte[hashDigestBytes.length-2]; - System.arraycopy(hashDigestBytes,0,truncatedHashDigestBytes,0,truncatedHashDigestBytes.length); - verifyResolveHashDigest(algorithm, hashCrypto,truncatedHashDigestBytes,32+1,IllegalArgumentException.class); - - hashDigestBytes = null; - verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,32+1,NullPointerException.class); - - - //test RIPEMD160 - algorithm = CryptoAlgorithm.RIPEMD160; - data = new byte[256]; - rand.nextBytes(data); - hashDigestBytes = hashCrypto.getFunction(algorithm).hash(data).toBytes(); - verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,20+1,null); - - truncatedHashDigestBytes = new byte[hashDigestBytes.length-2]; - System.arraycopy(hashDigestBytes,0,truncatedHashDigestBytes,0,truncatedHashDigestBytes.length); - verifyResolveHashDigest(algorithm, hashCrypto,truncatedHashDigestBytes,20+1,IllegalArgumentException.class); - - hashDigestBytes = null; - verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,20+1,NullPointerException.class); - - - //test SM3 - algorithm = CryptoAlgorithm.SM3; - data = new byte[256]; - rand.nextBytes(data); - hashDigestBytes = hashCrypto.getFunction(algorithm).hash(data).toBytes(); - verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,32+1,null); - - truncatedHashDigestBytes = new byte[hashDigestBytes.length-2]; - System.arraycopy(hashDigestBytes,0,truncatedHashDigestBytes,0,truncatedHashDigestBytes.length); - verifyResolveHashDigest(algorithm, hashCrypto,truncatedHashDigestBytes,32+1,IllegalArgumentException.class); - - hashDigestBytes = null; - verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,32+1,NullPointerException.class); - - - //test JNISHA256 - algorithm = CryptoAlgorithm.JNISHA256; - data = new byte[256]; - rand.nextBytes(data); - hashDigestBytes = hashCrypto.getFunction(algorithm).hash(data).toBytes(); - verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,32+1,null); - - truncatedHashDigestBytes = new byte[hashDigestBytes.length-2]; - System.arraycopy(hashDigestBytes,0,truncatedHashDigestBytes,0,truncatedHashDigestBytes.length); - verifyResolveHashDigest(algorithm, hashCrypto,truncatedHashDigestBytes,32+1,IllegalArgumentException.class); - - hashDigestBytes = null; - verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,32+1,NullPointerException.class); - - //test JNIRIPEMD160 - algorithm = CryptoAlgorithm.JNIRIPEMD160; - data = new byte[256]; - rand.nextBytes(data); - hashDigestBytes = hashCrypto.getFunction(algorithm).hash(data).toBytes(); - verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,20+1,null); - - truncatedHashDigestBytes = new byte[hashDigestBytes.length-2]; - System.arraycopy(hashDigestBytes,0,truncatedHashDigestBytes,0,truncatedHashDigestBytes.length); - verifyResolveHashDigest(algorithm, hashCrypto,truncatedHashDigestBytes,20+1,IllegalArgumentException.class); - - hashDigestBytes = null; - verifyResolveHashDigest(algorithm, hashCrypto,hashDigestBytes,20+1,NullPointerException.class); - } - - private void verifyResolveHashDigest(CryptoAlgorithm algorithm,HashCryptography - hashCrypto,byte[] hashDigestBytes,int expectedLength,ClassexpectedException){ - - Exception actualEx=null; - - try { - - HashDigest hashDigest=hashCrypto.resolveHashDigest(hashDigestBytes); - assertNotNull(hashDigest); - assertEquals(algorithm,hashDigest.getAlgorithm()); - byte[] algBytes = new byte[1]; - algBytes[0] = algorithm.CODE; - assertArrayEquals(hashDigestBytes,BytesUtils.concat(algBytes,hashDigest.getRawDigest())); - assertEquals(expectedLength,hashDigestBytes.length); - - }catch (Exception e) - { - actualEx = e; - } - if (expectedException==null) - { - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - } diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/jniutils/JNIED25519UtilsTest.java b/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/jniutils/JNIED25519UtilsTest.java deleted file mode 100644 index 8cbce2bb..00000000 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/jniutils/JNIED25519UtilsTest.java +++ /dev/null @@ -1,123 +0,0 @@ -package test.com.jd.blockchain.crypto.jniutils; - -import com.jd.blockchain.crypto.jniutils.asymmetric.JNIED25519Utils; - - -public class JNIED25519UtilsTest { - - /* Program entry function */ - public static void main(String args[]) { - - byte[] msg = "abc".getBytes(); - int i; - int j; - int count = 10000; - - long startTS; - long elapsedTS; - - byte[] privKey = new byte[32]; - byte[] pubKey = new byte[32]; - byte[] signature; - - - JNIED25519Utils ed25519 = new JNIED25519Utils(); - - System.out.println("=================== Key Generation test ==================="); - ed25519.generateKeyPair(privKey,pubKey); - System.out.println("Private Key: "); - for(i = 0; i < privKey.length; i++) { - System.out.print(privKey[i] + " "); - if((i+1)%8 == 0) - System.out.println(); - } - System.out.println(); - System.out.println("Public Key: "); - for(i = 0; i < pubKey.length; i++) { - System.out.print(pubKey[i] + " "); - if((i+1)%8 == 0) - System.out.println(); - } - System.out.println(); - - System.out.println("=================== Public Key Retrieval test ==================="); - byte[] pk; - pk = ed25519.getPubKey(privKey); - System.out.println("Retrieved Public Key: "); - for(i = 0; i < pk.length; i++) { - System.out.print(pk[i] + " "); - if((i+1)%8 == 0) - System.out.println(); - } - System.out.println(); - - System.out.println("=================== Signing test ==================="); - signature = ed25519.sign(msg,privKey,pubKey); - System.out.println("Signature: "); - for(i = 0; i < signature.length; i++) { - System.out.print(signature[i] + " "); - if((i+1)%8 == 0) - System.out.println(); - } - System.out.println(); - - System.out.println("=================== Verifying test ==================="); - if (ed25519.verify(msg,pubKey,signature)) - System.out.println("valid signature"); - else System.out.println("invalid signature"); - - System.out.println("=================== Do ED25519 Key Pair Generation Test ==================="); - - - for (j = 0; j < 5; j++) { - System.out.println("------------- round[" + j + "] --------------"); - startTS = System.currentTimeMillis(); - for (i = 0; i < count; i++) { - ed25519.generateKeyPair(privKey,pubKey); - } - elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("ED25519 Key Pair Generation: Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - System.out.println(); - - System.out.println("=================== Do ED25519 Public Key Retrieval Test ==================="); - for (j = 0; j < 5; j++) { - System.out.println("------------- round[" + j + "] --------------"); - startTS = System.currentTimeMillis(); - for (i = 0; i < count; i++) { - ed25519.getPubKey(privKey); - } - elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("ED25519 Public Key Retrieval: Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - System.out.println(); - - System.out.println("=================== Do ED25519 Signing Test ==================="); - for (j = 0; j < 5; j++) { - System.out.println("------------- round[" + j + "] --------------"); - startTS = System.currentTimeMillis(); - for (i = 0; i < count; i++) { - ed25519.sign(msg,privKey,pubKey); - } - elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("ED25519 Signing: Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - System.out.println(); - - System.out.println("=================== Do ED25519 Verifying Test ==================="); - for (j = 0; j < 5; j++) { - System.out.println("------------- round[" + j + "] --------------"); - startTS = System.currentTimeMillis(); - for (i = 0; i < count; i++) { - ed25519.verify(msg,pubKey,signature); - } - elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("ED25519 Verifying: Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - System.out.println(); - } -} diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/jniutils/JNIMBSHA256UtilsTest.java b/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/jniutils/JNIMBSHA256UtilsTest.java deleted file mode 100644 index e5b5ef2f..00000000 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/jniutils/JNIMBSHA256UtilsTest.java +++ /dev/null @@ -1,111 +0,0 @@ -package test.com.jd.blockchain.crypto.jniutils; - -import com.jd.blockchain.crypto.jniutils.hash.JNIMBSHA256Utils; - -public class JNIMBSHA256UtilsTest { - /* Program entry function */ - public static void main(String args[]) { - - String osName = System.getProperty("os.name").toLowerCase(); - - if (! osName.contains("linux")) { - return ; - } - - byte[] array1 = "abc".getBytes(); - byte[] array2 = "abcd".getBytes(); - byte[] array3 = "abcde".getBytes(); - byte[] array4 = "abcdef".getBytes(); - - byte[][] arrays = {array1,array2,array3,array4}; - JNIMBSHA256Utils mbsha256 = new JNIMBSHA256Utils(); - byte[][] results = mbsha256.multiBufferHash(arrays); - - System.out.println("JAVA to C : "); - for (int i = 0; i < arrays.length; i++) { - for (int j = 0; j < arrays[i].length; j++) { - System.out.print(arrays[i][j] + " "); - } - System.out.println(); - } - - System.out.println(); - - System.out.println("C to JAVA : "); - for (int i = 0; i < results.length; i++) { - for (int j = 0; j < results[i].length; j++) { - System.out.print(results[i][j] + " "); - } - System.out.println(); - } - - System.out.println(); - - String str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - byte[] array = str.getBytes(); - - - int count = 1000000; - - - byte[][] arraysx4 = {array,array,array,array}; - byte[][] arraysx8 = {array,array,array,array,array,array,array,array}; - byte[][] arraysx16 = {array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array}; - byte[][] arraysx32 = {array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array,array}; - - - System.out.println("=================== do MBSHA256 hash test in x4==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - mbsha256.multiBufferHash(arraysx4); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SHA256 hashing Count=%s; Elapsed Times=%s; KBPS=%.2f; Total KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS, (count * 1000.00D) / elapsedTS*4)); - } - System.out.println(); - System.out.println(); - - System.out.println("=================== do MBSHA256 hash test in x8==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - mbsha256.multiBufferHash(arraysx8); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SHA256 hashing Count=%s; Elapsed Times=%s; KBPS=%.2f; Total KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS, (count * 1000.00D) / elapsedTS*8)); - } - System.out.println(); - System.out.println(); - - System.out.println("=================== do MBSHA256 hash test in x16==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - mbsha256.multiBufferHash(arraysx16); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SHA256 hashing Count=%s; Elapsed Times=%s; KBPS=%.2f; Total KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS, (count * 1000.00D) / elapsedTS*16)); - } - System.out.println(); - System.out.println(); - - System.out.println("=================== do MBSHA256 hash test in x32==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - mbsha256.multiBufferHash(arraysx32); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SHA256 hashing Count=%s; Elapsed Times=%s; KBPS=%.2f; Total KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS, (count * 1000.00D) / elapsedTS*32)); - } - } -} diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/jniutils/JNIRIPEMD160UtilsTest.java b/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/jniutils/JNIRIPEMD160UtilsTest.java deleted file mode 100644 index 47bb7bda..00000000 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/jniutils/JNIRIPEMD160UtilsTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package test.com.jd.blockchain.crypto.jniutils; - -import com.jd.blockchain.crypto.jniutils.hash.JNIRIPEMD160Utils; - -public class JNIRIPEMD160UtilsTest { - - /* Program entry function */ - public static void main(String args[]) { - byte[] array1 = "abc".getBytes(); - byte[] array2; - JNIRIPEMD160Utils ripemd160 = new JNIRIPEMD160Utils(); - array2 = ripemd160.hash(array1); - - System.out.print("JAVA to C : "); - for (byte anArray1 : array1) { - System.out.print(anArray1 + " "); - } - System.out.println(); - System.out.print("C to JAVA : "); - for (byte anArray2 : array2) { - System.out.print(anArray2 + " "); - } - System.out.println(); - - String str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - byte[] array = str.getBytes(); - int count = 1000000; - - System.out.println("=================== do RIPEMD160 hash test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - ripemd160.hash(array); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("RIPEMD160 hashing Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - } -} \ No newline at end of file diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/jniutils/JNISHA256UtilsTest.java b/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/jniutils/JNISHA256UtilsTest.java deleted file mode 100644 index 10e040f8..00000000 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/jniutils/JNISHA256UtilsTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package test.com.jd.blockchain.crypto.jniutils; - -import com.jd.blockchain.crypto.jniutils.hash.JNISHA256Utils; - -public class JNISHA256UtilsTest { - - /* Program entry function */ - public static void main(String args[]) { - byte[] array1 = "abc".getBytes(); - byte[] array2; - JNISHA256Utils sha256 = new JNISHA256Utils(); - array2 = sha256.hash(array1); - System.out.print("JAVA to C : "); - for (byte anArray1 : array1) { - System.out.print(anArray1 + " "); - } - System.out.println(); - System.out.print("C to JAVA : "); - for (byte anArray2 : array2) { - System.out.print(anArray2 + " "); - } - System.out.println(); - - - String str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - byte[] array = str.getBytes(); - int count = 1000000; - - System.out.println("=================== do SHA256 hash test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - sha256.hash(array); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SHA256 hashing Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - } -} diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/performance/MyAsymmetricEncryptionTest.java b/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/performance/MyAsymmetricEncryptionTest.java deleted file mode 100644 index df33e94c..00000000 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/performance/MyAsymmetricEncryptionTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package test.com.jd.blockchain.crypto.performance; - -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; -import com.jd.blockchain.crypto.impl.sm.asymmetric.SM2CryptoFunction; -import org.bouncycastle.util.encoders.Hex; - -public class MyAsymmetricEncryptionTest { - - public static void main(String[] args) { - - String string1K = "0123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba9876543210"; - String string1M = ""; - for (int i = 0; i < 1024 ; i++) - { - string1M = string1M + string1K; - } - - byte[] data1K = Hex.decode(string1K); - byte[] data1M = Hex.decode(string1M); - int count = 10000; - - SM2CryptoFunction sm2 = new SM2CryptoFunction(); - CryptoKeyPair keyPairSM2 = sm2.generateKeyPair(); - PrivKey privKeySM2 = keyPairSM2.getPrivKey(); - PubKey pubKeySM2 = keyPairSM2.getPubKey(); - - System.out.println("=================== do SM2 encrypt test ==================="); - Ciphertext ciphertextSM2 = null; - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - ciphertextSM2 = sm2.encrypt(pubKeySM2,data1K); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SM2 Encrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do SM2 decrypt test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - sm2.decrypt(privKeySM2,ciphertextSM2); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SM2 Decrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - } -} diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/performance/MyHashTest.java b/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/performance/MyHashTest.java deleted file mode 100644 index 0c2733b0..00000000 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/performance/MyHashTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package test.com.jd.blockchain.crypto.performance; - -import com.jd.blockchain.crypto.impl.def.hash.RIPEMD160HashFunction; -import com.jd.blockchain.crypto.impl.def.hash.SHA256HashFunction; -import com.jd.blockchain.crypto.impl.sm.hash.SM3HashFunction; - -import java.util.Random; - -public class MyHashTest { - - public static void main(String[] args) { - - Random rand = new Random(); - byte[] data1K = new byte[1024]; - rand.nextBytes(data1K); - int count = 1000000; - - SHA256HashFunction sha256hf = new SHA256HashFunction(); - - System.out.println("=================== do SHA256 hash test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - sha256hf.hash(data1K); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SHA256 hashing Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - RIPEMD160HashFunction ripemd160hf = new RIPEMD160HashFunction(); - - System.out.println("=================== do RIPEMD160 hash test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - ripemd160hf.hash(data1K); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("RIPEMD160 hashing Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - SM3HashFunction sm3hf = new SM3HashFunction(); - - System.out.println("=================== do SM3 hash test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - sm3hf.hash(data1K); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SM3 hashing Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - } -} - diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/performance/MySignatureTest.java b/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/performance/MySignatureTest.java deleted file mode 100644 index 189d3011..00000000 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/performance/MySignatureTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package test.com.jd.blockchain.crypto.performance; - -import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; -import com.jd.blockchain.crypto.asymmetric.SignatureDigest; -import com.jd.blockchain.crypto.impl.def.asymmetric.ED25519SignatureFunction; -import com.jd.blockchain.crypto.impl.sm.asymmetric.SM2CryptoFunction; - -import java.util.Random; - -public class MySignatureTest { - - public static void main(String[] args) { - - Random rand = new Random(); - byte[] data = new byte[64]; - rand.nextBytes(data); - int count = 10000; - - ED25519SignatureFunction ed25519sf = new ED25519SignatureFunction(); - CryptoKeyPair keyPairED25519 = ed25519sf.generateKeyPair(); - PrivKey privKeyED25519 = keyPairED25519.getPrivKey(); - PubKey pubKeyED25519 = keyPairED25519.getPubKey(); - - System.out.println("=================== do ED25519 sign test ==================="); - SignatureDigest signatureDigestED25519 = null; - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - signatureDigestED25519 = ed25519sf.sign(privKeyED25519,data); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("ED25519 Signing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do ED25519 verify test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - ed25519sf.verify(signatureDigestED25519,pubKeyED25519,data); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("ED25519 Verifying Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - SM2CryptoFunction sm2 = new SM2CryptoFunction(); - CryptoKeyPair keyPairSM2 = sm2.generateKeyPair(); - PrivKey privKeySM2 = keyPairSM2.getPrivKey(); - PubKey pubKeySM2 = keyPairSM2.getPubKey(); - - - System.out.println("=================== do SM2 sign test ==================="); - SignatureDigest signatureDigestSM2 = null; - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - signatureDigestSM2 = sm2.sign(privKeySM2,data); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SM2 Signing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do SM2 verify test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - sm2.verify(signatureDigestSM2,pubKeySM2,data); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SM2 Verifying Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - } -} diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/performance/MySymmetricEncryptionTest.java b/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/performance/MySymmetricEncryptionTest.java deleted file mode 100644 index 82ea11c0..00000000 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/performance/MySymmetricEncryptionTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package test.com.jd.blockchain.crypto.performance; - -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.impl.def.symmetric.AESSymmetricEncryptionFunction; -import com.jd.blockchain.crypto.impl.sm.symmetric.SM4SymmetricEncryptionFunction; -import com.jd.blockchain.crypto.symmetric.SymmetricKey; -import org.bouncycastle.util.encoders.Hex; - -public class MySymmetricEncryptionTest { - - public static void main(String[] args) { - - String string1K = "0123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba9876543210"; - -// String string1M = ""; -// for (int i = 0; i < 1024 ; i++) -// { -// string1M = string1M + string1K; -// } - - byte[] data1K = Hex.decode(string1K); -// byte[] data1M = Hex.decode(string1M); - - int count = 100000; - - - AESSymmetricEncryptionFunction aes = new AESSymmetricEncryptionFunction(); - SymmetricKey keyAES = (SymmetricKey) aes.generateSymmetricKey(); - Ciphertext ciphertext1KAES = null; - Ciphertext ciphertext1MAES = null; - - System.out.println("=================== do AES encrypt test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - ciphertext1KAES = aes.encrypt(keyAES,data1K); -// ciphertext1MAES = aes.encrypt(keyAES,data1M); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("AES Encrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - - - System.out.println("=================== do AES decrypt test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - aes.decrypt(keyAES,ciphertext1KAES); -// aes.decrypt(keyAES,ciphertext1MAES); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("AES Decrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - SM4SymmetricEncryptionFunction sm4 = new SM4SymmetricEncryptionFunction(); - SymmetricKey keySM4 = (SymmetricKey) sm4.generateSymmetricKey(); - Ciphertext ciphertext1KSM4 = null; - Ciphertext ciphertext1MSM4 = null; - - System.out.println("=================== do SM4 encrypt test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - ciphertext1KSM4 = sm4.encrypt(keySM4,data1K); -// ciphertext1MSM4 =sm4.encrypt(keySM4,data1M); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SM4 Encrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - - System.out.println("=================== do SM4 decrypt test ==================="); - for (int r = 0; r < 5; r++) { - System.out.println("------------- round[" + r + "] --------------"); - long startTS = System.currentTimeMillis(); - for (int i = 0; i < count; i++) { - sm4.decrypt(keySM4,ciphertext1KSM4); -// sm4.decrypt(keySM4,ciphertext1MSM4); - } - long elapsedTS = System.currentTimeMillis() - startTS; - System.out.println(String.format("SM4 Decrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, - (count * 1000.00D) / elapsedTS)); - } - } -} diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/smutils/SM3UtilsTest.java b/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/smutils/SM3UtilsTest.java deleted file mode 100644 index 5d2ff04d..00000000 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/smutils/SM3UtilsTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package test.com.jd.blockchain.crypto.smutils; - -import com.jd.blockchain.crypto.smutils.hash.SM3Utils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class SM3UtilsTest { - - private static final int SM3DIGEST_LENGTH = 32; - - @Test - public void testHash() { - - String testString1 = "abc"; - String testString2 = "abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd"; - String expectedResult1="66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0" ; - String expectedResult2="debe9ff92275b8a138604889c18e5a4d6fdb70e5387e5765293dcba39c0c5732"; - - byte[] testString1Bytes = testString1.getBytes(); - byte[] testString2Bytes = testString2.getBytes(); - byte[] hash1 = SM3Utils.hash(testString1Bytes); - byte[] hash2 = SM3Utils.hash(testString2Bytes); - byte[] expectedResult1Bytes = expectedResult1.getBytes(); - byte[] expectedResult2Bytes = expectedResult2.getBytes(); - assertEquals(hash1.length, SM3DIGEST_LENGTH); - assertEquals(hash2.length, SM3DIGEST_LENGTH); - assertArrayEquals(hash1, Hex.decode(expectedResult1Bytes)); - assertArrayEquals(hash2, Hex.decode(expectedResult2Bytes)); - } - -} \ No newline at end of file diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/smutils/SM4UtilsTest.java b/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/smutils/SM4UtilsTest.java deleted file mode 100644 index 2137eec4..00000000 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/smutils/SM4UtilsTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package test.com.jd.blockchain.crypto.smutils; - -import com.jd.blockchain.crypto.smutils.symmetric.SM4Utils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class SM4UtilsTest { - - private static final int KEY_SIZE = 16; - private static final int BLOCK_SIZE = 16; - - @Test - public void testGenerateKey() { - byte[] key = SM4Utils.generateKey(); - assertEquals(KEY_SIZE,key.length); - } - - @Test - public void testEncrypt() { - - String plaintext = "0123456789abcdeffedcba9876543210"; - String key = "0123456789abcdeffedcba9876543210"; - String iv = "00000000000000000000000000000000"; - String expectedCiphertextIn2ndBlock = "681edf34d206965e86b3e94f536e4246"; - - byte[] plaintextBytes = Hex.decode(plaintext); - byte[] keyBytes = Hex.decode(key); - byte[] ivBytes = Hex.decode(iv); - byte[] expectedCiphertextIn2ndBlockBytes = Hex.decode(expectedCiphertextIn2ndBlock); - - - byte[] ciphertextbytes = SM4Utils.encrypt(plaintextBytes,keyBytes,ivBytes); - - assertEquals(BLOCK_SIZE*3,ciphertextbytes.length); - - byte[] ciphertextIn1stBlockBytes = new byte[BLOCK_SIZE]; - System.arraycopy(ciphertextbytes,0,ciphertextIn1stBlockBytes,0,BLOCK_SIZE); - assertArrayEquals(ivBytes,ciphertextIn1stBlockBytes); - - byte[] ciphertextIn2ndBlockBytes = new byte[BLOCK_SIZE]; - System.arraycopy(ciphertextbytes,BLOCK_SIZE,ciphertextIn2ndBlockBytes,0,BLOCK_SIZE); - assertArrayEquals(expectedCiphertextIn2ndBlockBytes,ciphertextIn2ndBlockBytes); - - - } - - @Test - public void testDecrypt() { - - String plaintext = "0123456789abcdeffedcba987654321000112233445566778899"; - String key = "0123456789abcdeffedcba9876543210"; - String iv = "0123456789abcdeffedcba9876543210"; - - byte[] plaintextBytes = Hex.decode(plaintext); - byte[] keyBytes = Hex.decode(key); - byte[] ivBytes = Hex.decode(iv); - - - byte[] ciphertext = SM4Utils.encrypt(plaintextBytes,keyBytes,ivBytes); - byte[] decryptedData = SM4Utils.decrypt(ciphertext,keyBytes); - assertArrayEquals(plaintextBytes,decryptedData); - - } -} \ No newline at end of file diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/symmetric/SymmetricCryptographyImplTest.java b/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/symmetric/SymmetricCryptographyImplTest.java deleted file mode 100644 index 37a3ceaf..00000000 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/symmetric/SymmetricCryptographyImplTest.java +++ /dev/null @@ -1,471 +0,0 @@ -package test.com.jd.blockchain.crypto.symmetric; - -import com.jd.blockchain.crypto.Ciphertext; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.impl.SymmetricCryptographyImpl; -import com.jd.blockchain.crypto.symmetric.SymmetricCryptography; -import com.jd.blockchain.crypto.symmetric.SymmetricEncryptionFunction; -import com.jd.blockchain.crypto.symmetric.SymmetricKey; -import com.jd.blockchain.utils.io.BytesUtils; - -import org.junit.Test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Random; - -import static com.jd.blockchain.crypto.CryptoKeyType.PRIV_KEY; -import static com.jd.blockchain.crypto.CryptoKeyType.SYMMETRIC_KEY; -import static org.junit.Assert.*; - -public class SymmetricCryptographyImplTest { - - @Test - public void testGenerateKey() { - - SymmetricCryptography symmetricCrypto = new SymmetricCryptographyImpl(); - - //test AES - CryptoAlgorithm algorithm = CryptoAlgorithm.AES; - verifyGenerateKey(symmetricCrypto,algorithm); - - //test SM4 - algorithm = CryptoAlgorithm.SM4; - verifyGenerateKey(symmetricCrypto,algorithm); - } - - private void verifyGenerateKey(SymmetricCryptography symmetricCrypto, CryptoAlgorithm algorithm){ - - SymmetricKey symmetricKey= symmetricCrypto.generateKey(algorithm); - - assertNotNull(symmetricKey); - assertEquals(algorithm, symmetricKey.getAlgorithm()); - assertEquals(128/8,symmetricKey.getRawKeyBytes().length); - - byte[] symmetricKeyBytes = symmetricKey.toBytes(); - //判断密钥数据长度=算法标识长度+密钥掩码长度+原始密钥长度 - assertEquals(1 + 1 + 128 / 8, symmetricKeyBytes.length); - - assertEquals(algorithm.CODE,symmetricKeyBytes[0]); - assertEquals(algorithm,CryptoAlgorithm.valueOf(symmetricKeyBytes[0])); - } - - @Test - public void testGetSymmetricEncryptionFunction() { - - SymmetricCryptography symmetricCrypto = new SymmetricCryptographyImpl(); - Random random = new Random(); - - - //test AES - CryptoAlgorithm algorithm = CryptoAlgorithm.AES; - - //Case 1: AES with 16 bytes data - //刚好一个分组长度,随机生成明文数据 - byte[] data = new byte[16]; - random.nextBytes(data); - verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 2*16, null); - - //Case 2: AES with 33 bytes data - //明文长度大于两倍分组长度,生成的密文是三倍分组长度 - data = new byte[33]; - random.nextBytes(data); - verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 3*16,null); - - //Case 3: AES with 3 bytes data - //明文长度小于分组长度,生成的密文是一倍分组长度 - data = new byte[3]; - random.nextBytes(data); - verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 16,null); - - //Case 4: AES with 0 bytes data - //明文长度小于分组长度,生成的密文是一倍分组长度 - data = new byte[0]; - random.nextBytes(data); - verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 16,null); - - //Case 5 AES with null - //明文为空,可以捕获到异常异常 - data = null; - verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 16,IllegalArgumentException.class); - - - //test ED25519 - algorithm = CryptoAlgorithm.ED25519; - data = new byte[16]; - random.nextBytes(data); - verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 16,IllegalArgumentException.class); - - - //test SM4 - algorithm = CryptoAlgorithm.SM4; - - //Case 1: SM4 with 16 bytes data - data = new byte[16]; - random.nextBytes(data); - //密文长度 = IV长度 + 真实密文长度 - verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 3*16, null); - - //Case 2: SM4 with 33 bytes data - data = new byte[33]; - random.nextBytes(data); - verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 4*16,null); - - //Case 3: SM4 with 3 bytes data - data = new byte[3]; - random.nextBytes(data); - verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 2*16,null); - - //Case 4: SM4 with 0 bytes data - data = new byte[0]; - random.nextBytes(data); - verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 2*16,null); - - //Case 5 SM4 with null - data = null; - verifyGetSymmetricEncryptionFunction(symmetricCrypto, algorithm, data, 16,IllegalArgumentException.class); - } - - //不同明文输入下,用来简化加解密过程的method - private void verifyGetSymmetricEncryptionFunction(SymmetricCryptography symmetricCrypto, CryptoAlgorithm algorithm, - byte[] data, int expectedCiphertextLength, Class expectedException){ - - //初始化一个异常 - Exception actualEx = null; - - try { - SymmetricEncryptionFunction sef = symmetricCrypto.getSymmetricEncryptionFunction(algorithm); - //验证获取的算法实例非空 - assertNotNull(sef); - - SymmetricKey symmetricKey = (SymmetricKey) sef.generateSymmetricKey(); - - //验证SymmetricKey的getAlgorithm方法 - assertEquals(algorithm, symmetricKey.getAlgorithm()); - //验证SymmetricKey的getRawKeyBytes方法 - assertEquals(16, symmetricKey.getRawKeyBytes().length); - //验证SymmetricKey的toBytes方法 - assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},new byte[]{SYMMETRIC_KEY.CODE},symmetricKey.getRawKeyBytes()), symmetricKey.toBytes()); - - - Ciphertext ciphertext = sef.encrypt(symmetricKey,data); - - //Ciphertext中算法标识与入参算法一致 - assertEquals(algorithm, ciphertext.getAlgorithm()); - //验证原始密文长度与预期长度一致 - assertEquals(expectedCiphertextLength, ciphertext.getRawCiphertext().length); - //验证密文数据长度=算法标识长度+预期长度 - byte[] ciphertextBytes = ciphertext.toBytes(); - assertArrayEquals(BytesUtils.concat(new byte[]{algorithm.CODE},ciphertext.getRawCiphertext()), ciphertextBytes); - - - //验证equal - assertTrue(ciphertext.equals(ciphertext)); - assertEquals(ciphertext.hashCode(),ciphertext.hashCode()); - - //验证SymmetricEncryptionFunction的decrypt - assertArrayEquals(data, sef.decrypt(symmetricKey,ciphertext)); - - //测试SymmetricEncryptionFunction的输入输出流的加解密方法 - InputStream inPlaintext = new ByteArrayInputStream(data); - //16字节的明文输入,将会产生32字节的密文 - OutputStream outCiphertext = new ByteArrayOutputStream(ciphertext.toBytes().length); - InputStream inCiphertext = new ByteArrayInputStream(ciphertext.toBytes()); - OutputStream outPlaintext = new ByteArrayOutputStream(data.length); - sef.encrypt(symmetricKey, inPlaintext, outCiphertext); - sef.decrypt(symmetricKey, inCiphertext, outPlaintext); - - //验证SymmetricEncryptionFunction的supportCiphertext方法 - assertTrue(sef.supportCiphertext(ciphertextBytes)); - - //验证SymmetricEncryptionFunction的resolveCiphertext方法 - assertEquals(ciphertext, sef.resolveCiphertext(ciphertextBytes)); - - //验证SymmetricEncryptionFunction的supportSymmetricKey方法 - assertTrue(sef.supportSymmetricKey(symmetricKey.toBytes())); - - //验证SymmetricEncryptionFunction的resolveSymmetricKey方法 - assertEquals(symmetricKey, sef.resolveSymmetricKey(symmetricKey.toBytes())); - - //验证SymmetricEncryptionFunction的getAlgorithm - assertEquals(algorithm, sef.getAlgorithm()); - - } catch (Exception e){ - actualEx = e; - } - - if (expectedException == null) { - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - - @Test - public void testDecrypt() { - - SymmetricCryptography symmetricCrypto = new SymmetricCryptographyImpl(); - Random randomData = new Random(); - Random randomKey = new Random(); - - - //test AES - CryptoAlgorithm algorithm = CryptoAlgorithm.AES; - SymmetricEncryptionFunction sef = symmetricCrypto.getSymmetricEncryptionFunction(algorithm); - - byte[] data = new byte[16]; - randomData.nextBytes(data); - byte[] key = new byte[16]; - randomKey.nextBytes(key); - - SymmetricKey symmetricKey = new SymmetricKey(algorithm, key); - byte[] ciphertextBytes = sef.encrypt(symmetricKey,data).toBytes(); - - verifyDecrypt(symmetricCrypto, algorithm, key, data, ciphertextBytes, null); - - //密钥的算法标识与密文的算法标识不一致情况 - verifyDecrypt(symmetricCrypto, CryptoAlgorithm.SM4, key, data, ciphertextBytes, IllegalArgumentException.class); - - //密文末尾两个字节丢失情况下,抛出异常 - byte[] truncatedCiphertextBytes = new byte[ciphertextBytes.length-2]; - System.arraycopy(ciphertextBytes,0,truncatedCiphertextBytes,0,truncatedCiphertextBytes.length); - verifyDecrypt(symmetricCrypto, algorithm, key, data, truncatedCiphertextBytes, IllegalArgumentException.class); - - byte[] ciphertextBytesWithWrongAlgCode = ciphertextBytes; - ciphertextBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyDecrypt(symmetricCrypto,algorithm,key,data,ciphertextBytesWithWrongAlgCode,IllegalArgumentException.class); - - ciphertextBytes = null; - verifyDecrypt(symmetricCrypto,algorithm,key,data,ciphertextBytes,NullPointerException.class); - - - //test SM4 - algorithm = CryptoAlgorithm.SM4; - sef = symmetricCrypto.getSymmetricEncryptionFunction(algorithm); - symmetricKey = new SymmetricKey(algorithm, key); - ciphertextBytes = sef.encrypt(symmetricKey,data).toBytes(); - - verifyDecrypt(symmetricCrypto, algorithm, key, data, ciphertextBytes, null); - - //密钥的算法标识与密文的算法标识不一致情况 - verifyDecrypt(symmetricCrypto, CryptoAlgorithm.AES, key, data, ciphertextBytes, IllegalArgumentException.class); - - //密文末尾两个字节丢失情况下,抛出异常 - truncatedCiphertextBytes = new byte[ciphertextBytes.length-2]; - System.arraycopy(ciphertextBytes,0,truncatedCiphertextBytes,0,truncatedCiphertextBytes.length); - verifyDecrypt(symmetricCrypto, algorithm, key, data, truncatedCiphertextBytes, IllegalArgumentException.class); - - ciphertextBytesWithWrongAlgCode = ciphertextBytes; - ciphertextBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyDecrypt(symmetricCrypto,algorithm,key,data,ciphertextBytesWithWrongAlgCode,IllegalArgumentException.class); - - ciphertextBytes = null; - verifyDecrypt(symmetricCrypto,algorithm,key,data,ciphertextBytes,NullPointerException.class); - } - - private void verifyDecrypt(SymmetricCryptography symmetricCrypto, CryptoAlgorithm algorithm, - byte[] key, byte[] data, byte[] ciphertextBytes, Class expectedException) { - - Exception actualEx = null; - - try { - SymmetricKey symmetricKey = new SymmetricKey(algorithm,key); - - byte[] plaintext = symmetricCrypto.decrypt(symmetricKey.toBytes(), ciphertextBytes); - - //解密后的明文与初始的明文一致 - assertArrayEquals(data,plaintext); - } - catch (Exception e){ - actualEx = e; - } - - if (expectedException == null) { - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - - @Test - public void testResolveCiphertext() { - - SymmetricCryptography symmetricCrypto = new SymmetricCryptographyImpl(); - Random randomData = new Random(); - Random randomKey = new Random(); - - //test AES - CryptoAlgorithm algorithm = CryptoAlgorithm.AES; - SymmetricEncryptionFunction sef = symmetricCrypto.getSymmetricEncryptionFunction(algorithm); - - byte[] data = new byte[16]; - randomData.nextBytes(data); - byte[] key = new byte[16]; - randomKey.nextBytes(key); - - SymmetricKey symmetricKey = new SymmetricKey(algorithm, key); - byte[] ciphertextBytes = sef.encrypt(symmetricKey,data).toBytes(); - verifyResolveCiphertext(symmetricCrypto, algorithm, ciphertextBytes, null); - - byte[] truncatedCiphertextBytes = new byte[ciphertextBytes.length-2]; - System.arraycopy(ciphertextBytes,0,truncatedCiphertextBytes,0,truncatedCiphertextBytes.length); - verifyResolveCiphertext(symmetricCrypto,algorithm,truncatedCiphertextBytes,IllegalArgumentException.class); - - byte[] ciphertextBytesWithWrongAlgCode = ciphertextBytes; - ciphertextBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyResolveCiphertext(symmetricCrypto,algorithm,ciphertextBytesWithWrongAlgCode,IllegalArgumentException.class); - - ciphertextBytes = null; - verifyResolveCiphertext(symmetricCrypto,algorithm,ciphertextBytes,NullPointerException.class); - - - //test SM4 - algorithm = CryptoAlgorithm.SM4; - sef = symmetricCrypto.getSymmetricEncryptionFunction(algorithm); - - symmetricKey = new SymmetricKey(algorithm, key); - ciphertextBytes = sef.encrypt(symmetricKey,data).toBytes(); - - verifyResolveCiphertext(symmetricCrypto, algorithm, ciphertextBytes, null); - - truncatedCiphertextBytes = new byte[ciphertextBytes.length-2]; - System.arraycopy(ciphertextBytes,0,truncatedCiphertextBytes,0,truncatedCiphertextBytes.length); - verifyResolveCiphertext(symmetricCrypto,algorithm,truncatedCiphertextBytes,IllegalArgumentException.class); - - ciphertextBytesWithWrongAlgCode = ciphertextBytes; - ciphertextBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyResolveCiphertext(symmetricCrypto,algorithm,ciphertextBytesWithWrongAlgCode,IllegalArgumentException.class); - - ciphertextBytes = null; - verifyResolveCiphertext(symmetricCrypto,algorithm,ciphertextBytes,NullPointerException.class); - } - - private void verifyResolveCiphertext(SymmetricCryptography symmetricCrypto, CryptoAlgorithm algorithm, byte[] ciphertextBytes, - Class expectedException) { - - Exception actualEx = null; - - try { - Ciphertext ciphertext = symmetricCrypto.resolveCiphertext(ciphertextBytes); - - assertNotNull(ciphertext); - - assertEquals(algorithm, ciphertext.getAlgorithm()); - - assertEquals(0, ciphertext.getRawCiphertext().length % 16); - - assertArrayEquals(ciphertextBytes, ciphertext.toBytes()); - } - catch (Exception e){ - actualEx = e; - } - - if (expectedException == null) { - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - - @Test - public void testTryResolveCiphertext() { - } - - - - @Test - public void testResolveSymmetricKey() { - - SymmetricCryptography symmetricCrypto = new SymmetricCryptographyImpl(); - - //test AES - CryptoAlgorithm algorithm = CryptoAlgorithm.AES; - - Random randomKey = new Random(); - byte[] key = new byte[16]; - randomKey.nextBytes(key); - - byte[] symmetricKeyBytes = BytesUtils.concat(new byte[]{algorithm.CODE},new byte[]{SYMMETRIC_KEY.CODE},key); - verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytes,null); - - byte[] truncatedSymmetricKeyBytes = new byte[symmetricKeyBytes.length-2]; - System.arraycopy(symmetricKeyBytes,0,truncatedSymmetricKeyBytes,0,truncatedSymmetricKeyBytes.length); - verifyResolveSymmetricKey(symmetricCrypto,algorithm,truncatedSymmetricKeyBytes,IllegalArgumentException.class); - - byte[] symmetricKeyBytesWithWrongAlgCode = symmetricKeyBytes; - symmetricKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytesWithWrongAlgCode,IllegalArgumentException.class); - - byte[] symmetricKeyBytesWithWrongKeyType= symmetricKeyBytes; - System.arraycopy(symmetricKeyBytes,0,symmetricKeyBytesWithWrongKeyType,0,symmetricKeyBytesWithWrongKeyType.length); - symmetricKeyBytesWithWrongKeyType[1] = PRIV_KEY.CODE; - verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytesWithWrongKeyType,IllegalArgumentException.class); - - symmetricKeyBytes = null; - verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytes,NullPointerException.class); - - - //test SM4 - algorithm = CryptoAlgorithm.SM4; - symmetricKeyBytes = BytesUtils.concat(new byte[]{algorithm.CODE},new byte[]{SYMMETRIC_KEY.CODE},key); - - verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytes,null); - - truncatedSymmetricKeyBytes = new byte[symmetricKeyBytes.length-2]; - System.arraycopy(symmetricKeyBytes,0,truncatedSymmetricKeyBytes,0,truncatedSymmetricKeyBytes.length); - verifyResolveSymmetricKey(symmetricCrypto,algorithm,truncatedSymmetricKeyBytes,IllegalArgumentException.class); - - symmetricKeyBytesWithWrongAlgCode = symmetricKeyBytes; - symmetricKeyBytesWithWrongAlgCode[0] = CryptoAlgorithm.SHA256.CODE; - verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytesWithWrongAlgCode,IllegalArgumentException.class); - - symmetricKeyBytesWithWrongKeyType= symmetricKeyBytes; - System.arraycopy(symmetricKeyBytes,0,symmetricKeyBytesWithWrongKeyType,0,symmetricKeyBytesWithWrongKeyType.length); - symmetricKeyBytesWithWrongKeyType[1] = PRIV_KEY.CODE; - verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytesWithWrongKeyType,IllegalArgumentException.class); - - symmetricKeyBytes = null; - verifyResolveSymmetricKey(symmetricCrypto,algorithm,symmetricKeyBytes,NullPointerException.class); - } - - private void verifyResolveSymmetricKey(SymmetricCryptography symmetricCrypto, CryptoAlgorithm algorithm, byte[] symmetricKeyBytes, - Class expectedException) { - - Exception actualEx = null; - - try { - SymmetricKey symmetricKey = symmetricCrypto.resolveSymmetricKey(symmetricKeyBytes); - - assertNotNull(symmetricKey); - - assertEquals(algorithm, symmetricKey.getAlgorithm()); - - assertEquals(16, symmetricKey.getRawKeyBytes().length); - - assertArrayEquals(symmetricKeyBytes, symmetricKey.toBytes()); - } - catch (Exception e){ - actualEx = e; - } - - if (expectedException == null) { - assertNull(actualEx); - } - else { - assertNotNull(actualEx); - assertTrue(expectedException.isAssignableFrom(actualEx.getClass())); - } - } - - @Test - public void testTryResolveSymmetricKey() { - } -} diff --git a/source/crypto/crypto-impl/pom.xml b/source/crypto/crypto-impl/pom.xml new file mode 100644 index 00000000..cb07d6c5 --- /dev/null +++ b/source/crypto/crypto-impl/pom.xml @@ -0,0 +1,20 @@ + + 4.0.0 + + com.jd.blockchain + crypto + 0.9.0-SNAPSHOT + + crypto-impl + + + + com.jd.blockchain + crypto-framework + ${project.version} + + + + \ No newline at end of file diff --git a/source/crypto/crypto-impl/src/main/java/com/jd/blockchain/crypto/impl/AsymmtricCryptographyImpl.java b/source/crypto/crypto-impl/src/main/java/com/jd/blockchain/crypto/impl/AsymmtricCryptographyImpl.java new file mode 100644 index 00000000..41b38408 --- /dev/null +++ b/source/crypto/crypto-impl/src/main/java/com/jd/blockchain/crypto/impl/AsymmtricCryptographyImpl.java @@ -0,0 +1,220 @@ +//package com.jd.blockchain.crypto.impl; +// +//import com.jd.blockchain.crypto.Ciphertext; +//import com.jd.blockchain.crypto.CryptoAlgorithm; +//import com.jd.blockchain.crypto.PrivKey; +//import com.jd.blockchain.crypto.PubKey; +//import com.jd.blockchain.crypto.asymmetric.*; +//import com.jd.blockchain.crypto.impl.jni.asymmetric.JNIED25519SignatureFunction; +//import com.jd.blockchain.crypto.impl.sm.asymmetric.SM2CryptoFunction; +//import com.jd.blockchain.crypto.service.classic.ED25519SignatureFunction; +// +//public class AsymmtricCryptographyImpl implements AsymmetricCryptography { +// +// private static final SignatureFunction ED25519_SIGF = new ED25519SignatureFunction(); +// +// private static final SignatureFunction SM2_SIGF = new SM2CryptoFunction(); +// +// private static final SignatureFunction JNIED25519_SIGF = new JNIED25519SignatureFunction(); +// +// private static final AsymmetricEncryptionFunction SM2_ENCF = new SM2CryptoFunction(); +// +// /** +// * 封装了非对称密码算法对应的密钥生成算法 +// */ +// @Override +// public CryptoKeyPair generateKeyPair(CryptoAlgorithm algorithm) { +// +// //判断算法是签名算法还是非对称加密算法,并根据算法生成密钥对,否则抛出异常 +// if (algorithm.isSignable() && algorithm.hasAsymmetricKey()){ +// return getSignatureFunction(algorithm).generateKeyPair(); +// } +// else if (algorithm.isEncryptable() && algorithm.hasAsymmetricKey()){ +// return getAsymmetricEncryptionFunction(algorithm).generateKeyPair(); +// } +// else throw new IllegalArgumentException("The specified algorithm is not signature or asymmetric encryption algorithm!"); +// } +// +// @Override +// public SignatureFunction getSignatureFunction(CryptoAlgorithm algorithm) { +// //遍历签名算法,如果满足,则返回实例 +// switch (algorithm) { +// case ED25519: +// return ED25519_SIGF; +// case SM2: +// return SM2_SIGF; +// case JNIED25519: +// return JNIED25519_SIGF; +// default: +// break; +// } +// throw new IllegalArgumentException("The specified algorithm is not signature algorithm!"); +// } +// +// @Override +// public boolean verify(byte[] digestBytes, byte[] pubKeyBytes, byte[] data) { +// +// //得到SignatureDigest类型的签名摘要,并得到算法标识 +// SignatureDigest signatureDigest = resolveSignatureDigest(digestBytes); +// CryptoAlgorithm algorithm = signatureDigest.getAlgorithm(); +// PubKey pubKey = resolvePubKey(pubKeyBytes); +// +// //验证两个输入中算法标识一致,否则抛出异常 +// if (algorithm != signatureDigest.getAlgorithm()) +// throw new IllegalArgumentException("Digest's algorithm and key's are not matching!"); +// +// //根据算法标识,调用对应算法实例来验证签名摘要 +// return getSignatureFunction(algorithm).verify(signatureDigest,pubKey,data); +// } +// +// @Override +// public AsymmetricEncryptionFunction getAsymmetricEncryptionFunction(CryptoAlgorithm algorithm) { +// //遍历非对称加密算法,如果满足,则返回实例 +// switch (algorithm) { +// case SM2: +// return SM2_ENCF; +// default: +// break; +// } +// throw new IllegalArgumentException("The specified algorithm is not asymmetric encryption algorithm!"); +// } +// +// @Override +// public byte[] decrypt(byte[] privKeyBytes, byte[] ciphertextBytes) { +// +// //分别得到PrivKey和Ciphertext类型的密钥和密文,以及privKey对应的算法 +// PrivKey privKey = resolvePrivKey(privKeyBytes); +// Ciphertext ciphertext = resolveCiphertext(ciphertextBytes); +// CryptoAlgorithm algorithm = privKey.getAlgorithm(); +// +// //验证两个输入中算法标识一致,否则抛出异常 +// if (algorithm != ciphertext.getAlgorithm()) +// throw new IllegalArgumentException("Ciphertext's algorithm and key's are not matching!"); +// +// //根据算法标识,调用对应算法实例来计算返回明文 +// return getAsymmetricEncryptionFunction(algorithm).decrypt(privKey,ciphertext); +// } +// +// @Override +// public Ciphertext resolveCiphertext(byte[] ciphertextBytes) { +// Ciphertext ciphertext = tryResolveCiphertext(ciphertextBytes); +// if (ciphertext == null) +// throw new IllegalArgumentException("This ciphertextBytes cannot be resolved!"); +// else return ciphertext; +// } +// +// @Override +// public Ciphertext tryResolveCiphertext(byte[] ciphertextBytes) { +// //遍历非对称加密算法,如果满足,则返回解析结果 +// if (SM2_ENCF.supportCiphertext(ciphertextBytes)){ +// return SM2_ENCF.resolveCiphertext(ciphertextBytes); +// } +// //否则返回null +// return null; +// } +// +// @Override +// public SignatureDigest resolveSignatureDigest(byte[] digestBytes) { +// SignatureDigest signatureDigest = tryResolveSignatureDigest(digestBytes); +// if (signatureDigest == null) +// throw new IllegalArgumentException("This digestBytes cannot be resolved!"); +// else return signatureDigest; +// } +// +// @Override +// public SignatureDigest tryResolveSignatureDigest(byte[] digestBytes) { +// //遍历签名算法,如果满足,则返回解析结果 +// if (ED25519_SIGF.supportDigest(digestBytes)){ +// return ED25519_SIGF.resolveDigest(digestBytes); +// } +// if (SM2_SIGF.supportDigest(digestBytes)){ +// return SM2_SIGF.resolveDigest(digestBytes); +// } +// if (JNIED25519_SIGF.supportDigest(digestBytes)){ +// return JNIED25519_SIGF.resolveDigest(digestBytes); +// } +// //否则返回null +// return null; +// } +// +// @Override +// public byte[] retrievePubKeyBytes(byte[] privKeyBytes) { +// byte[] pubKeyBytes = tryRetrievePubKeyBytes(privKeyBytes); +// if (pubKeyBytes == null) +// throw new IllegalArgumentException("The specified algorithm in privKeyBytes is not signature or asymmetric encryption algorithm!"); +// else return pubKeyBytes; +// } +// +// @Override +// public byte[] tryRetrievePubKeyBytes(byte[] privKeyBytes) { +// //解析私钥获得算法标识 +// CryptoAlgorithm algorithm = resolvePrivKey(privKeyBytes).getAlgorithm(); +// +// //判断算法是签名算法还是非对称加密算法,并根据算法生成密钥对,否则抛出异常 +// if (algorithm.isSignable() && algorithm.hasAsymmetricKey()){ +// return getSignatureFunction(algorithm).retrievePubKeyBytes(privKeyBytes); +// } +// else if (algorithm.isEncryptable() && algorithm.hasAsymmetricKey()){ +// return getAsymmetricEncryptionFunction(algorithm).retrievePubKeyBytes(privKeyBytes); +// } +// //否则返回null +// return null; +// } +// +// @Override +// public PubKey resolvePubKey(byte[] pubKeyBytes) { +// PubKey pubKey = tryResolvePubKey(pubKeyBytes); +// if (pubKey == null) +// throw new IllegalArgumentException("This pubKeyBytes cannot be resolved!"); +// else return pubKey; +// +// } +// +// @Override +// public PubKey tryResolvePubKey(byte[] pubKeyBytes) { +// //遍历签名算法,如果满足,则返回解析结果 +// if (ED25519_SIGF.supportPubKey(pubKeyBytes)){ +// return ED25519_SIGF.resolvePubKey(pubKeyBytes); +// } +// if (SM2_SIGF.supportPubKey(pubKeyBytes)){ +// return SM2_SIGF.resolvePubKey(pubKeyBytes); +// } +// if (JNIED25519_SIGF.supportPubKey(pubKeyBytes)){ +// return JNIED25519_SIGF.resolvePubKey(pubKeyBytes); +// } +// //遍历非对称加密算法,如果满足,则返回解析结果 +// if (SM2_ENCF.supportPubKey(pubKeyBytes)){ +// return SM2_ENCF.resolvePubKey(pubKeyBytes); +// } +// //否则返回null +// return null; +// } +// +// @Override +// public PrivKey resolvePrivKey(byte[] privKeyBytes) { +// PrivKey privKey = tryResolvePrivKey(privKeyBytes); +// if (privKey == null) +// throw new IllegalArgumentException("This privKeyBytes cannot be resolved!"); +// else return privKey; +// } +// +// @Override +// public PrivKey tryResolvePrivKey(byte[] privKeyBytes) { +// //遍历签名算法,如果满足,则返回解析结果 +// if (ED25519_SIGF.supportPrivKey(privKeyBytes)){ +// return ED25519_SIGF.resolvePrivKey(privKeyBytes); +// } +// if (SM2_SIGF.supportPrivKey(privKeyBytes)){ +// return SM2_SIGF.resolvePrivKey(privKeyBytes); +// } +// if (JNIED25519_SIGF.supportPrivKey(privKeyBytes)){ +// return JNIED25519_SIGF.resolvePrivKey(privKeyBytes); +// } +// //遍历非对称加密算法,如果满足,则返回解析结果 +// if (SM2_ENCF.supportPrivKey(privKeyBytes)){ +// return SM2_ENCF.resolvePrivKey(privKeyBytes); +// } +// //否则返回null +// return null; +// } +//} diff --git a/source/crypto/crypto-impl/src/main/java/com/jd/blockchain/crypto/impl/CryptoFactoryImpl.java b/source/crypto/crypto-impl/src/main/java/com/jd/blockchain/crypto/impl/CryptoFactoryImpl.java new file mode 100644 index 00000000..ffd35e66 --- /dev/null +++ b/source/crypto/crypto-impl/src/main/java/com/jd/blockchain/crypto/impl/CryptoFactoryImpl.java @@ -0,0 +1,30 @@ +//package com.jd.blockchain.crypto.impl; +// +//import com.jd.blockchain.crypto.CryptoFactory; +//import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; +//import com.jd.blockchain.crypto.hash.HashCryptography; +//import com.jd.blockchain.crypto.symmetric.SymmetricCryptography; +// +//public class CryptoFactoryImpl implements CryptoFactory { +// +// //Field; +// private static HashCryptography hashCryptography = new HashCryptographyImpl(); +// private static AsymmetricCryptography asymmetricCryptography = new AsymmtricCryptographyImpl(); +// private static SymmetricCryptography symmetricCryptography = new SymmetricCryptographyImpl(); +// +// @Override +// public HashCryptography hashCryptography() { +// return hashCryptography; +// } +// +// @Override +// public AsymmetricCryptography asymmetricCryptography() { +// return asymmetricCryptography; +// } +// +// @Override +// public SymmetricCryptography symmetricCryptography() { +// return symmetricCryptography; +// } +// +//} diff --git a/source/crypto/crypto-impl/src/main/java/com/jd/blockchain/crypto/impl/HashCryptographyImpl.java b/source/crypto/crypto-impl/src/main/java/com/jd/blockchain/crypto/impl/HashCryptographyImpl.java new file mode 100644 index 00000000..59a1defc --- /dev/null +++ b/source/crypto/crypto-impl/src/main/java/com/jd/blockchain/crypto/impl/HashCryptographyImpl.java @@ -0,0 +1,84 @@ +//package com.jd.blockchain.crypto.impl; +// +//import com.jd.blockchain.crypto.CryptoAlgorithm; +//import com.jd.blockchain.crypto.hash.HashCryptography; +//import com.jd.blockchain.crypto.hash.HashDigest; +//import com.jd.blockchain.crypto.hash.HashFunction; +//import com.jd.blockchain.crypto.impl.jni.hash.JNIRIPEMD160HashFunction; +//import com.jd.blockchain.crypto.impl.jni.hash.JNISHA256HashFunction; +//import com.jd.blockchain.crypto.impl.sm.hash.SM3HashFunction; +//import com.jd.blockchain.crypto.service.classic.RIPEMD160HashFunction; +//import com.jd.blockchain.crypto.service.classic.SHA256HashFunction; +// +//public class HashCryptographyImpl implements HashCryptography { +// +// private static final HashFunction SHA256_FUNC = new SHA256HashFunction(); +// private static final HashFunction RIPEMD160_FUNC = new RIPEMD160HashFunction(); +// private static final HashFunction SM3_FUNC = new SM3HashFunction(); +// +// private static final HashFunction JNISHA256_FUNC = new JNISHA256HashFunction(); +// private static final HashFunction JNIRIPEMD160_FUNC = new JNIRIPEMD160HashFunction(); +// +// @Override +// public HashFunction getFunction(CryptoAlgorithm algorithm) { +// +// // 遍历哈希算法,如果满足,则返回实例 +// switch (algorithm) { +// case SHA256: +// return SHA256_FUNC; +// case RIPEMD160: +// return RIPEMD160_FUNC; +// case SM3: +// return SM3_FUNC; +// case JNISHA256: +// return JNISHA256_FUNC; +// case JNIRIPEMD160: +// return JNIRIPEMD160_FUNC; +// default: +// break; +// } +// throw new IllegalArgumentException("The specified algorithm is not hash algorithm!"); +// } +// +// @Override +// public boolean verify(byte[] digestBytes, byte[] data) { +// HashDigest hashDigest = resolveHashDigest(digestBytes); +// return verify(hashDigest,data); +// } +// +// @Override +// public boolean verify(HashDigest digest, byte[] data) { +// CryptoAlgorithm algorithm = digest.getAlgorithm(); +// return getFunction(algorithm).verify(digest, data); +// } +// +// @Override +// public HashDigest resolveHashDigest(byte[] digestBytes) { +// HashDigest hashDigest = tryResolveHashDigest(digestBytes); +// if (hashDigest == null) +// throw new IllegalArgumentException("This digestBytes cannot be resolved!"); +// else return hashDigest; +// } +// +// @Override +// public HashDigest tryResolveHashDigest(byte[] digestBytes) { +// //遍历哈希函数,如果满足,则返回解析结果 +// if (SHA256_FUNC.supportHashDigest(digestBytes)) { +// return SHA256_FUNC.resolveHashDigest(digestBytes); +// } +// if (RIPEMD160_FUNC.supportHashDigest(digestBytes)) { +// return RIPEMD160_FUNC.resolveHashDigest(digestBytes); +// } +// if (SM3_FUNC.supportHashDigest(digestBytes)) { +// return SM3_FUNC.resolveHashDigest(digestBytes); +// } +// if (JNISHA256_FUNC.supportHashDigest(digestBytes)) { +// return JNISHA256_FUNC.resolveHashDigest(digestBytes); +// } +// if (JNIRIPEMD160_FUNC.supportHashDigest(digestBytes)) { +// return JNIRIPEMD160_FUNC.resolveHashDigest(digestBytes); +// } +// //否则返回null +// return null; +// } +//} \ No newline at end of file diff --git a/source/crypto/crypto-impl/src/main/java/com/jd/blockchain/crypto/impl/SymmetricCryptographyImpl.java b/source/crypto/crypto-impl/src/main/java/com/jd/blockchain/crypto/impl/SymmetricCryptographyImpl.java new file mode 100644 index 00000000..115855d0 --- /dev/null +++ b/source/crypto/crypto-impl/src/main/java/com/jd/blockchain/crypto/impl/SymmetricCryptographyImpl.java @@ -0,0 +1,101 @@ +//package com.jd.blockchain.crypto.impl; +// +//import com.jd.blockchain.crypto.Ciphertext; +//import com.jd.blockchain.crypto.CryptoAlgorithm; +//import com.jd.blockchain.crypto.SingleKey; +//import com.jd.blockchain.crypto.impl.sm.symmetric.SM4SymmetricEncryptionFunction; +//import com.jd.blockchain.crypto.service.classic.AESSymmetricEncryptionFunction; +//import com.jd.blockchain.crypto.symmetric.SymmetricCryptography; +//import com.jd.blockchain.crypto.symmetric.SymmetricEncryptionFunction; +// +//public class SymmetricCryptographyImpl implements SymmetricCryptography { +// +// private static final SymmetricEncryptionFunction AES_ENCF = new AESSymmetricEncryptionFunction(); +// private static final SymmetricEncryptionFunction SM4_ENCF = new SM4SymmetricEncryptionFunction(); +// +// /** +// * 封装了对称密码算法对应的密钥生成算法 +// */ +// @Override +// public SingleKey generateKey(CryptoAlgorithm algorithm) { +// +// //验证算法标识是对称加密算法,并根据算法生成对称密钥,否则抛出异常 +// if (algorithm.isEncryptable() && algorithm.isSymmetric() ){ +// return (SingleKey) getSymmetricEncryptionFunction(algorithm).generateSymmetricKey(); +// } +// else throw new IllegalArgumentException("The specified algorithm is not symmetric encryption algorithm!"); +// } +// +// @Override +// public SymmetricEncryptionFunction getSymmetricEncryptionFunction(CryptoAlgorithm algorithm) { +// +// // 遍历对称加密算法,如果满足,则返回实例 +// switch (algorithm) { +// case AES: +// return AES_ENCF; +// case SM4: +// return SM4_ENCF; +// default: +// break; +// } +// throw new IllegalArgumentException("The specified algorithm is not symmetric encryption algorithm!"); +// } +// +// @Override +// public byte[] decrypt(byte[] symmetricKeyBytes, byte[] ciphertextBytes) { +// +// //分别得到SymmetricKey和Ciphertext类型的密钥和密文,以及symmetricKey对应的算法 +// SingleKey symmetricKey = resolveSymmetricKey(symmetricKeyBytes); +// Ciphertext ciphertext = resolveCiphertext(ciphertextBytes); +// CryptoAlgorithm algorithm = symmetricKey.getAlgorithm(); +// +// //验证两个输入中算法标识一致,否则抛出异常 +// if (algorithm != ciphertext.getAlgorithm()) +// throw new IllegalArgumentException("Ciphertext's algorithm and key's are not matching!"); +// +// //根据算法标识,调用对应算法实例来计算返回明文 +// return getSymmetricEncryptionFunction(algorithm).decrypt(symmetricKey,ciphertext); +// } +// +// @Override +// public Ciphertext resolveCiphertext(byte[] ciphertextBytes) { +// Ciphertext ciphertext = tryResolveCiphertext(ciphertextBytes); +// if (ciphertext == null) +// throw new IllegalArgumentException("This ciphertextBytes cannot be resolved!"); +// else return ciphertext; +// } +// +// @Override +// public Ciphertext tryResolveCiphertext(byte[] ciphertextBytes) { +// //遍历对称加密算法,如果满足,则返回解析结果 +// if (AES_ENCF.supportCiphertext(ciphertextBytes)) { +// return AES_ENCF.resolveCiphertext(ciphertextBytes); +// } +// if (SM4_ENCF.supportCiphertext(ciphertextBytes)) { +// return SM4_ENCF.resolveCiphertext(ciphertextBytes); +// } +// //否则返回null +// return null; +// } +// +// @Override +// public SingleKey resolveSymmetricKey(byte[] symmetricKeyBytes) { +// SingleKey symmetricKey = tryResolveSymmetricKey(symmetricKeyBytes); +// if (symmetricKey == null) +// throw new IllegalArgumentException("This symmetricKeyBytes cannot be resolved!"); +// else return symmetricKey; +// } +// +// @Override +// public SingleKey tryResolveSymmetricKey(byte[] symmetricKeyBytes) { +// //遍历对称加密算法,如果满足,则返回解析结果 +// if(AES_ENCF.supportSymmetricKey(symmetricKeyBytes)) { +// return AES_ENCF.resolveSymmetricKey(symmetricKeyBytes); +// } +// if(SM4_ENCF.supportSymmetricKey(symmetricKeyBytes)) { +// return SM4_ENCF.resolveSymmetricKey(symmetricKeyBytes); +// } +// //否则返回null +// return null; +// } +//} diff --git a/source/crypto/crypto-impl/src/test/java/test/com/jd/blockchain/crypto/performance/MyAsymmetricEncryptionTest.java b/source/crypto/crypto-impl/src/test/java/test/com/jd/blockchain/crypto/performance/MyAsymmetricEncryptionTest.java new file mode 100644 index 00000000..87ff496f --- /dev/null +++ b/source/crypto/crypto-impl/src/test/java/test/com/jd/blockchain/crypto/performance/MyAsymmetricEncryptionTest.java @@ -0,0 +1,55 @@ +//package test.com.jd.blockchain.crypto.performance; +// +//import com.jd.blockchain.crypto.Ciphertext; +//import com.jd.blockchain.crypto.PrivKey; +//import com.jd.blockchain.crypto.PubKey; +//import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; +//import com.jd.blockchain.crypto.impl.sm.asymmetric.SM2CryptoFunction; +//import org.bouncycastle.util.encoders.Hex; +// +//public class MyAsymmetricEncryptionTest { +// +// public static void main(String[] args) { +// +// String string1K = "0123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba9876543210"; +// String string1M = ""; +// for (int i = 0; i < 1024 ; i++) +// { +// string1M = string1M + string1K; +// } +// +// byte[] data1K = Hex.decode(string1K); +// byte[] data1M = Hex.decode(string1M); +// int count = 10000; +// +// SM2CryptoFunction sm2 = new SM2CryptoFunction(); +// CryptoKeyPair keyPairSM2 = sm2.generateKeyPair(); +// PrivKey privKeySM2 = keyPairSM2.getPrivKey(); +// PubKey pubKeySM2 = keyPairSM2.getPubKey(); +// +// System.out.println("=================== do SM2 encrypt test ==================="); +// Ciphertext ciphertextSM2 = null; +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// ciphertextSM2 = sm2.encrypt(pubKeySM2,data1K); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SM2 Encrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// System.out.println("=================== do SM2 decrypt test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// sm2.decrypt(privKeySM2,ciphertextSM2); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SM2 Decrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// } +//} diff --git a/source/crypto/crypto-impl/src/test/java/test/com/jd/blockchain/crypto/performance/MyHashTest.java b/source/crypto/crypto-impl/src/test/java/test/com/jd/blockchain/crypto/performance/MyHashTest.java new file mode 100644 index 00000000..dfa922fc --- /dev/null +++ b/source/crypto/crypto-impl/src/test/java/test/com/jd/blockchain/crypto/performance/MyHashTest.java @@ -0,0 +1,62 @@ +//package test.com.jd.blockchain.crypto.performance; +// +//import com.jd.blockchain.crypto.impl.sm.hash.SM3HashFunction; +//import com.jd.blockchain.crypto.service.classic.RIPEMD160HashFunction; +//import com.jd.blockchain.crypto.service.classic.SHA256HashFunction; +// +//import java.util.Random; +// +//public class MyHashTest { +// +// public static void main(String[] args) { +// +// Random rand = new Random(); +// byte[] data1K = new byte[1024]; +// rand.nextBytes(data1K); +// int count = 1000000; +// +// SHA256HashFunction sha256hf = new SHA256HashFunction(); +// +// System.out.println("=================== do SHA256 hash test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// sha256hf.hash(data1K); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SHA256 hashing Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// RIPEMD160HashFunction ripemd160hf = new RIPEMD160HashFunction(); +// +// System.out.println("=================== do RIPEMD160 hash test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// ripemd160hf.hash(data1K); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("RIPEMD160 hashing Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// SM3HashFunction sm3hf = new SM3HashFunction(); +// +// System.out.println("=================== do SM3 hash test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// sm3hf.hash(data1K); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SM3 hashing Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// } +//} +// diff --git a/source/crypto/crypto-impl/src/test/java/test/com/jd/blockchain/crypto/performance/MySignatureTest.java b/source/crypto/crypto-impl/src/test/java/test/com/jd/blockchain/crypto/performance/MySignatureTest.java new file mode 100644 index 00000000..684ecdb6 --- /dev/null +++ b/source/crypto/crypto-impl/src/test/java/test/com/jd/blockchain/crypto/performance/MySignatureTest.java @@ -0,0 +1,83 @@ +//package test.com.jd.blockchain.crypto.performance; +// +//import com.jd.blockchain.crypto.PrivKey; +//import com.jd.blockchain.crypto.PubKey; +//import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; +//import com.jd.blockchain.crypto.asymmetric.SignatureDigest; +//import com.jd.blockchain.crypto.impl.sm.asymmetric.SM2CryptoFunction; +//import com.jd.blockchain.crypto.service.classic.ED25519SignatureFunction; +// +//import java.util.Random; +// +//public class MySignatureTest { +// +// public static void main(String[] args) { +// +// Random rand = new Random(); +// byte[] data = new byte[64]; +// rand.nextBytes(data); +// int count = 10000; +// +// ED25519SignatureFunction ed25519sf = new ED25519SignatureFunction(); +// CryptoKeyPair keyPairED25519 = ed25519sf.generateKeyPair(); +// PrivKey privKeyED25519 = keyPairED25519.getPrivKey(); +// PubKey pubKeyED25519 = keyPairED25519.getPubKey(); +// +// System.out.println("=================== do ED25519 sign test ==================="); +// SignatureDigest signatureDigestED25519 = null; +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// signatureDigestED25519 = ed25519sf.sign(privKeyED25519,data); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("ED25519 Signing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// System.out.println("=================== do ED25519 verify test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// ed25519sf.verify(signatureDigestED25519,pubKeyED25519,data); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("ED25519 Verifying Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// SM2CryptoFunction sm2 = new SM2CryptoFunction(); +// CryptoKeyPair keyPairSM2 = sm2.generateKeyPair(); +// PrivKey privKeySM2 = keyPairSM2.getPrivKey(); +// PubKey pubKeySM2 = keyPairSM2.getPubKey(); +// +// +// System.out.println("=================== do SM2 sign test ==================="); +// SignatureDigest signatureDigestSM2 = null; +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// signatureDigestSM2 = sm2.sign(privKeySM2,data); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SM2 Signing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// System.out.println("=================== do SM2 verify test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// sm2.verify(signatureDigestSM2,pubKeySM2,data); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SM2 Verifying Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// } +//} diff --git a/source/crypto/crypto-impl/src/test/java/test/com/jd/blockchain/crypto/performance/MySymmetricEncryptionTest.java b/source/crypto/crypto-impl/src/test/java/test/com/jd/blockchain/crypto/performance/MySymmetricEncryptionTest.java new file mode 100644 index 00000000..fbab4b13 --- /dev/null +++ b/source/crypto/crypto-impl/src/test/java/test/com/jd/blockchain/crypto/performance/MySymmetricEncryptionTest.java @@ -0,0 +1,92 @@ +//package test.com.jd.blockchain.crypto.performance; +// +//import com.jd.blockchain.crypto.Ciphertext; +//import com.jd.blockchain.crypto.SingleKey; +//import com.jd.blockchain.crypto.impl.sm.symmetric.SM4SymmetricEncryptionFunction; +//import com.jd.blockchain.crypto.service.classic.AESSymmetricEncryptionFunction; +// +//import org.bouncycastle.util.encoders.Hex; +// +//public class MySymmetricEncryptionTest { +// +// public static void main(String[] args) { +// +// String string1K = "0123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba9876543210"; +// +//// String string1M = ""; +//// for (int i = 0; i < 1024 ; i++) +//// { +//// string1M = string1M + string1K; +//// } +// +// byte[] data1K = Hex.decode(string1K); +//// byte[] data1M = Hex.decode(string1M); +// +// int count = 100000; +// +// +// AESSymmetricEncryptionFunction aes = new AESSymmetricEncryptionFunction(); +// SingleKey keyAES = (SingleKey) aes.generateSymmetricKey(); +// Ciphertext ciphertext1KAES = null; +// Ciphertext ciphertext1MAES = null; +// +// System.out.println("=================== do AES encrypt test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// ciphertext1KAES = aes.encrypt(keyAES,data1K); +//// ciphertext1MAES = aes.encrypt(keyAES,data1M); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("AES Encrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// +// +// System.out.println("=================== do AES decrypt test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// aes.decrypt(keyAES,ciphertext1KAES); +//// aes.decrypt(keyAES,ciphertext1MAES); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("AES Decrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// SM4SymmetricEncryptionFunction sm4 = new SM4SymmetricEncryptionFunction(); +// SingleKey keySM4 = (SingleKey) sm4.generateSymmetricKey(); +// Ciphertext ciphertext1KSM4 = null; +// Ciphertext ciphertext1MSM4 = null; +// +// System.out.println("=================== do SM4 encrypt test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// ciphertext1KSM4 = sm4.encrypt(keySM4,data1K); +//// ciphertext1MSM4 =sm4.encrypt(keySM4,data1M); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SM4 Encrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// System.out.println("=================== do SM4 decrypt test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// sm4.decrypt(keySM4,ciphertext1KSM4); +//// sm4.decrypt(keySM4,ciphertext1MSM4); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SM4 Decrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// } +//} diff --git a/source/crypto/crypto-sm/pom.xml b/source/crypto/crypto-sm/pom.xml new file mode 100644 index 00000000..607c7360 --- /dev/null +++ b/source/crypto/crypto-sm/pom.xml @@ -0,0 +1,20 @@ + + 4.0.0 + + com.jd.blockchain + crypto + 0.9.0-SNAPSHOT + + crypto-sm + + + + com.jd.blockchain + crypto-framework + ${project.version} + + + + \ No newline at end of file diff --git a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM2CryptoFunction.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM2CryptoFunction.java new file mode 100644 index 00000000..2c2c1fb2 --- /dev/null +++ b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM2CryptoFunction.java @@ -0,0 +1,212 @@ +package com.jd.blockchain.crypto.service.sm; + +import static com.jd.blockchain.crypto.BaseCryptoKey.KEY_TYPE_BYTES; +import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; +import static com.jd.blockchain.crypto.CryptoKeyType.PRIV_KEY; +import static com.jd.blockchain.crypto.CryptoKeyType.PUB_KEY; + +import com.jd.blockchain.crypto.*; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.params.ECPrivateKeyParameters; +import org.bouncycastle.crypto.params.ECPublicKeyParameters; + +import com.jd.blockchain.crypto.asymmetric.AsymmetricCiphertext; +import com.jd.blockchain.crypto.asymmetric.AsymmetricEncryptionFunction; +import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; +import com.jd.blockchain.crypto.asymmetric.SignatureDigest; +import com.jd.blockchain.crypto.asymmetric.SignatureFunction; +import com.jd.blockchain.crypto.utils.sm.SM2Utils; + +public class SM2CryptoFunction implements AsymmetricEncryptionFunction, SignatureFunction { + + private static final CryptoAlgorithm SM2 = SMCryptoService.SM2_ALGORITHM; + + private static final int ECPOINT_SIZE = 65; + private static final int PRIVKEY_SIZE = 32; + private static final int SIGNATUREDIGEST_SIZE = 64; + private static final int HASHDIGEST_SIZE = 32; + + private static final int PUBKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + ECPOINT_SIZE; + private static final int PRIVKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + PRIVKEY_SIZE; + private static final int SIGNATUREDIGEST_LENGTH = ALGORYTHM_CODE_SIZE + SIGNATUREDIGEST_SIZE; + + SM2CryptoFunction() { + } + + @Override + public Ciphertext encrypt(PubKey pubKey, byte[] data) { + + byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); + + // 验证原始公钥长度为65字节 + if (rawPubKeyBytes.length != ECPOINT_SIZE) { + throw new CryptoException("This key has wrong format!"); + } + + // 验证密钥数据的算法标识对应SM2算法 + if (pubKey.getAlgorithm().code() != SM2.code()) { + throw new CryptoException("The is not sm2 public key!"); + } + + // 调用SM2加密算法计算密文 + return new AsymmetricCiphertext(SM2, SM2Utils.encrypt(data, rawPubKeyBytes)); + } + + @Override + public byte[] decrypt(PrivKey privKey, Ciphertext ciphertext) { + + byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); + byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); + + // 验证原始私钥长度为32字节 + if (rawPrivKeyBytes.length != PRIVKEY_SIZE) { + throw new CryptoException("This key has wrong format!"); + } + + // 验证密钥数据的算法标识对应SM2算法 + if (privKey.getAlgorithm().code() != SM2.code()) { + throw new CryptoException("This key is not SM2 private key!"); + } + + // 验证密文数据的算法标识对应SM2签名算法,并且原始摘要长度为64字节 + if (ciphertext.getAlgorithm().code() != SM2.code() + || rawCiphertextBytes.length < ECPOINT_SIZE + HASHDIGEST_SIZE) { + throw new CryptoException("This is not SM2 ciphertext!"); + } + + // 调用SM2解密算法得到明文结果 + return SM2Utils.decrypt(rawCiphertextBytes, rawPrivKeyBytes); + } + + @Override + public byte[] retrievePubKeyBytes(byte[] privKeyBytes) { + + byte[] rawPrivKeyBytes = resolvePrivKey(privKeyBytes).getRawKeyBytes(); + byte[] rawPubKeyBytes = SM2Utils.retrievePublicKey(rawPrivKeyBytes); + return new PubKey(SM2, rawPubKeyBytes).toBytes(); + } + + @Override + public boolean supportPrivKey(byte[] privKeyBytes) { + // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,密钥数据的算法标识对应SM2算法,并且密钥类型是私钥 + return privKeyBytes.length == PRIVKEY_LENGTH && CryptoAlgorithm.match(SM2, privKeyBytes) + && privKeyBytes[ALGORYTHM_CODE_SIZE] == PRIV_KEY.CODE; + } + + @Override + public PrivKey resolvePrivKey(byte[] privKeyBytes) { + // 由框架调用 support 方法检查有效性,在此不做重复检查; + return new PrivKey(privKeyBytes); + } + + @Override + public boolean supportPubKey(byte[] pubKeyBytes) { + // 验证输入字节数组长度=算法标识长度+密钥类型长度+椭圆曲线点长度,密钥数据的算法标识对应SM2算法,并且密钥类型是公钥 + return pubKeyBytes.length == PUBKEY_LENGTH && CryptoAlgorithm.match(SM2, pubKeyBytes) + && pubKeyBytes[ALGORYTHM_CODE_SIZE] == PUB_KEY.CODE; + } + + @Override + public PubKey resolvePubKey(byte[] pubKeyBytes) { + // 由框架调用 support 方法检查有效性,在此不做重复检查; + return new PubKey(pubKeyBytes); + } + + @Override + public boolean supportCiphertext(byte[] ciphertextBytes) { + // 验证输入字节数组长度>=算法标识长度+椭圆曲线点长度+哈希长度,字节数组的算法标识对应SM2算法 + return ciphertextBytes.length >= ALGORYTHM_CODE_SIZE + ECPOINT_SIZE + HASHDIGEST_SIZE + && CryptoAlgorithm.match(SM2, ciphertextBytes); + } + + @Override + public AsymmetricCiphertext resolveCiphertext(byte[] ciphertextBytes) { + // 由框架调用 support 方法检查有效性,在此不做重复检查; + return new AsymmetricCiphertext(ciphertextBytes); + } + + @Override + public SignatureDigest sign(PrivKey privKey, byte[] data) { + + byte[] rawPrivKeyBytes = privKey.getRawKeyBytes(); + + // 验证原始私钥长度为256比特,即32字节 + if (rawPrivKeyBytes.length != PRIVKEY_SIZE) { + throw new CryptoException("This key has wrong format!"); + } + + // 验证密钥数据的算法标识对应SM2签名算法 + if (privKey.getAlgorithm().code() != SM2.code()) { + throw new CryptoException("This key is not SM2 private key!"); + } + + // 调用SM2签名算法计算签名结果 + return new SignatureDigest(SM2, SM2Utils.sign(data, rawPrivKeyBytes)); + } + + @Override + public boolean verify(SignatureDigest digest, PubKey pubKey, byte[] data) { + + byte[] rawPubKeyBytes = pubKey.getRawKeyBytes(); + byte[] rawDigestBytes = digest.getRawDigest(); + + // 验证原始公钥长度为520比特,即65字节 + if (rawPubKeyBytes.length != ECPOINT_SIZE) { + throw new CryptoException("This key has wrong format!"); + } + + // 验证密钥数据的算法标识对应SM2签名算法 + if (pubKey.getAlgorithm().code() != SM2.code()) { + throw new CryptoException("This key is not SM2 public key!"); + } + + // 验证签名数据的算法标识对应SM2签名算法,并且原始签名长度为64字节 + if (digest.getAlgorithm().code() != SM2.code() || rawDigestBytes.length != SIGNATUREDIGEST_SIZE) { + throw new CryptoException("This is not SM2 signature digest!"); + } + + // 调用SM2验签算法验证签名结果 + return SM2Utils.verify(data, rawPubKeyBytes, rawDigestBytes); + } + + @Override + public boolean supportDigest(byte[] digestBytes) { + // 验证输入字节数组长度=算法标识长度+签名长度,字节数组的算法标识对应SM2算法 + return digestBytes.length == SIGNATUREDIGEST_LENGTH && CryptoAlgorithm.match(SM2, digestBytes); + } + + @Override + public SignatureDigest resolveDigest(byte[] digestBytes) { + // 由框架调用 support 方法检查有效性,在此不做重复检查; + return new SignatureDigest(digestBytes); + } + + @Override + public CryptoAlgorithm getAlgorithm() { + return SM2; + } + + @Override + public CryptoKeyPair generateKeyPair() { + + // 调用SM2算法的密钥生成算法生成公私钥对priKey和pubKey,返回密钥对 + AsymmetricCipherKeyPair keyPair = SM2Utils.generateKeyPair(); + ECPrivateKeyParameters ecPriv = (ECPrivateKeyParameters) keyPair.getPrivate(); + ECPublicKeyParameters ecPub = (ECPublicKeyParameters) keyPair.getPublic(); + + byte[] privKeyBytesD = ecPriv.getD().toByteArray(); + byte[] privKeyBytes = new byte[PRIVKEY_SIZE]; + if (privKeyBytesD.length > PRIVKEY_SIZE) { + System.arraycopy(privKeyBytesD, privKeyBytesD.length - PRIVKEY_SIZE, + privKeyBytes, 0, PRIVKEY_SIZE); + } + else { + System.arraycopy(privKeyBytesD, 0, + privKeyBytes, PRIVKEY_SIZE - privKeyBytesD.length, privKeyBytesD.length); + } + + byte[] pubKeyBytes = ecPub.getQ().getEncoded(false); + + return new CryptoKeyPair(new PubKey(SM2, pubKeyBytes), new PrivKey(SM2, privKeyBytes)); + } +} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/sm/hash/SM3HashFunction.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM3HashFunction.java similarity index 66% rename from source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/sm/hash/SM3HashFunction.java rename to source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM3HashFunction.java index 98f9a487..b79a0f07 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/impl/sm/hash/SM3HashFunction.java +++ b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM3HashFunction.java @@ -1,20 +1,24 @@ -package com.jd.blockchain.crypto.impl.sm.hash; +package com.jd.blockchain.crypto.service.sm; + +import java.util.Arrays; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoBytes; +import com.jd.blockchain.crypto.CryptoException; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.crypto.hash.HashFunction; -import com.jd.blockchain.crypto.smutils.hash.SM3Utils; - -import java.util.Arrays; - -import static com.jd.blockchain.crypto.CryptoAlgorithm.SM3; +import com.jd.blockchain.crypto.utils.sm.SM3Utils; public class SM3HashFunction implements HashFunction { - private static final int DIGEST_BYTES = 256/8; + private static final CryptoAlgorithm SM3 = SMCryptoService.SM3_ALGORITHM; - private static final int DIGEST_LENGTH = CryptoBytes.ALGORYTHM_BYTES + DIGEST_BYTES; + private static final int DIGEST_BYTES = 256 / 8; + + private static final int DIGEST_LENGTH = CryptoBytes.ALGORYTHM_CODE_SIZE + DIGEST_BYTES; + + SM3HashFunction() { + } @Override public CryptoAlgorithm getAlgorithm() { @@ -23,8 +27,13 @@ public class SM3HashFunction implements HashFunction { @Override public HashDigest hash(byte[] data) { + + if (data == null) { + throw new CryptoException("The input is null!"); + } + byte[] digestBytes = SM3Utils.hash(data); - return new HashDigest(SM3,digestBytes); + return new HashDigest(SM3, digestBytes); } @Override @@ -36,7 +45,7 @@ public class SM3HashFunction implements HashFunction { @Override public boolean supportHashDigest(byte[] digestBytes) { // 验证输入字节数组长度=算法标识长度+摘要长度,以及算法标识; - return SM3.CODE == digestBytes[0] && DIGEST_LENGTH == digestBytes.length; + return CryptoAlgorithm.match(SM3, digestBytes) && DIGEST_LENGTH == digestBytes.length; } @Override diff --git a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM4EncryptionFunction.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM4EncryptionFunction.java new file mode 100644 index 00000000..d4766af5 --- /dev/null +++ b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SM4EncryptionFunction.java @@ -0,0 +1,148 @@ +package com.jd.blockchain.crypto.service.sm; + +import static com.jd.blockchain.crypto.BaseCryptoKey.KEY_TYPE_BYTES; +import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_CODE_SIZE; +import static com.jd.blockchain.crypto.CryptoKeyType.SYMMETRIC_KEY; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import com.jd.blockchain.crypto.*; +import com.jd.blockchain.crypto.symmetric.SymmetricCiphertext; +import com.jd.blockchain.crypto.symmetric.SymmetricEncryptionFunction; +import com.jd.blockchain.crypto.utils.sm.SM4Utils; + +public class SM4EncryptionFunction implements SymmetricEncryptionFunction { + + private static final CryptoAlgorithm SM4 = SMCryptoService.SM4_ALGORITHM; + + private static final int KEY_SIZE = 128 / 8; + private static final int BLOCK_SIZE = 128 / 8; + + private static final int SYMMETRICKEY_LENGTH = ALGORYTHM_CODE_SIZE + KEY_TYPE_BYTES + KEY_SIZE; + + SM4EncryptionFunction() { + } + + @Override + public Ciphertext encrypt(SymmetricKey key, byte[] data) { + + byte[] rawKeyBytes = key.getRawKeyBytes(); + + // 验证原始密钥长度为128比特,即16字节 + if (rawKeyBytes.length != KEY_SIZE) { + throw new CryptoException("This key has wrong format!"); + } + + // 验证密钥数据的算法标识对应SM4算法 + if (key.getAlgorithm().code() != SM4.code()) { + throw new CryptoException("The is not SM4 symmetric key!"); + } + + // 调用底层SM4算法并计算密文数据 + return new SymmetricCiphertext(SM4, SM4Utils.encrypt(data, rawKeyBytes)); + } + + @Override + public void encrypt(SymmetricKey key, InputStream in, OutputStream out) { + + // 读输入流得到明文,加密,密文数据写入输出流 + try { + byte[] sm4Data = new byte[in.available()]; + in.read(sm4Data); + in.close(); + + out.write(encrypt(key, sm4Data).toBytes()); + out.close(); + } catch (IOException e) { + throw new CryptoException(e.getMessage(), e); + } + } + + @Override + public byte[] decrypt(SymmetricKey key, Ciphertext ciphertext) { + + byte[] rawKeyBytes = key.getRawKeyBytes(); + byte[] rawCiphertextBytes = ciphertext.getRawCiphertext(); + + // 验证原始密钥长度为128比特,即16字节 + if (rawKeyBytes.length != KEY_SIZE) { + throw new CryptoException("This key has wrong format!"); + } + + // 验证密钥数据的算法标识对应SM4算法 + if (key.getAlgorithm().code() != SM4.code()) { + throw new CryptoException("The is not SM4 symmetric key!"); + } + + // 验证原始密文长度为分组长度的整数倍 + if (rawCiphertextBytes.length % BLOCK_SIZE != 0) { + throw new CryptoException("This ciphertext has wrong format!"); + } + + // 验证密文数据算法标识对应SM4算法 + if (ciphertext.getAlgorithm().code() != SM4.code()) { + throw new CryptoException("This is not SM4 ciphertext!"); + } + + // 调用底层SM4算法解密,得到明文 + return SM4Utils.decrypt(rawCiphertextBytes, rawKeyBytes); + } + + @Override + public void decrypt(SymmetricKey key, InputStream in, OutputStream out) { + // 读输入流得到密文数据,解密,明文写入输出流 + try { + byte[] sm4Data = new byte[in.available()]; + in.read(sm4Data); + in.close(); + + if (!supportCiphertext(sm4Data)) { + throw new CryptoException("InputStream is not valid SM4 ciphertext!"); + } + + out.write(decrypt(key, resolveCiphertext(sm4Data))); + out.close(); + } catch (IOException e) { + throw new CryptoException(e.getMessage(), e); + } + } + + @Override + public boolean supportSymmetricKey(byte[] symmetricKeyBytes) { + // 验证输入字节数组长度=算法标识长度+密钥类型长度+密钥长度,字节数组的算法标识对应SM4算法且密钥密钥类型是对称密钥 + return symmetricKeyBytes.length == SYMMETRICKEY_LENGTH && CryptoAlgorithm.match(SM4, symmetricKeyBytes) + && symmetricKeyBytes[ALGORYTHM_CODE_SIZE] == SYMMETRIC_KEY.CODE; + } + + @Override + public SymmetricKey resolveSymmetricKey(byte[] symmetricKeyBytes) { + // 由框架调用 support 方法检查有效性,在此不做重复检查; + return new SymmetricKey(symmetricKeyBytes); + } + + @Override + public boolean supportCiphertext(byte[] ciphertextBytes) { + // 验证(输入字节数组长度-算法标识长度)是分组长度的整数倍,字节数组的算法标识对应SM4算法 + return (ciphertextBytes.length - ALGORYTHM_CODE_SIZE) % BLOCK_SIZE == 0 + && CryptoAlgorithm.match(SM4, ciphertextBytes); + } + + @Override + public SymmetricCiphertext resolveCiphertext(byte[] ciphertextBytes) { + // 由框架调用 support 方法检查有效性,在此不做重复检查; + return new SymmetricCiphertext(ciphertextBytes); + } + + @Override + public CryptoAlgorithm getAlgorithm() { + return SM4; + } + + @Override + public CryptoKey generateSymmetricKey() { + // 根据对应的标识和原始密钥生成相应的密钥数据 + return new SymmetricKey(SM4, SM4Utils.generateKey()); + } +} diff --git a/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SMCryptoService.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SMCryptoService.java new file mode 100644 index 00000000..a4579d27 --- /dev/null +++ b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/service/sm/SMCryptoService.java @@ -0,0 +1,47 @@ +package com.jd.blockchain.crypto.service.sm; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoAlgorithmDefinition; +import com.jd.blockchain.crypto.CryptoFunction; +import com.jd.blockchain.crypto.CryptoService; +import com.jd.blockchain.provider.NamedProvider; + +/** + * 国密软实现; + * + * @author huanghaiquan + * + */ +@NamedProvider("SM-SOFTWARE") +public class SMCryptoService implements CryptoService { + + public static final CryptoAlgorithm SM2_ALGORITHM = CryptoAlgorithmDefinition.defineSignature("SM2", + true, (byte) 2); + + public static final CryptoAlgorithm SM3_ALGORITHM = CryptoAlgorithmDefinition.defineHash("SM3", (byte) 3); + + public static final CryptoAlgorithm SM4_ALGORITHM = CryptoAlgorithmDefinition.defineSymmetricEncryption("SM4", + (byte) 4); + + public static final SM2CryptoFunction SM2 = new SM2CryptoFunction(); + public static final SM3HashFunction SM3 = new SM3HashFunction(); + public static final SM4EncryptionFunction SM4 = new SM4EncryptionFunction(); + + private static final Collection FUNCTIONS; + + static { + List funcs = Arrays.asList(SM2, SM3, SM4); + FUNCTIONS = Collections.unmodifiableList(funcs); + } + + @Override + public Collection getFunctions() { + return FUNCTIONS; + } + +} diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/smutils/asymmetric/SM2Utils.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM2Utils.java similarity index 76% rename from source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/smutils/asymmetric/SM2Utils.java rename to source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM2Utils.java index 7be18edf..2e16d553 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/smutils/asymmetric/SM2Utils.java +++ b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM2Utils.java @@ -1,4 +1,4 @@ -package com.jd.blockchain.crypto.smutils.asymmetric; +package com.jd.blockchain.crypto.utils.sm; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Integer; @@ -31,18 +31,18 @@ public class SM2Utils { // The length of sm3 output is 32 bytes private static final int SM3DIGEST_LENGTH = 32; - private static final BigInteger SM2_ECC_P = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16); - private static final BigInteger SM2_ECC_A = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", 16); - private static final BigInteger SM2_ECC_B = new BigInteger("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16); - private static final BigInteger SM2_ECC_N = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16); - private static final BigInteger SM2_ECC_GX = new BigInteger("32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", 16); - private static final BigInteger SM2_ECC_GY = new BigInteger("BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", 16); + private static final BigInteger SM2_P = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16); + private static final BigInteger SM2_A = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", 16); + private static final BigInteger SM2_B = new BigInteger("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16); + private static final BigInteger SM2_N = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16); + private static final BigInteger SM2_GX = new BigInteger("32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", 16); + private static final BigInteger SM2_GY = new BigInteger("BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", 16); // To get the curve from the equation y^2=x^3+ax+b according the coefficient a and b, // with the big prime p, and obtain the generator g and the domain's parameters - private static final ECCurve curve = new ECCurve.Fp(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B); - private static final ECPoint g = curve.createPoint(SM2_ECC_GX, SM2_ECC_GY); - private static final ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N); + private static final ECCurve CURVE = new ECCurve.Fp(SM2_P, SM2_A, SM2_B); + private static final ECPoint G = CURVE.createPoint(SM2_GX, SM2_GY); + private static final ECDomainParameters DOMAIN_PARAMS = new ECDomainParameters(CURVE, G, SM2_N); //-----------------Key Pair Generation Algorithm----------------- @@ -60,7 +60,7 @@ public class SM2Utils { public static AsymmetricCipherKeyPair generateKeyPair(SecureRandom random){ - ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(domainParams,random); + ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(DOMAIN_PARAMS,random); ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator(); // To generate the key pair @@ -71,7 +71,7 @@ public class SM2Utils { public static byte[] retrievePublicKey(byte[] privateKey) { ECMultiplier createBasePointMultiplier = new FixedPointCombMultiplier(); - ECPoint publicKeyPoint = createBasePointMultiplier.multiply(domainParams.getG(), new BigInteger(1,privateKey)).normalize(); + ECPoint publicKeyPoint = createBasePointMultiplier.multiply(DOMAIN_PARAMS.getG(), new BigInteger(1,privateKey)).normalize(); return publicKeyPoint.getEncoded(false); } @@ -89,7 +89,7 @@ public class SM2Utils { public static byte[] sign(byte[] data, byte[] privateKey){ SecureRandom random = new SecureRandom(); - ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(new BigInteger(1,privateKey),domainParams); + ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(new BigInteger(1,privateKey), DOMAIN_PARAMS); CipherParameters param = new ParametersWithRandom(privKey,random); return sign(data,param); @@ -97,13 +97,13 @@ public class SM2Utils { public static byte[] sign(byte[] data, byte[] privateKey, SecureRandom random, String ID){ - ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(new BigInteger(1,privateKey),domainParams); + ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(new BigInteger(1,privateKey), DOMAIN_PARAMS); CipherParameters param = new ParametersWithID(new ParametersWithRandom(privKey,random),ID.getBytes()); return sign(data,param); } - private static byte[] sign(byte[] data, CipherParameters param){ + public static byte[] sign(byte[] data, CipherParameters param){ SM2Signer signer = new SM2Signer(); @@ -142,7 +142,7 @@ public class SM2Utils { public static boolean verify(byte[] data, byte[] publicKey, byte[] signature){ ECPoint pubKeyPoint = resolvePubKeyBytes(publicKey); - ECPublicKeyParameters pubKey = new ECPublicKeyParameters(pubKeyPoint,domainParams); + ECPublicKeyParameters pubKey = new ECPublicKeyParameters(pubKeyPoint, DOMAIN_PARAMS); return verify(data,pubKey,signature); } @@ -150,13 +150,13 @@ public class SM2Utils { public static boolean verify(byte[] data, byte[] publicKey, byte[] signature, String ID){ ECPoint pubKeyPoint = resolvePubKeyBytes(publicKey); - ECPublicKeyParameters pubKey = new ECPublicKeyParameters(pubKeyPoint,domainParams); + ECPublicKeyParameters pubKey = new ECPublicKeyParameters(pubKeyPoint, DOMAIN_PARAMS); ParametersWithID param = new ParametersWithID(pubKey,ID.getBytes()); return verify(data,param,signature); } - private static boolean verify(byte[] data, CipherParameters param, byte[] signature){ + public static boolean verify(byte[] data, CipherParameters param, byte[] signature){ SM2Signer verifier = new SM2Signer(); @@ -199,21 +199,35 @@ public class SM2Utils { public static byte[] encrypt(byte[] plainBytes, byte[] publicKey){ SecureRandom random = new SecureRandom(); + return encrypt(plainBytes,publicKey,random); } public static byte[] encrypt(byte[] plainBytes, byte[] publicKey, SecureRandom random){ ECPoint pubKeyPoint = resolvePubKeyBytes(publicKey); - ECPublicKeyParameters pubKey = new ECPublicKeyParameters(pubKeyPoint,domainParams); + ECPublicKeyParameters pubKey = new ECPublicKeyParameters(pubKeyPoint, DOMAIN_PARAMS); + ParametersWithRandom param = new ParametersWithRandom(pubKey,random); + + return encrypt(plainBytes,param); + } + + public static byte[] encrypt(byte[] plainBytes, ECPublicKeyParameters pubKey){ + + SecureRandom random = new SecureRandom(); ParametersWithRandom param = new ParametersWithRandom(pubKey,random); + return encrypt(plainBytes,param); + } + + public static byte[] encrypt(byte[] plainBytes, CipherParameters param){ + SM2Engine encryptor = new SM2Engine(); // To prepare parameters encryptor.init(true,param); - // To generate the twisted ciphertext c1c2c3. + // To generate the twisted ciphertext c1c2c3. // The latest standard specification indicates that the correct ordering is c1c3c2 byte[] c1c2c3 = new byte[0]; try { @@ -240,19 +254,23 @@ public class SM2Utils { */ public static byte[] decrypt(byte[] cipherBytes, byte[] privateKey){ + ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(new BigInteger(1,privateKey), DOMAIN_PARAMS); - // To get c1c2c3 from ciphertext whose ordering is c1c3c2 - byte[] c1c2c3 = new byte[cipherBytes.length]; - System.arraycopy(cipherBytes,0,c1c2c3,0,POINT_SIZE); - System.arraycopy(cipherBytes,POINT_SIZE,c1c2c3,c1c2c3.length-SM3DIGEST_LENGTH, SM3DIGEST_LENGTH); - System.arraycopy(cipherBytes,SM3DIGEST_LENGTH + POINT_SIZE,c1c2c3,POINT_SIZE,c1c2c3.length-SM3DIGEST_LENGTH-POINT_SIZE); + return decrypt(cipherBytes,privKey); + } - ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(new BigInteger(1,privateKey),domainParams); + public static byte[] decrypt(byte[] cipherBytes, CipherParameters param){ SM2Engine decryptor = new SM2Engine(); // To prepare parameters - decryptor.init(false,privKey); + decryptor.init(false,param); + + // To get c1c2c3 from ciphertext whose ordering is c1c3c2 + byte[] c1c2c3 = new byte[cipherBytes.length]; + System.arraycopy(cipherBytes,0,c1c2c3,0,POINT_SIZE); + System.arraycopy(cipherBytes,POINT_SIZE,c1c2c3,c1c2c3.length-SM3DIGEST_LENGTH, SM3DIGEST_LENGTH); + System.arraycopy(cipherBytes,SM3DIGEST_LENGTH + POINT_SIZE,c1c2c3,POINT_SIZE,c1c2c3.length-SM3DIGEST_LENGTH-POINT_SIZE); // To output the plaintext try { @@ -262,23 +280,29 @@ public class SM2Utils { } } + + // To convert BigInteger to byte[] whose length is 32 private static byte[] BigIntegerTo32Bytes(BigInteger b){ byte[] tmp = b.toByteArray(); byte[] result = new byte[32]; - if (tmp.length > result.length) - System.arraycopy(tmp, tmp.length-result.length, result, 0, result.length); - else System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); + if (tmp.length > result.length) { + System.arraycopy(tmp, tmp.length - result.length, result, 0, result.length); + } + else { + System.arraycopy(tmp,0,result,result.length-tmp.length,tmp.length); + } return result; } // To retrieve the public key point from publicKey in byte array mode private static ECPoint resolvePubKeyBytes(byte[] publicKey){ - return curve.decodePoint(publicKey); + return CURVE.decodePoint(publicKey); } - public static ECCurve getCurve(){return curve;} - public static ECDomainParameters getDomainParams(){return domainParams;} + public static ECCurve getCurve(){return CURVE;} + + public static ECDomainParameters getDomainParams(){return DOMAIN_PARAMS;} } diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/smutils/hash/SM3Utils.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM3Utils.java similarity index 89% rename from source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/smutils/hash/SM3Utils.java rename to source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM3Utils.java index 788247f3..6272a990 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/smutils/hash/SM3Utils.java +++ b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM3Utils.java @@ -1,10 +1,9 @@ -package com.jd.blockchain.crypto.smutils.hash; +package com.jd.blockchain.crypto.utils.sm; import org.bouncycastle.crypto.digests.SM3Digest; public class SM3Utils { - // The length of sm3 output is 32 bytes private static final int SM3DIGEST_LENGTH = 32; @@ -18,8 +17,6 @@ public class SM3Utils { sm3digest.doFinal(result, 0); return result; - } - } diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/smutils/symmetric/SM4Utils.java b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM4Utils.java similarity index 91% rename from source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/smutils/symmetric/SM4Utils.java rename to source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM4Utils.java index b1855a19..63295f49 100644 --- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/smutils/symmetric/SM4Utils.java +++ b/source/crypto/crypto-sm/src/main/java/com/jd/blockchain/crypto/utils/sm/SM4Utils.java @@ -1,4 +1,4 @@ -package com.jd.blockchain.crypto.smutils.symmetric; +package com.jd.blockchain.crypto.utils.sm; import com.jd.blockchain.crypto.CryptoException; import org.bouncycastle.crypto.CipherKeyGenerator; @@ -15,7 +15,7 @@ import java.security.SecureRandom; public class SM4Utils { // SM4 supports 128-bit secret key - private static final int KEY_Length = 128; + private static final int KEY_LENGTH = 128; // One block contains 16 bytes private static final int BLOCK_SIZE = 16; // Initial vector's size is 16 bytes @@ -33,7 +33,7 @@ public class SM4Utils { // To provide secure randomness and key length as input // to prepare generate private key - keyGenerator.init(new KeyGenerationParameters(new SecureRandom(),KEY_Length)); + keyGenerator.init(new KeyGenerationParameters(new SecureRandom(), KEY_LENGTH)); // To generate key return keyGenerator.generateKey(); @@ -53,7 +53,7 @@ public class SM4Utils { // To ensure that plaintext is not null if (plainBytes == null) { - throw new IllegalArgumentException("plaintext is null!"); + throw new CryptoException("plaintext is null!"); } // To get the value padded into input @@ -72,8 +72,9 @@ public class SM4Utils { encryptor.init(true,new ParametersWithIV(new KeyParameter(secretKey),iv)); byte[] output = new byte[plainBytesWithPadding.length + IV_SIZE]; // To encrypt the input_p in CBC mode - for(int i = 0 ; i < plainBytesWithPadding.length/BLOCK_SIZE; i++) - encryptor.processBlock(plainBytesWithPadding, i * BLOCK_SIZE, output, (i+1) * BLOCK_SIZE); + for(int i = 0 ; i < plainBytesWithPadding.length/BLOCK_SIZE; i++) { + encryptor.processBlock(plainBytesWithPadding, i * BLOCK_SIZE, output, (i + 1) * BLOCK_SIZE); + } // The IV locates on the first block of ciphertext System.arraycopy(iv,0,output,0,BLOCK_SIZE); @@ -100,13 +101,13 @@ public class SM4Utils { // To ensure that the ciphertext is not null if (cipherBytes == null) { - throw new IllegalArgumentException("ciphertext is null!"); + throw new CryptoException("ciphertext is null!"); } // To ensure that the ciphertext's length is integral multiples of 16 bytes if ( cipherBytes.length % BLOCK_SIZE != 0 ) { - throw new IllegalArgumentException("ciphertext's length is wrong!"); + throw new CryptoException("ciphertext's length is wrong!"); } byte[] iv = new byte[IV_SIZE]; @@ -117,8 +118,9 @@ public class SM4Utils { decryptor.init(false,new ParametersWithIV(new KeyParameter(secretKey),iv)); byte[] outputWithPadding = new byte[cipherBytes.length-BLOCK_SIZE]; // To decrypt the input in CBC mode - for(int i = 1 ; i < cipherBytes.length/BLOCK_SIZE ; i++) - decryptor.processBlock(cipherBytes, i * BLOCK_SIZE, outputWithPadding, (i-1) * BLOCK_SIZE); + for(int i = 1 ; i < cipherBytes.length/BLOCK_SIZE ; i++) { + decryptor.processBlock(cipherBytes, i * BLOCK_SIZE, outputWithPadding, (i - 1) * BLOCK_SIZE); + } int p = outputWithPadding[outputWithPadding.length-1]; // To ensure that the padding of output_p is valid diff --git a/source/crypto/crypto-sm/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService b/source/crypto/crypto-sm/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService new file mode 100644 index 00000000..e89073b2 --- /dev/null +++ b/source/crypto/crypto-sm/src/main/resources/META-INF/services/com.jd.blockchain.crypto.CryptoService @@ -0,0 +1 @@ +com.jd.blockchain.crypto.service.sm.SMCryptoService \ No newline at end of file diff --git a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/smutils/SM2UtilsTest.java b/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/smutils/SM2UtilsTest.java similarity index 50% rename from source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/smutils/SM2UtilsTest.java rename to source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/smutils/SM2UtilsTest.java index b10f294b..dec8f2f3 100644 --- a/source/crypto/crypto-framework/src/test/java/test/com/jd/blockchain/crypto/smutils/SM2UtilsTest.java +++ b/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/smutils/SM2UtilsTest.java @@ -1,6 +1,13 @@ package test.com.jd.blockchain.crypto.smutils; -import com.jd.blockchain.crypto.smutils.asymmetric.SM2Utils; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.jd.blockchain.utils.security.Ed25519Utils; +import net.i2p.crypto.eddsa.EdDSAPrivateKey; +import net.i2p.crypto.eddsa.EdDSAPublicKey; +import net.i2p.crypto.eddsa.KeyPairGenerator; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.params.ECPrivateKeyParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters; @@ -8,7 +15,11 @@ import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.TestRandomBigInteger; import org.junit.Test; -import static org.junit.Assert.*; +import com.jd.blockchain.crypto.utils.sm.SM2Utils; + +import java.security.KeyPair; +import java.util.Arrays; +import java.util.Random; public class SM2UtilsTest { @@ -114,4 +125,117 @@ public class SM2UtilsTest { byte[] plaintext = SM2Utils.decrypt(ciphertext,privKeyBytes); assertArrayEquals(expectedMessage.getBytes(),plaintext); } +// +// @Test +// public void encryptingPerformace(){ +// +// byte[] data = new byte[1000]; +// Random random = new Random(); +// random.nextBytes(data); +// +// int count = 10000; +// +// byte[] ciphertext = null; +// +// AsymmetricCipherKeyPair keyPair = SM2Utils.generateKeyPair(); +// ECPublicKeyParameters ecPub = (ECPublicKeyParameters) keyPair.getPublic(); +// ECPrivateKeyParameters ecPriv = (ECPrivateKeyParameters) keyPair.getPrivate(); +// +// System.out.println("=================== do SM2 encrypt test ==================="); +// +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// ciphertext = SM2Utils.encrypt(data,ecPub); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SM2 Encrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// System.out.println("=================== do SM2 decrypt test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// SM2Utils.decrypt(ciphertext,ecPriv); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SM2 Decrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// } +// +// +// @Test +// public void signingPerformace(){ +// +// byte[] data = new byte[1000]; +// Random random = new Random(); +// random.nextBytes(data); +// +// int count = 10000; +// +// byte[] sm2Digest = null; +// byte[] ed25519Digest = null; +// +// AsymmetricCipherKeyPair keyPair = SM2Utils.generateKeyPair(); +// ECPublicKeyParameters ecPub = (ECPublicKeyParameters) keyPair.getPublic(); +// ECPrivateKeyParameters ecPriv = (ECPrivateKeyParameters) keyPair.getPrivate(); +// +// System.out.println("=================== do SM2 sign test ==================="); +// +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// sm2Digest = SM2Utils.sign(data,ecPriv); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SM2 Signing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// System.out.println("=================== do SM2 verify test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// SM2Utils.verify(data,ecPub,sm2Digest); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SM2 Verifying Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// KeyPairGenerator keyPairGenerator = new KeyPairGenerator(); +// KeyPair ed25519KeyPair = keyPairGenerator.generateKeyPair(); +// EdDSAPrivateKey privKey = (EdDSAPrivateKey) ed25519KeyPair.getPrivate(); +// EdDSAPublicKey pubKey = (EdDSAPublicKey) ed25519KeyPair.getPublic(); +// +// System.out.println("=================== do ED25519 sign test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// ed25519Digest = Ed25519Utils.sign_512(data,privKey.getSeed()); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("ED25519 Signing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// System.out.println("=================== do ED25519 verify test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// Ed25519Utils.verify(data,pubKey.getAbyte(),ed25519Digest); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("ED25519 Verifying Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// } } \ No newline at end of file diff --git a/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/smutils/SM3UtilsTest.java b/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/smutils/SM3UtilsTest.java new file mode 100644 index 00000000..8b155edf --- /dev/null +++ b/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/smutils/SM3UtilsTest.java @@ -0,0 +1,71 @@ +package test.com.jd.blockchain.crypto.smutils; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import com.jd.blockchain.utils.security.ShaUtils; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Test; + +import com.jd.blockchain.crypto.utils.sm.SM3Utils; + +import java.util.Random; + +public class SM3UtilsTest { + + private static final int SM3DIGEST_LENGTH = 32; + + @Test + public void testHash() { + + String testString1 = "abc"; + String testString2 = "abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd"; + String expectedResult1="66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0" ; + String expectedResult2="debe9ff92275b8a138604889c18e5a4d6fdb70e5387e5765293dcba39c0c5732"; + + byte[] testString1Bytes = testString1.getBytes(); + byte[] testString2Bytes = testString2.getBytes(); + byte[] hash1 = SM3Utils.hash(testString1Bytes); + byte[] hash2 = SM3Utils.hash(testString2Bytes); + byte[] expectedResult1Bytes = expectedResult1.getBytes(); + byte[] expectedResult2Bytes = expectedResult2.getBytes(); + assertEquals(hash1.length, SM3DIGEST_LENGTH); + assertEquals(hash2.length, SM3DIGEST_LENGTH); + assertArrayEquals(hash1, Hex.decode(expectedResult1Bytes)); + assertArrayEquals(hash2, Hex.decode(expectedResult2Bytes)); + } + +// @Test +// public void hashingPerformance() { +// +// byte[] data = new byte[1000]; +// Random random = new Random(); +// random.nextBytes(data); +// +// int count = 1000000; +// +// System.out.println("=================== do SM3 hash test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// SM3Utils.hash(data); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SM3 hashing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// System.out.println("=================== do SHA256 hash test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// ShaUtils.hash_256(data); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SHA256 hashing Count=%s; Elapsed Times=%s; TPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// } +} \ No newline at end of file diff --git a/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/smutils/SM4UtilsTest.java b/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/smutils/SM4UtilsTest.java new file mode 100644 index 00000000..d37238c6 --- /dev/null +++ b/source/crypto/crypto-sm/src/test/java/test/com/jd/blockchain/crypto/smutils/SM4UtilsTest.java @@ -0,0 +1,137 @@ +package test.com.jd.blockchain.crypto.smutils; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import com.jd.blockchain.utils.security.AESUtils; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Test; + +import com.jd.blockchain.crypto.utils.sm.SM4Utils; + +import java.util.Random; + +public class SM4UtilsTest { + + private static final int KEY_SIZE = 16; + private static final int BLOCK_SIZE = 16; + + @Test + public void testGenerateKey() { + byte[] key = SM4Utils.generateKey(); + assertEquals(KEY_SIZE,key.length); + } + + @Test + public void testEncrypt() { + + String plaintext = "0123456789abcdeffedcba9876543210"; + String key = "0123456789abcdeffedcba9876543210"; + String iv = "00000000000000000000000000000000"; + String expectedCiphertextIn2ndBlock = "681edf34d206965e86b3e94f536e4246"; + + byte[] plaintextBytes = Hex.decode(plaintext); + byte[] keyBytes = Hex.decode(key); + byte[] ivBytes = Hex.decode(iv); + byte[] expectedCiphertextIn2ndBlockBytes = Hex.decode(expectedCiphertextIn2ndBlock); + + + byte[] ciphertextbytes = SM4Utils.encrypt(plaintextBytes,keyBytes,ivBytes); + + assertEquals(BLOCK_SIZE*3,ciphertextbytes.length); + + byte[] ciphertextIn1stBlockBytes = new byte[BLOCK_SIZE]; + System.arraycopy(ciphertextbytes,0,ciphertextIn1stBlockBytes,0,BLOCK_SIZE); + assertArrayEquals(ivBytes,ciphertextIn1stBlockBytes); + + byte[] ciphertextIn2ndBlockBytes = new byte[BLOCK_SIZE]; + System.arraycopy(ciphertextbytes,BLOCK_SIZE,ciphertextIn2ndBlockBytes,0,BLOCK_SIZE); + assertArrayEquals(expectedCiphertextIn2ndBlockBytes,ciphertextIn2ndBlockBytes); + + + } + + @Test + public void testDecrypt() { + + String plaintext = "0123456789abcdeffedcba987654321000112233445566778899"; + String key = "0123456789abcdeffedcba9876543210"; + String iv = "0123456789abcdeffedcba9876543210"; + + byte[] plaintextBytes = Hex.decode(plaintext); + byte[] keyBytes = Hex.decode(key); + byte[] ivBytes = Hex.decode(iv); + + + byte[] ciphertext = SM4Utils.encrypt(plaintextBytes,keyBytes,ivBytes); + byte[] decryptedData = SM4Utils.decrypt(ciphertext,keyBytes); + assertArrayEquals(plaintextBytes,decryptedData); + + } + +// @Test +// public void encryptingPerformance() { +// +// byte[] data = new byte[1000]; +// Random random = new Random(); +// random.nextBytes(data); +// +// byte[] sm4Ciphertext = null; +// byte[] aesCiphertext = null; +// +// int count = 100000; +// +// byte[] sm4Key = SM4Utils.generateKey(); +// +// System.out.println("=================== do SM4 encrypt test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// sm4Ciphertext = SM4Utils.encrypt(data, sm4Key); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SM4 Encrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// System.out.println("=================== do SM4 decrypt test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// SM4Utils.decrypt(sm4Ciphertext, sm4Key); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("SM4 Decrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// byte[] aesKey = AESUtils.generateKey128_Bytes(); +// +// System.out.println("=================== do AES encrypt test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// aesCiphertext = AESUtils.encrypt(data, aesKey); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("AES Encrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// +// +// System.out.println("=================== do AES decrypt test ==================="); +// for (int r = 0; r < 5; r++) { +// System.out.println("------------- round[" + r + "] --------------"); +// long startTS = System.currentTimeMillis(); +// for (int i = 0; i < count; i++) { +// AESUtils.decrypt(aesCiphertext, aesKey); +// } +// long elapsedTS = System.currentTimeMillis() - startTS; +// System.out.println(String.format("AES Decrypting Count=%s; Elapsed Times=%s; KBPS=%.2f", count, elapsedTS, +// (count * 1000.00D) / elapsedTS)); +// } +// } +} \ No newline at end of file diff --git a/source/crypto/pom.xml b/source/crypto/pom.xml index 807125a1..d0ee654b 100644 --- a/source/crypto/pom.xml +++ b/source/crypto/pom.xml @@ -9,10 +9,13 @@ crypto pom - + crypto-framework + crypto-classic + crypto-sm + crypto-jni-clib crypto-adv - + \ No newline at end of file diff --git a/source/deployment/deployment-peer/src/main/java/com/jd/blockchain/boot/peer/PeerBooter.java b/source/deployment/deployment-peer/src/main/java/com/jd/blockchain/boot/peer/PeerBooter.java index d04ada1a..1bde8881 100644 --- a/source/deployment/deployment-peer/src/main/java/com/jd/blockchain/boot/peer/PeerBooter.java +++ b/source/deployment/deployment-peer/src/main/java/com/jd/blockchain/boot/peer/PeerBooter.java @@ -14,7 +14,7 @@ import com.jd.blockchain.runtime.boot.HomeBooter; import com.jd.blockchain.runtime.boot.HomeContext; /** - * Peer starter; + * Peer 启动器; * * @author huanghaiquan * diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayServerBooter.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayServerBooter.java index 34b2df7b..accd6542 100644 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayServerBooter.java +++ b/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayServerBooter.java @@ -11,9 +11,9 @@ import org.springframework.boot.SpringApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.io.ClassPathResource; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.ArgumentSet; import com.jd.blockchain.utils.BaseConstant; diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/BlockBrowserController.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/BlockBrowserController.java index 1c5b1fcb..ae697531 100644 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/BlockBrowserController.java +++ b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/BlockBrowserController.java @@ -1,7 +1,7 @@ package com.jd.blockchain.gateway.web; import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.gateway.PeerService; import com.jd.blockchain.gateway.service.DataRetrievalService; diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebServerConfigurer.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebServerConfigurer.java index ed43d2a7..249bf42f 100644 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebServerConfigurer.java +++ b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebServerConfigurer.java @@ -2,7 +2,7 @@ package com.jd.blockchain.gateway.web; import java.util.List; -import com.jd.blockchain.web.serializes.ByteArrayObjectUtil; +import com.jd.blockchain.utils.io.BytesSlice; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.http.converter.HttpMessageConverter; @@ -11,6 +11,12 @@ import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import com.jd.blockchain.crypto.PubKey; +import com.jd.blockchain.crypto.asymmetric.SignatureDigest; +import com.jd.blockchain.crypto.hash.HashDigest; +import com.jd.blockchain.crypto.serialize.ByteArrayObjectDeserializer; +import com.jd.blockchain.crypto.serialize.ByteArrayObjectSerializer; +import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.io.ByteArray; import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils; import com.jd.blockchain.utils.web.model.JsonWebResponseMessageConverter; @@ -24,6 +30,13 @@ import com.jd.blockchain.web.converters.HashDigestInputConverter; @Configuration public class GatewayWebServerConfigurer implements WebMvcConfigurer { + private static final Class[] BYTEARRAY_JSON_SERIALIZE_CLASS = new Class[] { + HashDigest.class, + PubKey.class, + SignatureDigest.class, + Bytes.class, + BytesSlice.class}; + static { JSONSerializeUtils.disableCircularReferenceDetect(); JSONSerializeUtils.configStringSerializer(ByteArray.class); @@ -66,6 +79,10 @@ public class GatewayWebServerConfigurer implements WebMvcConfigurer { } private void initByteArrayJsonSerialize() { - ByteArrayObjectUtil.init(); + for (Class byteArrayClass : BYTEARRAY_JSON_SERIALIZE_CLASS) { + JSONSerializeUtils.configSerialization(byteArrayClass, + ByteArrayObjectSerializer.getInstance(byteArrayClass), + ByteArrayObjectDeserializer.getInstance(byteArrayClass)); + } } } diff --git a/source/gateway/src/main/resources/application-gw.properties b/source/gateway/src/main/resources/application-gw.properties index b87537f3..e69de29b 100644 --- a/source/gateway/src/main/resources/application-gw.properties +++ b/source/gateway/src/main/resources/application-gw.properties @@ -1 +0,0 @@ -spring.mvc.favicon.enabled=false \ No newline at end of file diff --git a/source/ledger/ledger-core/pom.xml b/source/ledger/ledger-core/pom.xml index f25f8678..65055dd4 100644 --- a/source/ledger/ledger-core/pom.xml +++ b/source/ledger/ledger-core/pom.xml @@ -49,6 +49,20 @@ org.springframework spring-context + + + com.jd.blockchain + crypto-classic + ${project.version} + test + + + com.jd.blockchain + crypto-sm + ${project.version} + test + + diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountAccessPolicy.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountAccessPolicy.java index eb2763d9..2a0202c4 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountAccessPolicy.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountAccessPolicy.java @@ -1,7 +1,7 @@ package com.jd.blockchain.ledger.core; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.AccountHeader; import com.jd.blockchain.utils.Bytes; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountSet.java index 511a939f..5fef84aa 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountSet.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountSet.java @@ -8,7 +8,7 @@ import com.jd.blockchain.binaryproto.DConstructor; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.binaryproto.FieldSetter; import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.AccountHeader; import com.jd.blockchain.ledger.CryptoSetting; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/BaseAccount.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/BaseAccount.java index 5417dc2a..45ec6ec7 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/BaseAccount.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/BaseAccount.java @@ -1,6 +1,6 @@ package com.jd.blockchain.ledger.core; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.AccountHeader; import com.jd.blockchain.ledger.BlockchainIdentity; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccount.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccount.java index bdabb6dc..877949ff 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccount.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccount.java @@ -1,6 +1,6 @@ package com.jd.blockchain.ledger.core; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.AccountHeader; import com.jd.blockchain.utils.Bytes; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccountSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccountSet.java index 612de4b8..8263e0f6 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccountSet.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccountSet.java @@ -1,6 +1,6 @@ package com.jd.blockchain.ledger.core; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.AccountHeader; import com.jd.blockchain.ledger.CryptoSetting; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccount.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccount.java index 2b2271ae..34a2eb43 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccount.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccount.java @@ -1,17 +1,18 @@ package com.jd.blockchain.ledger.core; import com.jd.blockchain.binaryproto.BinaryEncodingUtils; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.AccountHeader; import com.jd.blockchain.ledger.BytesValue; import com.jd.blockchain.ledger.KVDataEntry; import com.jd.blockchain.ledger.KVDataObject; import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.QueryUtil; import com.jd.blockchain.utils.ValueType; +import com.jd.blockchain.utils.serialize.binary.BinarySerializeUtils; public class DataAccount implements AccountHeader, MerkleProvable { + private BaseAccount baseAccount; public DataAccount(BaseAccount accBase) { @@ -118,12 +119,19 @@ public class DataAccount implements AccountHeader, MerkleProvable { */ public KVDataEntry[] getDataEntries(int fromIndex, int count) { + if (getDataEntriesTotalCount() == 0 || count == 0) { return null; } - int pages[] = QueryUtil.calFromIndexAndCount(fromIndex,count,(int)getDataEntriesTotalCount()); - fromIndex = pages[0]; - count = pages[1]; + + if (count == -1 || count > getDataEntriesTotalCount()) { + fromIndex = 0; + count = (int)getDataEntriesTotalCount(); + } + + if (fromIndex < 0 || fromIndex > getDataEntriesTotalCount() - 1) { + fromIndex = 0; + } KVDataEntry[] kvDataEntries = new KVDataEntry[count]; byte[] value; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccountSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccountSet.java index 8d92eb5a..5d318b92 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccountSet.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccountSet.java @@ -1,6 +1,6 @@ package com.jd.blockchain.ledger.core; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.AccountHeader; import com.jd.blockchain.ledger.CryptoSetting; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitDecision.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitDecision.java index 8d3f35b2..b0ad19a1 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitDecision.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitDecision.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger.core; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitPermission.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitPermission.java index 46319be8..70a0f554 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitPermission.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitPermission.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger.core; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.ledger.LedgerInitOperation; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerMetadata.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerMetadata.java index 3655e7b0..5a114533 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerMetadata.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerMetadata.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger.core; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSetting.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSetting.java index 67c503c9..eba16465 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSetting.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSetting.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger.core; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.ledger.CryptoSetting; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantCertData.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantCertData.java index 62b649ce..96d30caf 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantCertData.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantCertData.java @@ -1,6 +1,6 @@ package com.jd.blockchain.ledger.core; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.ParticipantNode; /** diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccount.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccount.java index 6db9fcee..4094c4e0 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccount.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccount.java @@ -1,7 +1,7 @@ package com.jd.blockchain.ledger.core; import com.jd.blockchain.crypto.CryptoUtils; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.UserInfo; import com.jd.blockchain.utils.Bytes; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccountSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccountSet.java index 08364fe7..0cf02380 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccountSet.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccountSet.java @@ -1,6 +1,6 @@ package com.jd.blockchain.ledger.core; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.AccountHeader; import com.jd.blockchain.ledger.CryptoSetting; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerTransactionData.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerTransactionData.java index a76dd68b..3f5e38b2 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerTransactionData.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerTransactionData.java @@ -57,7 +57,6 @@ public class LedgerTransactionData implements LedgerTransaction { this.endpointSignatures = txReq.getEndpointSignatures(); this.nodeSignatures = txReq.getNodeSignatures(); this.executionState = execState; - this.hash = txReq.getHash(); } @Override diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/OpeningAccessPolicy.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/OpeningAccessPolicy.java index bc97dd02..3af84a5a 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/OpeningAccessPolicy.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/OpeningAccessPolicy.java @@ -1,6 +1,6 @@ package com.jd.blockchain.ledger.core.impl; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.AccountHeader; import com.jd.blockchain.ledger.core.AccountAccessPolicy; import com.jd.blockchain.utils.Bytes; diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/AccountSetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/AccountSetTest.java index bd15285b..84fe1441 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/AccountSetTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/AccountSetTest.java @@ -8,6 +8,7 @@ import org.junit.Test; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.hash.HashDigest; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeyPair; import com.jd.blockchain.ledger.core.AccountSet; @@ -26,7 +27,7 @@ public class AccountSetTest { CryptoConfig cryptoConf = new CryptoConfig(); cryptoConf.setAutoVerifyHash(true); - cryptoConf.setHashAlgorithm(CryptoAlgorithm.SHA256); + cryptoConf.setHashAlgorithm(ClassicCryptoService.SHA256_ALGORITHM); String keyPrefix = ""; AccountSet accset = new AccountSet(cryptoConf,keyPrefix, storage, storage, accessPolicy); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/BaseAccountTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/BaseAccountTest.java index acdeff44..7365be93 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/BaseAccountTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/BaseAccountTest.java @@ -7,6 +7,7 @@ import org.junit.Test; import org.springframework.util.StringUtils; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeyPair; import com.jd.blockchain.ledger.core.BaseAccount; @@ -30,7 +31,7 @@ public class BaseAccountTest { CryptoConfig cryptoConf = new CryptoConfig(); cryptoConf.setAutoVerifyHash(true); - cryptoConf.setHashAlgorithm(CryptoAlgorithm.SHA256); + cryptoConf.setHashAlgorithm(ClassicCryptoService.SHA256_ALGORITHM); OpeningAccessPolicy accPlc = new OpeningAccessPolicy(); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerAccountTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerAccountTest.java index 11681165..aac4dd23 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerAccountTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerAccountTest.java @@ -3,8 +3,10 @@ package test.com.jd.blockchain.ledger; import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; +import com.jd.blockchain.crypto.service.sm.SMCryptoService; import com.jd.blockchain.ledger.AccountHeader; import com.jd.blockchain.ledger.ParticipantNode; import com.jd.blockchain.ledger.UserInfo; @@ -44,8 +46,8 @@ public class LedgerAccountTest { @Test public void testSerialize_AccountHeader() { String address = "xxxxxxxxxxxx"; - PubKey pubKey = new PubKey(CryptoAlgorithm.SM2, rawDigestBytes); - HashDigest hashDigest = new HashDigest(CryptoAlgorithm.SHA256, rawDigestBytes); + PubKey pubKey = new PubKey(SMCryptoService.SM2_ALGORITHM, rawDigestBytes); + HashDigest hashDigest = new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, rawDigestBytes); AccountSet.AccountHeaderData accountHeaderData = new AccountSet.AccountHeaderData(Bytes.fromString(address), pubKey, hashDigest); //encode and decode diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerAdminAccountTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerAdminAccountTest.java index bad75327..29423fee 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerAdminAccountTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerAdminAccountTest.java @@ -14,6 +14,7 @@ import org.junit.Test; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.hash.HashDigest; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeyPair; import com.jd.blockchain.ledger.ParticipantNode; @@ -57,7 +58,7 @@ public class LedgerAdminAccountTest { CryptoConfig cryptoSetting = new CryptoConfig(); cryptoSetting.setAutoVerifyHash(true); - cryptoSetting.setHashAlgorithm(CryptoAlgorithm.SHA256); + cryptoSetting.setHashAlgorithm(ClassicCryptoService.SHA256_ALGORITHM); initSetting.setCryptoSetting(cryptoSetting); byte[] ledgerSeed = new byte[16]; diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerBlockImplTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerBlockImplTest.java index d00bcd05..69bef9a3 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerBlockImplTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerBlockImplTest.java @@ -8,18 +8,19 @@ */ package test.com.jd.blockchain.ledger; +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.hash.HashDigest; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.ledger.LedgerBlock; import com.jd.blockchain.ledger.LedgerDataSnapshot; import com.jd.blockchain.ledger.core.impl.LedgerBlockData; import com.jd.blockchain.ledger.core.impl.TransactionStagedSnapshot; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; /** * @@ -37,17 +38,17 @@ public class LedgerBlockImplTest { DataContractRegistry.register(LedgerBlock.class); DataContractRegistry.register(LedgerDataSnapshot.class); long height = 9999L; - HashDigest ledgerHash = new HashDigest(CryptoAlgorithm.SHA256, "zhangsan".getBytes()); - HashDigest previousHash = new HashDigest(CryptoAlgorithm.SHA256, "lisi".getBytes()); + HashDigest ledgerHash = new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "zhangsan".getBytes()); + HashDigest previousHash = new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "lisi".getBytes()); data = new LedgerBlockData(height, ledgerHash, previousHash); - data.setHash(new HashDigest(CryptoAlgorithm.SHA256, "wangwu".getBytes())); - data.setTransactionSetHash(new HashDigest(CryptoAlgorithm.SHA256, "zhaoliu".getBytes())); + data.setHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "wangwu".getBytes())); + data.setTransactionSetHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "zhaoliu".getBytes())); // 设置LedgerDataSnapshot相关属性 - data.setAdminAccountHash(new HashDigest(CryptoAlgorithm.SHA256, "jd1".getBytes())); - data.setDataAccountSetHash(new HashDigest(CryptoAlgorithm.SHA256, "jd2".getBytes())); - data.setUserAccountSetHash(new HashDigest(CryptoAlgorithm.SHA256, "jd3".getBytes())); - data.setContractAccountSetHash(new HashDigest(CryptoAlgorithm.SHA256, "jd4".getBytes())); + data.setAdminAccountHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "jd1".getBytes())); + data.setDataAccountSetHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "jd2".getBytes())); + data.setUserAccountSetHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "jd3".getBytes())); + data.setContractAccountSetHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "jd4".getBytes())); } @@ -88,10 +89,10 @@ public class LedgerBlockImplTest { public void testSerialize_LedgerDataSnapshot() throws Exception { TransactionStagedSnapshot transactionStagedSnapshot = new TransactionStagedSnapshot(); - HashDigest admin = new HashDigest(CryptoAlgorithm.SHA256, "alice".getBytes()); - HashDigest contract = new HashDigest(CryptoAlgorithm.SHA256, "bob".getBytes()); - HashDigest data = new HashDigest(CryptoAlgorithm.SHA256, "jerry".getBytes()); - HashDigest user = new HashDigest(CryptoAlgorithm.SHA256, "tom".getBytes()); + HashDigest admin = new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "alice".getBytes()); + HashDigest contract = new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "bob".getBytes()); + HashDigest data = new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "jerry".getBytes()); + HashDigest user = new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "tom".getBytes()); transactionStagedSnapshot.setAdminAccountHash(admin); transactionStagedSnapshot.setContractAccountSetHash(contract); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerEditerTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerEditerTest.java index f7b94a22..db8647d6 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerEditerTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerEditerTest.java @@ -1,7 +1,9 @@ package test.com.jd.blockchain.ledger; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.core.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import org.junit.Test; @@ -12,7 +14,19 @@ import com.jd.blockchain.crypto.CryptoUtils; import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; import com.jd.blockchain.crypto.asymmetric.SignatureFunction; -import com.jd.blockchain.crypto.impl.AsymmtricCryptographyImpl; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; +import com.jd.blockchain.ledger.BlockchainKeyPair; +import com.jd.blockchain.ledger.LedgerBlock; +import com.jd.blockchain.ledger.LedgerInitSetting; +import com.jd.blockchain.ledger.LedgerTransaction; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.ledger.TransactionState; +import com.jd.blockchain.ledger.core.CryptoConfig; +import com.jd.blockchain.ledger.core.DataAccount; +import com.jd.blockchain.ledger.core.LedgerDataSet; +import com.jd.blockchain.ledger.core.LedgerEditor; +import com.jd.blockchain.ledger.core.LedgerTransactionContext; +import com.jd.blockchain.ledger.core.UserAccount; import com.jd.blockchain.ledger.core.impl.LedgerTransactionalEditor; import com.jd.blockchain.ledger.data.ConsensusParticipantData; import com.jd.blockchain.ledger.data.LedgerInitSettingData; @@ -21,8 +35,6 @@ import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.io.BytesUtils; import com.jd.blockchain.utils.net.NetworkAddress; -import static org.junit.Assert.*; - public class LedgerEditerTest { static { @@ -32,8 +44,9 @@ public class LedgerEditerTest { } String ledgerKeyPrefix = "LDG://"; - AsymmetricCryptography asymmetricCryptography = new AsymmtricCryptographyImpl(); - SignatureFunction signatureFunction = asymmetricCryptography.getSignatureFunction(CryptoAlgorithm.ED25519); + AsymmetricCryptography asymmetricCryptography = CryptoUtils.asymmCrypto(); + SignatureFunction signatureFunction = asymmetricCryptography + .getSignatureFunction(ClassicCryptoService.ED25519_ALGORITHM); // 存储; MemoryKVStorage storage = new MemoryKVStorage(); @@ -100,7 +113,7 @@ public class LedgerEditerTest { private LedgerInitSetting createLedgerInitSetting() { CryptoConfig defCryptoSetting = new CryptoConfig(); defCryptoSetting.setAutoVerifyHash(true); - defCryptoSetting.setHashAlgorithm(CryptoAlgorithm.SHA256); + defCryptoSetting.setHashAlgorithm(ClassicCryptoService.SHA256_ALGORITHM); LedgerInitSettingData initSetting = new LedgerInitSettingData(); @@ -110,7 +123,7 @@ public class LedgerEditerTest { parties[0] = new ConsensusParticipantData(); parties[0].setId(0); parties[0].setName("John"); - CryptoKeyPair kp0 = CryptoUtils.sign(CryptoAlgorithm.ED25519).generateKeyPair(); + CryptoKeyPair kp0 = CryptoUtils.sign(ClassicCryptoService.ED25519_ALGORITHM).generateKeyPair(); parties[0].setPubKey(kp0.getPubKey()); parties[0].setAddress(AddressEncoding.generateAddress(kp0.getPubKey()).toBase58()); parties[0].setHostAddress(new NetworkAddress("192.168.1.6", 9000)); @@ -118,7 +131,7 @@ public class LedgerEditerTest { parties[1] = new ConsensusParticipantData(); parties[1].setId(1); parties[1].setName("John"); - CryptoKeyPair kp1 = CryptoUtils.sign(CryptoAlgorithm.ED25519).generateKeyPair(); + CryptoKeyPair kp1 = CryptoUtils.sign(ClassicCryptoService.ED25519_ALGORITHM).generateKeyPair(); parties[1].setPubKey(kp1.getPubKey()); parties[1].setAddress(AddressEncoding.generateAddress(kp1.getPubKey()).toBase58()); parties[1].setHostAddress(new NetworkAddress("192.168.1.7", 9000)); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerInitOperationTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerInitOperationTest.java index 2a1a363f..9a10158c 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerInitOperationTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerInitOperationTest.java @@ -4,6 +4,7 @@ import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeyPair; import com.jd.blockchain.ledger.LedgerInitOperation; @@ -45,7 +46,7 @@ public class LedgerInitOperationTest { CryptoConfig cryptoConfig = new CryptoConfig(); cryptoConfig.setAutoVerifyHash(true); - cryptoConfig.setHashAlgorithm(CryptoAlgorithm.SHA256); + cryptoConfig.setHashAlgorithm(ClassicCryptoService.SHA256_ALGORITHM); ledgerInitSettingData.setConsensusSettings(new Bytes(csSysSettingBytes)); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerInitSettingTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerInitSettingTest.java index d171e421..a4a56abe 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerInitSettingTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerInitSettingTest.java @@ -4,6 +4,7 @@ import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeyPair; import com.jd.blockchain.ledger.LedgerInitOperation; @@ -43,7 +44,7 @@ public class LedgerInitSettingTest { CryptoConfig cryptoConfig = new CryptoConfig(); cryptoConfig.setAutoVerifyHash(true); - cryptoConfig.setHashAlgorithm(CryptoAlgorithm.SHA256); + cryptoConfig.setHashAlgorithm(ClassicCryptoService.SHA256_ALGORITHM); ledgerInitSettingData.setConsensusSettings(new Bytes(csSysSettingBytes)); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerManagerTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerManagerTest.java index 8ed3e587..102c3319 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerManagerTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerManagerTest.java @@ -20,6 +20,7 @@ import com.jd.blockchain.crypto.CryptoUtils; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; import com.jd.blockchain.crypto.asymmetric.SignatureFunction; import com.jd.blockchain.crypto.hash.HashDigest; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.ledger.BlockBody; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeyPair; @@ -60,7 +61,7 @@ public class LedgerManagerTest { DataContractRegistry.register(BlockBody.class); } - private static SignatureFunction signatureFunction = CryptoUtils.sign(CryptoAlgorithm.ED25519); + private static SignatureFunction signatureFunction = CryptoUtils.sign(ClassicCryptoService.ED25519_ALGORITHM); @Test public void testLedgerInit() { @@ -172,7 +173,7 @@ public class LedgerManagerTest { private LedgerInitSetting createLedgerInitSetting() { CryptoConfig defCryptoSetting = new CryptoConfig(); defCryptoSetting.setAutoVerifyHash(true); - defCryptoSetting.setHashAlgorithm(CryptoAlgorithm.SHA256); + defCryptoSetting.setHashAlgorithm(ClassicCryptoService.SHA256_ALGORITHM); LedgerInitSettingData initSetting = new LedgerInitSettingData(); @@ -182,7 +183,7 @@ public class LedgerManagerTest { parties[0] = new ConsensusParticipantData(); parties[0].setId(0); parties[0].setName("John"); - CryptoKeyPair kp0 = CryptoUtils.sign(CryptoAlgorithm.ED25519).generateKeyPair(); + CryptoKeyPair kp0 = CryptoUtils.sign(ClassicCryptoService.ED25519_ALGORITHM).generateKeyPair(); parties[0].setPubKey(kp0.getPubKey()); parties[0].setAddress(AddressEncoding.generateAddress(kp0.getPubKey()).toBase58()); parties[0].setHostAddress(new NetworkAddress("127.0.0.1", 9000)); @@ -190,7 +191,7 @@ public class LedgerManagerTest { parties[1] = new ConsensusParticipantData(); parties[1].setId(1); parties[1].setName("Mary"); - CryptoKeyPair kp1 = CryptoUtils.sign(CryptoAlgorithm.ED25519).generateKeyPair(); + CryptoKeyPair kp1 = CryptoUtils.sign(ClassicCryptoService.ED25519_ALGORITHM).generateKeyPair(); parties[1].setPubKey(kp1.getPubKey()); parties[1].setAddress(AddressEncoding.generateAddress(kp1.getPubKey()).toBase58()); parties[1].setHostAddress(new NetworkAddress("127.0.0.1", 9010)); @@ -198,7 +199,7 @@ public class LedgerManagerTest { parties[2] = new ConsensusParticipantData(); parties[2].setId(2); parties[2].setName("Jerry"); - CryptoKeyPair kp2 = CryptoUtils.sign(CryptoAlgorithm.ED25519).generateKeyPair(); + CryptoKeyPair kp2 = CryptoUtils.sign(ClassicCryptoService.ED25519_ALGORITHM).generateKeyPair(); parties[2].setPubKey(kp2.getPubKey()); parties[2].setAddress(AddressEncoding.generateAddress(kp2.getPubKey()).toBase58()); parties[2].setHostAddress(new NetworkAddress("127.0.0.1", 9020)); @@ -206,7 +207,7 @@ public class LedgerManagerTest { parties[3] = new ConsensusParticipantData(); parties[3].setId(3); parties[3].setName("Tom"); - CryptoKeyPair kp3 = CryptoUtils.sign(CryptoAlgorithm.ED25519).generateKeyPair(); + CryptoKeyPair kp3 = CryptoUtils.sign(ClassicCryptoService.ED25519_ALGORITHM).generateKeyPair(); parties[3].setPubKey(kp3.getPubKey()); parties[3].setAddress(AddressEncoding.generateAddress(kp3.getPubKey()).toBase58()); parties[3].setHostAddress(new NetworkAddress("127.0.0.1", 9030)); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerMetaDataTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerMetaDataTest.java index 4785ab13..e2ce75ad 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerMetaDataTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerMetaDataTest.java @@ -13,11 +13,11 @@ import org.junit.Test; import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.ledger.ParticipantNode; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.ledger.CryptoSetting; +import com.jd.blockchain.ledger.ParticipantNode; import com.jd.blockchain.ledger.core.CryptoConfig; import com.jd.blockchain.ledger.core.LedgerAdminAccount; import com.jd.blockchain.ledger.core.LedgerConfiguration; @@ -54,11 +54,11 @@ public class LedgerMetaDataTest { // prepare work // ConsensusConfig consensusConfig = new ConsensusConfig(); - // consensusConfig.setValue(settingValue); + // consensusConfig.setValue(settingValue);ClassicCryptoService.ED25519_ALGORITHM CryptoConfig cryptoConfig = new CryptoConfig(); cryptoConfig.setAutoVerifyHash(true); - cryptoConfig.setHashAlgorithm(CryptoAlgorithm.SHA256); + cryptoConfig.setHashAlgorithm(ClassicCryptoService.SHA256_ALGORITHM); LedgerConfiguration ledgerConfiguration = new LedgerConfiguration(consensusProvider, new Bytes(consensusSettingBytes), cryptoConfig); @@ -67,7 +67,7 @@ public class LedgerMetaDataTest { ledgerMetadata.setSeed(seed); ledgerMetadata.setSetting(ledgerConfiguration); - HashDigest hashDigest = new HashDigest(CryptoAlgorithm.SHA256, rawDigestBytes); + HashDigest hashDigest = new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, rawDigestBytes); ledgerMetadata.setParticipantsHash(hashDigest); // encode and decode @@ -95,7 +95,7 @@ public class LedgerMetaDataTest { CryptoConfig cryptoConfig = new CryptoConfig(); cryptoConfig.setAutoVerifyHash(true); - cryptoConfig.setHashAlgorithm(CryptoAlgorithm.SHA256); + cryptoConfig.setHashAlgorithm(ClassicCryptoService.SHA256_ALGORITHM); LedgerConfiguration ledgerConfiguration = new LedgerConfiguration(consensusProvider, new Bytes(csSettingsBytes), cryptoConfig); byte[] encodeBytes = BinaryEncodingUtils.encode(ledgerConfiguration, LedgerSetting.class); @@ -134,7 +134,7 @@ public class LedgerMetaDataTest { // LedgerCodes.METADATA_LEDGER_SETTING_CRYPTO CryptoConfig cryptoConfig = new CryptoConfig(); cryptoConfig.setAutoVerifyHash(true); - cryptoConfig.setHashAlgorithm(CryptoAlgorithm.SHA256); + cryptoConfig.setHashAlgorithm(ClassicCryptoService.SHA256_ALGORITHM); byte[] encodeBytes = BinaryEncodingUtils.encode(cryptoConfig, CryptoSetting.class); CryptoSetting deCryptoConfig = BinaryEncodingUtils.decode(encodeBytes); @@ -150,7 +150,7 @@ public class LedgerMetaDataTest { // prepare work int id = 1; // String address = "xxxxxxxxxxxxxx"; - PubKey pubKey = new PubKey(CryptoAlgorithm.ED25519, rawDigestBytes); + PubKey pubKey = new PubKey(ClassicCryptoService.ED25519_ALGORITHM, rawDigestBytes); // ParticipantInfo info = new ParticipantCertData.ParticipantInfoData(1, "yyy"); // SignatureDigest signature = new SignatureDigest(CryptoAlgorithm.SM2, // rawDigestBytes); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerTestUtils.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerTestUtils.java index d9c80841..d78ebed3 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerTestUtils.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerTestUtils.java @@ -4,10 +4,11 @@ import java.util.Random; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoUtils; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureFunction; import com.jd.blockchain.crypto.hash.HashDigest; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.ledger.*; import com.jd.blockchain.ledger.core.CryptoConfig; import com.jd.blockchain.ledger.core.impl.TransactionStagedSnapshot; @@ -22,7 +23,7 @@ public class LedgerTestUtils { public static TransactionRequest createTxRequest(HashDigest ledgerHash) { - return createTxRequest(ledgerHash, CryptoUtils.sign(CryptoAlgorithm.ED25519)); + return createTxRequest(ledgerHash, CryptoUtils.sign(ClassicCryptoService.ED25519_ALGORITHM)); } public static TransactionRequest createTxRequest(HashDigest ledgerHash, SignatureFunction signatureFunction) { @@ -68,14 +69,14 @@ public class LedgerTestUtils { public static HashDigest generateRandomHash() { byte[] data = new byte[64]; rand.nextBytes(data); - return CryptoUtils.hash(CryptoAlgorithm.SHA256).hash(data); + return CryptoUtils.hash(ClassicCryptoService.SHA256_ALGORITHM).hash(data); } public static CryptoSetting createDefaultCryptoSetting() { CryptoConfig cryptoSetting = new CryptoConfig(); cryptoSetting.setAutoVerifyHash(true); - cryptoSetting.setHashAlgorithm(CryptoAlgorithm.SHA256); + cryptoSetting.setHashAlgorithm(ClassicCryptoService.SHA256_ALGORITHM); return cryptoSetting; } diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerTransactionDataTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerTransactionDataTest.java index d44e08d9..e91688a1 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerTransactionDataTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerTransactionDataTest.java @@ -19,9 +19,10 @@ import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoUtils; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeyPair; import com.jd.blockchain.ledger.DataAccountKVSetOperation; @@ -69,11 +70,11 @@ public class LedgerTransactionDataTest { long blockHeight = 9986L; data = new LedgerTransactionData(blockHeight, txRequestMessage, TransactionState.SUCCESS, initTransactionStagedSnapshot()); - HashDigest hash = new HashDigest(CryptoAlgorithm.SHA256, "zhangsan".getBytes()); - HashDigest adminAccountHash = new HashDigest(CryptoAlgorithm.SHA256, "lisi".getBytes()); - HashDigest userAccountSetHash = new HashDigest(CryptoAlgorithm.SHA256, "wangwu".getBytes()); - HashDigest dataAccountSetHash = new HashDigest(CryptoAlgorithm.SHA256, "zhaoliu".getBytes()); - HashDigest contractAccountSetHash = new HashDigest(CryptoAlgorithm.SHA256, "sunqi".getBytes()); + HashDigest hash = new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "zhangsan".getBytes()); + HashDigest adminAccountHash = new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "lisi".getBytes()); + HashDigest userAccountSetHash = new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "wangwu".getBytes()); + HashDigest dataAccountSetHash = new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "zhaoliu".getBytes()); + HashDigest contractAccountSetHash = new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "sunqi".getBytes()); data.setHash(hash); // data.setBlockHeight(blockHeight); @@ -213,30 +214,30 @@ public class LedgerTransactionDataTest { private TransactionStagedSnapshot initTransactionStagedSnapshot() { TransactionStagedSnapshot transactionStagedSnapshot = new TransactionStagedSnapshot(); - transactionStagedSnapshot.setAdminAccountHash(new HashDigest(CryptoAlgorithm.SHA256, "zhangsan".getBytes())); - transactionStagedSnapshot.setContractAccountSetHash(new HashDigest(CryptoAlgorithm.SHA256, "lisi".getBytes())); - transactionStagedSnapshot.setDataAccountSetHash(new HashDigest(CryptoAlgorithm.SHA256, "wangwu".getBytes())); - transactionStagedSnapshot.setUserAccountSetHash(new HashDigest(CryptoAlgorithm.SHA256, "zhaoliu".getBytes())); + transactionStagedSnapshot.setAdminAccountHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "zhangsan".getBytes())); + transactionStagedSnapshot.setContractAccountSetHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "lisi".getBytes())); + transactionStagedSnapshot.setDataAccountSetHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "wangwu".getBytes())); + transactionStagedSnapshot.setUserAccountSetHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "zhaoliu".getBytes())); return transactionStagedSnapshot; } private TxRequestMessage initTxRequestMessage() throws Exception { TxRequestMessage txRequestMessage = new TxRequestMessage(initTransactionContent()); - SignatureDigest digest1 = new SignatureDigest(CryptoAlgorithm.ED25519, "zhangsan".getBytes()); - SignatureDigest digest2 = new SignatureDigest(CryptoAlgorithm.ED25519, "lisi".getBytes()); - DigitalSignatureBlob endPoint1 = new DigitalSignatureBlob(new PubKey(CryptoAlgorithm.ED25519, "jd1.com".getBytes()) + SignatureDigest digest1 = new SignatureDigest(ClassicCryptoService.ED25519_ALGORITHM, "zhangsan".getBytes()); + SignatureDigest digest2 = new SignatureDigest(ClassicCryptoService.ED25519_ALGORITHM, "lisi".getBytes()); + DigitalSignatureBlob endPoint1 = new DigitalSignatureBlob(new PubKey(ClassicCryptoService.ED25519_ALGORITHM, "jd1.com".getBytes()) , digest1); - DigitalSignatureBlob endPoint2 = new DigitalSignatureBlob(new PubKey(CryptoAlgorithm.ED25519, "jd2.com".getBytes()) + DigitalSignatureBlob endPoint2 = new DigitalSignatureBlob(new PubKey(ClassicCryptoService.ED25519_ALGORITHM, "jd2.com".getBytes()) , digest2); txRequestMessage.addEndpointSignatures(endPoint1); txRequestMessage.addEndpointSignatures(endPoint2); - SignatureDigest digest3 = new SignatureDigest(CryptoAlgorithm.ED25519, "wangwu".getBytes()); - SignatureDigest digest4 = new SignatureDigest(CryptoAlgorithm.ED25519, "zhaoliu".getBytes()); - DigitalSignatureBlob node1 = new DigitalSignatureBlob(new PubKey(CryptoAlgorithm.ED25519, "jd3.com".getBytes()) + SignatureDigest digest3 = new SignatureDigest(ClassicCryptoService.ED25519_ALGORITHM, "wangwu".getBytes()); + SignatureDigest digest4 = new SignatureDigest(ClassicCryptoService.ED25519_ALGORITHM, "zhaoliu".getBytes()); + DigitalSignatureBlob node1 = new DigitalSignatureBlob(new PubKey(ClassicCryptoService.ED25519_ALGORITHM, "jd3.com".getBytes()) , digest3); - DigitalSignatureBlob node2 = new DigitalSignatureBlob(new PubKey(CryptoAlgorithm.ED25519, "jd4.com".getBytes()) + DigitalSignatureBlob node2 = new DigitalSignatureBlob(new PubKey(ClassicCryptoService.ED25519_ALGORITHM, "jd4.com".getBytes()) , digest4); txRequestMessage.addNodeSignatures(node1); txRequestMessage.addNodeSignatures(node2); @@ -246,11 +247,11 @@ public class LedgerTransactionDataTest { private TransactionContent initTransactionContent() throws Exception{ TxContentBlob contentBlob = null; - BlockchainKeyPair id = BlockchainKeyGenerator.getInstance().generate(CryptoAlgorithm.ED25519); - HashDigest ledgerHash = CryptoUtils.hash(CryptoAlgorithm.SHA256).hash(UUID.randomUUID().toString().getBytes("UTF-8")); + BlockchainKeyPair id = BlockchainKeyGenerator.getInstance().generate(ClassicCryptoService.ED25519_ALGORITHM); + HashDigest ledgerHash = CryptoUtils.hash(ClassicCryptoService.SHA256_ALGORITHM).hash(UUID.randomUUID().toString().getBytes("UTF-8")); BlockchainOperationFactory opFactory = new BlockchainOperationFactory(); contentBlob = new TxContentBlob(ledgerHash); - contentBlob.setHash(new HashDigest(CryptoAlgorithm.SHA256, "jd.com".getBytes())); + contentBlob.setHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "jd.com".getBytes())); // contentBlob.setSubjectAccount(id.getAddress()); // contentBlob.setSequenceNumber(1); DataAccountKVSetOperation kvsetOP = opFactory.dataAccount(id.getAddress()).set("Name", ByteArray.fromString("AAA", "UTF-8"), -1).getOperation(); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/MerkleDataSetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/MerkleDataSetTest.java index 6a93df07..232fc9a2 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/MerkleDataSetTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/MerkleDataSetTest.java @@ -13,10 +13,9 @@ import java.util.Random; import java.util.Set; import org.junit.Test; -import org.springframework.util.StringUtils; -import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.hash.HashDigest; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.ledger.core.CryptoConfig; import com.jd.blockchain.ledger.core.MerkleDataSet; import com.jd.blockchain.ledger.core.MerkleProof; @@ -34,7 +33,7 @@ public class MerkleDataSetTest { public void testStorageIncreasement() { String keyPrefix = ""; CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setHashAlgorithm(CryptoAlgorithm.SHA256); + cryptoConfig.setHashAlgorithm(ClassicCryptoService.SHA256_ALGORITHM); cryptoConfig.setAutoVerifyHash(true); MemoryKVStorage storage = new MemoryKVStorage(); @@ -118,7 +117,7 @@ public class MerkleDataSetTest { Random rand = new Random(); CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setHashAlgorithm(CryptoAlgorithm.SHA256); + cryptoConfig.setHashAlgorithm(ClassicCryptoService.SHA256_ALGORITHM); cryptoConfig.setAutoVerifyHash(true); MemoryKVStorage storage = new MemoryKVStorage(); @@ -283,7 +282,7 @@ public class MerkleDataSetTest { Random rand = new Random(); CryptoConfig cryptoConfig = new CryptoConfig(); - cryptoConfig.setHashAlgorithm(CryptoAlgorithm.SHA256); + cryptoConfig.setHashAlgorithm(ClassicCryptoService.SHA256_ALGORITHM); cryptoConfig.setAutoVerifyHash(true); MemoryKVStorage storage = new MemoryKVStorage(); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/MerkleTreeTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/MerkleTreeTest.java index 7a3b9140..8ccd2195 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/MerkleTreeTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/MerkleTreeTest.java @@ -14,8 +14,8 @@ import java.util.TreeMap; import org.junit.Test; import org.mockito.Mockito; -import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.hash.HashDigest; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.ledger.CryptoSetting; import com.jd.blockchain.ledger.core.MerkleDataNode; import com.jd.blockchain.ledger.core.MerkleNode; @@ -34,7 +34,7 @@ public class MerkleTreeTest { Random rand = new Random(); CryptoSetting setting = Mockito.mock(CryptoSetting.class); - when(setting.getHashAlgorithm()).thenReturn(CryptoAlgorithm.SHA256); + when(setting.getHashAlgorithm()).thenReturn(ClassicCryptoService.SHA256_ALGORITHM); when(setting.getAutoVerifyHash()).thenReturn(true); // 测试从空的树开始,顺序增加数据节点; @@ -85,7 +85,7 @@ public class MerkleTreeTest { @Test public void testSequenceInsert_OneCommit() { CryptoSetting setting = Mockito.mock(CryptoSetting.class); - when(setting.getHashAlgorithm()).thenReturn(CryptoAlgorithm.SHA256); + when(setting.getHashAlgorithm()).thenReturn(ClassicCryptoService.SHA256_ALGORITHM); when(setting.getAutoVerifyHash()).thenReturn(true); // 测试从空的树开始,顺序增加数据节点; @@ -139,7 +139,7 @@ public class MerkleTreeTest { @Test public void testSequenceInsert_MultiCommit() { CryptoSetting setting = Mockito.mock(CryptoSetting.class); - when(setting.getHashAlgorithm()).thenReturn(CryptoAlgorithm.SHA256); + when(setting.getHashAlgorithm()).thenReturn(ClassicCryptoService.SHA256_ALGORITHM); when(setting.getAutoVerifyHash()).thenReturn(true); // 测试从空的树开始,顺序增加数据节点; @@ -319,7 +319,7 @@ public class MerkleTreeTest { @Test public void testRandomInsert_MultiCommit() { CryptoSetting setting = Mockito.mock(CryptoSetting.class); - when(setting.getHashAlgorithm()).thenReturn(CryptoAlgorithm.SHA256); + when(setting.getHashAlgorithm()).thenReturn(ClassicCryptoService.SHA256_ALGORITHM); when(setting.getAutoVerifyHash()).thenReturn(true); // 保存所有写入的数据节点的 SN-Hash 映射表; @@ -409,7 +409,7 @@ public class MerkleTreeTest { @Test public void testDataModify() { CryptoSetting setting = Mockito.mock(CryptoSetting.class); - when(setting.getHashAlgorithm()).thenReturn(CryptoAlgorithm.SHA256); + when(setting.getHashAlgorithm()).thenReturn(ClassicCryptoService.SHA256_ALGORITHM); when(setting.getAutoVerifyHash()).thenReturn(true); // 保存所有写入的数据节点的 SN-Hash 映射表; @@ -492,7 +492,7 @@ public class MerkleTreeTest { @Test public void testDataVersionModify() { CryptoSetting setting = Mockito.mock(CryptoSetting.class); - when(setting.getHashAlgorithm()).thenReturn(CryptoAlgorithm.SHA256); + when(setting.getHashAlgorithm()).thenReturn(ClassicCryptoService.SHA256_ALGORITHM); when(setting.getAutoVerifyHash()).thenReturn(true); // 保存所有写入的数据节点的 SN-Hash 映射表; @@ -559,7 +559,7 @@ public class MerkleTreeTest { @Test public void testMerkleReload() { CryptoSetting setting = Mockito.mock(CryptoSetting.class); - when(setting.getHashAlgorithm()).thenReturn(CryptoAlgorithm.SHA256); + when(setting.getHashAlgorithm()).thenReturn(ClassicCryptoService.SHA256_ALGORITHM); when(setting.getAutoVerifyHash()).thenReturn(true); // 保存所有写入的数据节点的 SN-Hash 映射表; diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TransactionStagedSnapshotTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TransactionStagedSnapshotTest.java index a38c7d0b..e819751c 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TransactionStagedSnapshotTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TransactionStagedSnapshotTest.java @@ -8,22 +8,17 @@ */ package test.com.jd.blockchain.ledger; +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.PubKey; -import com.jd.blockchain.crypto.base.BaseCryptoKey; import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.ledger.ContractEventSendOperation; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.ledger.LedgerDataSnapshot; -import com.jd.blockchain.ledger.Operation; import com.jd.blockchain.ledger.core.impl.TransactionStagedSnapshot; -import com.jd.blockchain.ledger.data.ContractEventSendOpTemplate; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; /** * @@ -40,10 +35,10 @@ public class TransactionStagedSnapshotTest { public void initTransactionStagedSnapshot() { DataContractRegistry.register(LedgerDataSnapshot.class); data = new TransactionStagedSnapshot(); - data.setAdminAccountHash(new HashDigest(CryptoAlgorithm.SHA256, "zhangsan".getBytes())); - data.setContractAccountSetHash(new HashDigest(CryptoAlgorithm.SHA256, "lisi".getBytes())); - data.setDataAccountSetHash(new HashDigest(CryptoAlgorithm.SHA256, "wangwu".getBytes())); - data.setUserAccountSetHash(new HashDigest(CryptoAlgorithm.SHA256, "zhaoliu".getBytes())); + data.setAdminAccountHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "zhangsan".getBytes())); + data.setContractAccountSetHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "lisi".getBytes())); + data.setDataAccountSetHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "wangwu".getBytes())); + data.setUserAccountSetHash(new HashDigest(ClassicCryptoService.SHA256_ALGORITHM, "zhaoliu".getBytes())); } @Test diff --git a/source/ledger/ledger-model/pom.xml b/source/ledger/ledger-model/pom.xml index d70eb20c..0c19fb1e 100644 --- a/source/ledger/ledger-model/pom.xml +++ b/source/ledger/ledger-model/pom.xml @@ -21,6 +21,14 @@ crypto-framework ${project.version} + + + com.jd.blockchain + crypto-impl + ${project.version} + test + + com.jd.blockchain utils-common @@ -31,6 +39,8 @@ utils-web ${project.version} + + diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/AccountHeader.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/AccountHeader.java index d382295d..fa77557c 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/AccountHeader.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/AccountHeader.java @@ -1,9 +1,9 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.consts.TypeCodes; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockBody.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockBody.java index 54a6011e..73d8496c 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockBody.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockBody.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentity.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentity.java index 4b54cd3c..ea061bcf 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentity.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentity.java @@ -1,9 +1,9 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.consts.TypeCodes; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentityData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentityData.java index 212b49e3..66cd5766 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentityData.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentityData.java @@ -16,7 +16,7 @@ import com.jd.blockchain.binaryproto.FieldSetter; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.data.CryptoKeyEncoding; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.io.ByteArray; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeyGenerator.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeyGenerator.java index cdf97c92..03fce3d1 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeyGenerator.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeyGenerator.java @@ -2,10 +2,7 @@ package com.jd.blockchain.ledger; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoUtils; -import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.SignatureFunction; -import com.jd.blockchain.crypto.impl.AsymmtricCryptographyImpl; /** * 区块链密钥生成器; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeyPair.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeyPair.java index 2a2a7c9a..a988d2b3 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeyPair.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeyPair.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.utils.Bytes; /** diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesValue.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesValue.java index c2fec5fc..d54b29b0 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesValue.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BytesValue.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.ValueType; import com.jd.blockchain.utils.io.BytesSlice; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractCodeDeployOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractCodeDeployOperation.java index 48ab6294..7d82a7c8 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractCodeDeployOperation.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractCodeDeployOperation.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.ValueType; @DataContract(code= TypeCodes.TX_OP_CONTRACT_DEPLOY) diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractEventSendOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractEventSendOperation.java index dce287b8..38c6b90d 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractEventSendOperation.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractEventSendOperation.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/CryptoSetting.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/CryptoSetting.java index d00518e9..4dae891b 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/CryptoSetting.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/CryptoSetting.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountKVSetOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountKVSetOperation.java index 868bbd0f..a892aba9 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountKVSetOperation.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountKVSetOperation.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountRegisterOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountRegisterOperation.java index d79ae611..c938d352 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountRegisterOperation.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountRegisterOperation.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; @DataContract(code= TypeCodes.TX_OP_DATA_ACC_REG) public interface DataAccountRegisterOperation extends Operation { diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataType.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataType.java index 5bbd832d..278937d0 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataType.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataType.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.EnumContract; import com.jd.blockchain.binaryproto.EnumField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.ValueType; /** diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignature.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignature.java index 9a4ea62a..1a4ce413 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignature.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignature.java @@ -1,7 +1,7 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; +import com.jd.blockchain.consts.TypeCodes; /** * 数字签名; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignatureBody.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignatureBody.java index 1b3f26ac..4182bed3 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignatureBody.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignatureBody.java @@ -1,9 +1,9 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.consts.TypeCodes; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/EndpointRequest.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/EndpointRequest.java index f0a31867..0af6f231 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/EndpointRequest.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/EndpointRequest.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashObject.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashObject.java index 1e9fb23c..8027bb03 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashObject.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashObject.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.hash.HashDigest; /** diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerBlock.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerBlock.java index e2c3eecc..c2e1e48a 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerBlock.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerBlock.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerDataSnapshot.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerDataSnapshot.java index 27265b6f..969feb78 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerDataSnapshot.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerDataSnapshot.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitOperation.java index 9b6a98a6..c14e79c1 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitOperation.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitOperation.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; @DataContract(code= TypeCodes.TX_OP_LEDGER_INIT) public interface LedgerInitOperation extends Operation{ diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitSetting.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitSetting.java index 548ec34f..7d36dd30 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitSetting.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitSetting.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerTransaction.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerTransaction.java index 45bc493c..ef7cb4d3 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerTransaction.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerTransaction.java @@ -1,7 +1,7 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; +import com.jd.blockchain.consts.TypeCodes; /** * 账本的事务; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/NodeRequest.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/NodeRequest.java index 574f1fcf..2742d4c9 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/NodeRequest.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/NodeRequest.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.hash.HashDigest; @DataContract(code = TypeCodes.REQUEST_NODE) diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Operation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Operation.java index 87b8f97b..cbc7ffcb 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Operation.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Operation.java @@ -1,7 +1,7 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; +import com.jd.blockchain.consts.TypeCodes; @DataContract(code= TypeCodes.TX_OP) public interface Operation { diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantNode.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantNode.java index 6cc9924d..91b63af1 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantNode.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantNode.java @@ -1,9 +1,9 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.consts.TypeCodes; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.utils.ValueType; /** diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Transaction.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Transaction.java index a286797e..38dd7978 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Transaction.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Transaction.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.utils.ValueType; import com.jd.blockchain.utils.io.ByteArray; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionContent.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionContent.java index 136ce6e0..1d63bacc 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionContent.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionContent.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionContentBody.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionContentBody.java index 39a27256..2fc029db 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionContentBody.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionContentBody.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRequest.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRequest.java index 7bb56dcb..db2c39f4 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRequest.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRequest.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionResponse.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionResponse.java index db7e5125..e6b16a32 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionResponse.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionResponse.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.utils.ValueType; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionState.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionState.java index d19bcff2..ed756109 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionState.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionState.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.EnumContract; import com.jd.blockchain.binaryproto.EnumField; +import com.jd.blockchain.consts.TypeCodes; import com.jd.blockchain.utils.ValueType; /** diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserInfo.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserInfo.java index 5510cdb0..eea581ff 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserInfo.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserInfo.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.consts.TypeCodes; +import com.jd.blockchain.crypto.PubKey; @DataContract(code= TypeCodes.USER) public interface UserInfo extends AccountHeader { diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRegisterOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRegisterOperation.java index ec0f7372..f565b190 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRegisterOperation.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRegisterOperation.java @@ -1,8 +1,8 @@ package com.jd.blockchain.ledger; -import com.jd.blockchain.base.data.TypeCodes; import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.TypeCodes; @DataContract(code= TypeCodes.TX_OP_USER_REG) public interface UserRegisterOperation extends Operation { diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/ConsensusParticipantData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/ConsensusParticipantData.java index 73049d3a..e31d6447 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/ConsensusParticipantData.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/ConsensusParticipantData.java @@ -1,6 +1,6 @@ package com.jd.blockchain.ledger.data; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.ParticipantNode; import com.jd.blockchain.utils.net.NetworkAddress; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/CryptoKeyEncoding.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/CryptoKeyEncoding.java index fcf22a26..15cb3649 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/CryptoKeyEncoding.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/CryptoKeyEncoding.java @@ -7,8 +7,8 @@ import java.io.OutputStream; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoKey; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.MagicNumber; import com.jd.blockchain.utils.io.ByteArray; import com.jd.blockchain.utils.io.BytesEncoding; @@ -34,7 +34,7 @@ public class CryptoKeyEncoding { } out.write(magicNum); - out.write(key.getAlgorithm().CODE); + out.write(key.getAlgorithm().code()); int size = 2;// 已经写入 2 字节; size += BytesEncoding.write(key.getRawKeyBytes(), NumberMask.SHORT, out); diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/DigitalSignatureBlob.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/DigitalSignatureBlob.java index 47fb64b3..86e78819 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/DigitalSignatureBlob.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/DigitalSignatureBlob.java @@ -1,7 +1,7 @@ package com.jd.blockchain.ledger.data; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.DigitalSignature; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/PreparedTx.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/PreparedTx.java index 68faa219..7e798102 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/PreparedTx.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/PreparedTx.java @@ -2,12 +2,11 @@ package com.jd.blockchain.ledger.data; import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.crypto.CryptoUtils; +import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.asymmetric.SignatureFunction; import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.impl.def.asymmetric.ED25519SignatureFunction; import com.jd.blockchain.ledger.DigitalSignature; import com.jd.blockchain.ledger.PreparedTransaction; import com.jd.blockchain.ledger.TransactionContent; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/TxRequestBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/TxRequestBuilder.java index ee8232b7..8d2577a1 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/TxRequestBuilder.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/data/TxRequestBuilder.java @@ -6,9 +6,9 @@ import java.util.List; import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoUtils; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.DigitalSignature; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/AddressEncodingTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/AddressEncodingTest.java index 60003c9b..e2b8a828 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/AddressEncodingTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/AddressEncodingTest.java @@ -3,7 +3,7 @@ package test.com.jd.blockchain.ledger.data; import java.util.Random; import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeyPair; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ContractCodeDeployOpTemplateTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ContractCodeDeployOpTemplateTest.java index 801e744d..ca6e28d3 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ContractCodeDeployOpTemplateTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ContractCodeDeployOpTemplateTest.java @@ -11,7 +11,7 @@ package test.com.jd.blockchain.ledger.data; import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.*; import com.jd.blockchain.ledger.data.ContractCodeDeployOpTemplate; import com.jd.blockchain.utils.io.BytesUtils; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DataAccountRegisterOpTemplateTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DataAccountRegisterOpTemplateTest.java index f31fe98c..27b62443 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DataAccountRegisterOpTemplateTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DataAccountRegisterOpTemplateTest.java @@ -11,7 +11,7 @@ package test.com.jd.blockchain.ledger.data; import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.*; import com.jd.blockchain.ledger.data.DataAccountRegisterOpTemplate; import com.jd.blockchain.utils.io.ByteArray; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DigitalSignatureBlobTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DigitalSignatureBlobTest.java index 27f6d733..b75c4149 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DigitalSignatureBlobTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DigitalSignatureBlobTest.java @@ -16,7 +16,7 @@ import org.junit.Test; import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.ledger.DigitalSignature; import com.jd.blockchain.ledger.DigitalSignatureBody; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/TxRequestMessageTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/TxRequestMessageTest.java index 6649c6b8..a361cfa3 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/TxRequestMessageTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/TxRequestMessageTest.java @@ -19,7 +19,7 @@ import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoUtils; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.BlockchainKeyGenerator; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/UserRegisterOpTemplateTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/UserRegisterOpTemplateTest.java index c5e717f4..ce31ce45 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/UserRegisterOpTemplateTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/UserRegisterOpTemplateTest.java @@ -11,7 +11,7 @@ package test.com.jd.blockchain.ledger.data; import com.jd.blockchain.binaryproto.BinaryEncodingUtils; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.*; import com.jd.blockchain.ledger.data.ContractEventSendOpTemplate; import com.jd.blockchain.ledger.data.DataAccountRegisterOpTemplate; diff --git a/source/ledger/ledger-rpc/pom.xml b/source/ledger/ledger-rpc/pom.xml index d46aafd3..3dd190a8 100644 --- a/source/ledger/ledger-rpc/pom.xml +++ b/source/ledger/ledger-rpc/pom.xml @@ -36,16 +36,16 @@ - - - - org.apache.maven.plugins - maven-deploy-plugin - 2.8.2 - - false - - - - + + + + org.apache.maven.plugins + maven-deploy-plugin + 2.8.2 + + true + + + + \ No newline at end of file diff --git a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectJsonSerializer.java b/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectJsonSerializer.java deleted file mode 100644 index 4aba18a3..00000000 --- a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectJsonSerializer.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.jd.blockchain.web.serializes; - -import com.alibaba.fastjson.serializer.JSONSerializer; -import com.alibaba.fastjson.serializer.ObjectSerializer; -import com.jd.blockchain.crypto.asymmetric.PubKey; -import com.jd.blockchain.crypto.asymmetric.SignatureDigest; -import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.ledger.DataType; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.BytesSlice; - -import java.lang.reflect.Type; - -public class ByteArrayObjectJsonSerializer implements ObjectSerializer { - - private Class clazz; - - private ByteArrayObjectJsonSerializer(Class clazz) { - this.clazz = clazz; - } - - public static ByteArrayObjectJsonSerializer getInstance(Class clazz) { - return new ByteArrayObjectJsonSerializer(clazz); - } - - @Override - public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) { - if (object.getClass() != clazz) { - serializer.writeNull(); - return; - } - if (object instanceof HashDigest) { - serializer.write(new HashDigestJson(((HashDigest) object).toBase58())); - } else if (object instanceof PubKey) { - serializer.write(new HashDigestJson(((PubKey) object).toBase58())); - } else if (object instanceof SignatureDigest) { - serializer.write(new HashDigestJson(((SignatureDigest) object).toBase58())); - } else if (object instanceof Bytes) { - serializer.write(new HashDigestJson(((Bytes) object).toBase58())); - } else if (object instanceof BytesSlice) { - serializer.write(Base58Utils.encode(((BytesSlice) object).toBytes())); - } - -// else if (object instanceof BytesValue) { -// DataType dataType = ((BytesValue) object).getType(); -// BytesSlice bytesValue = ((BytesValue) object).getValue(); -// Object realVal; -// switch (dataType) { -// case NIL: -// realVal = null; -// break; -// case TEXT: -// realVal = bytesValue.getString(); -// break; -// case BYTES: -// realVal = ByteArray.toHex(bytesValue.toBytes()); -// break; -// case INT32: -// realVal = bytesValue.getInt(); -// break; -// case INT64: -// realVal = bytesValue.getLong(); -// break; -// case JSON: -// realVal = bytesValue.getString(); -// break; -// default: -// realVal = ByteArray.toHex(bytesValue.toBytes()); -// break; -// } -// serializer.write(new BytesValueJson(dataType, realVal)); -// } - } - - private static class HashDigestJson { - - String value; - - public HashDigestJson(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - } - - public static class BytesValueJson { - - public BytesValueJson(DataType type, Object value) { - this.type = type; - this.value = value; - } - - DataType type; - - Object value; - - public DataType getType() { - return type; - } - - public void setType(DataType type) { - this.type = type; - } - - public Object getValue() { - return value; - } - - public void setValue(Object value) { - this.value = value; - } - } -} diff --git a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectUtil.java b/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectUtil.java deleted file mode 100644 index 2623cfe5..00000000 --- a/source/ledger/ledger-rpc/src/main/java/com/jd/blockchain/web/serializes/ByteArrayObjectUtil.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.web.serializes.ByteArrayObjectUtil - * Author: shaozhuguang - * Department: Y事业部 - * Date: 2019/3/27 上午11:23 - * Description: - */ -package com.jd.blockchain.web.serializes; - -import com.jd.blockchain.crypto.asymmetric.PubKey; -import com.jd.blockchain.crypto.asymmetric.SignatureDigest; -import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesSlice; -import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils; - -/** - * - * @author shaozhuguang - * @create 2019/3/27 - * @since 1.0.0 - */ - -public class ByteArrayObjectUtil { - - public static final Class[] BYTEARRAY_JSON_SERIALIZE_CLASS = new Class[] { - HashDigest.class, - PubKey.class, - SignatureDigest.class, - Bytes.class, - BytesSlice.class}; - - public static void init() { - for (Class byteArrayClass : BYTEARRAY_JSON_SERIALIZE_CLASS) { - JSONSerializeUtils.configSerialization(byteArrayClass, - ByteArrayObjectJsonSerializer.getInstance(byteArrayClass), - ByteArrayObjectJsonDeserializer.getInstance(byteArrayClass)); - } - } -} \ No newline at end of file diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerWebServerConfigurer.java b/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerWebServerConfigurer.java index f0d52ac5..9ae76451 100644 --- a/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerWebServerConfigurer.java +++ b/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerWebServerConfigurer.java @@ -2,16 +2,22 @@ package com.jd.blockchain.peer.web; import java.util.List; +import com.jd.blockchain.utils.io.BytesSlice; import com.jd.blockchain.web.converters.BinaryMessageConverter; import com.jd.blockchain.web.converters.HashDigestInputConverter; -import com.jd.blockchain.web.serializes.ByteArrayObjectUtil; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import com.jd.blockchain.crypto.PubKey; +import com.jd.blockchain.crypto.asymmetric.SignatureDigest; +import com.jd.blockchain.crypto.hash.HashDigest; +import com.jd.blockchain.crypto.serialize.ByteArrayObjectDeserializer; +import com.jd.blockchain.crypto.serialize.ByteArrayObjectSerializer; +import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.io.ByteArray; import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils; import com.jd.blockchain.utils.web.model.JsonWebResponseMessageConverter; @@ -19,6 +25,13 @@ import com.jd.blockchain.utils.web.model.JsonWebResponseMessageConverter; @Configuration public class PeerWebServerConfigurer implements WebMvcConfigurer { + private static final Class[] BYTEARRAY_JSON_SERIALIZE_CLASS = new Class[] { + HashDigest.class, + PubKey.class, + SignatureDigest.class, + Bytes.class, + BytesSlice.class}; + static { JSONSerializeUtils.disableCircularReferenceDetect(); JSONSerializeUtils.configStringSerializer(ByteArray.class); @@ -46,6 +59,10 @@ public class PeerWebServerConfigurer implements WebMvcConfigurer { } private void initByteArrayJsonSerialize() { - ByteArrayObjectUtil.init(); + for (Class byteArrayClass : BYTEARRAY_JSON_SERIALIZE_CLASS) { + JSONSerializeUtils.configSerialization(byteArrayClass, + ByteArrayObjectSerializer.getInstance(byteArrayClass), + ByteArrayObjectDeserializer.getInstance(byteArrayClass)); + } } } diff --git a/source/pom.xml b/source/pom.xml index 2e510d96..37592211 100644 --- a/source/pom.xml +++ b/source/pom.xml @@ -41,7 +41,7 @@ 0.8.1-SNAPSHOT 0.0.8.RELEASE - 0.6.6.RELEASE + 0.6.4.RELEASE diff --git a/source/runtime/runtime-context/src/main/java/com/jd/blockchain/runtime/AbstractModule.java b/source/runtime/runtime-context/src/main/java/com/jd/blockchain/runtime/AbstractModule.java index 234b73fe..fbd2df3f 100644 --- a/source/runtime/runtime-context/src/main/java/com/jd/blockchain/runtime/AbstractModule.java +++ b/source/runtime/runtime-context/src/main/java/com/jd/blockchain/runtime/AbstractModule.java @@ -22,8 +22,7 @@ public abstract class AbstractModule implements Module { throw new IllegalStateException(e.getMessage(), e); } } - - @Override + public InputStream loadResourceAsStream(String name) { return getModuleClassLoader().getResourceAsStream(name); } diff --git a/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/ModularFactory.java b/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/ModularFactory.java index e38b3dd1..b9615482 100644 --- a/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/ModularFactory.java +++ b/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/ModularFactory.java @@ -3,7 +3,7 @@ package com.jd.blockchain.runtime.modular; public class ModularFactory { /** - * start system; + * 启动系统; */ public static void startSystem(String runtimeDir, boolean productMode, ClassLoader libClassLoader,String mainClassName, ClassLoader systemClassLoader, String[] args) { diff --git a/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/MuduleClassLoader.java b/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/MuduleClassLoader.java index ad202462..732ba9a8 100644 --- a/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/MuduleClassLoader.java +++ b/source/runtime/runtime-modular/src/main/java/com/jd/blockchain/runtime/modular/MuduleClassLoader.java @@ -11,7 +11,6 @@ public class MuduleClassLoader extends URLClassLoader { } - @Override public Class loadClass(String name) throws ClassNotFoundException{ if (name.equals("com.jd.blockchain.contract.model.ContractEventContext") ){ diff --git a/source/sdk/sdk-base/pom.xml b/source/sdk/sdk-base/pom.xml index 4b629000..4179db3a 100644 --- a/source/sdk/sdk-base/pom.xml +++ b/source/sdk/sdk-base/pom.xml @@ -9,15 +9,14 @@ sdk-base - + com.jd.blockchain - ledger-rpc + ledger-model ${project.version} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/HashDigestsResponseConverter.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/HashDigestsResponseConverter.java index 9c766e5e..85aefe33 100644 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/HashDigestsResponseConverter.java +++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/HashDigestsResponseConverter.java @@ -4,7 +4,7 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.jd.blockchain.binaryproto.BinaryEncodingUtils; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.data.TxResponseMessage; diff --git a/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/ClientOperationUtil.java b/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/ClientOperationUtil.java deleted file mode 100644 index 2d75f985..00000000 --- a/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/ClientOperationUtil.java +++ /dev/null @@ -1,273 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: com.jd.blockchain.sdk.client.ClientOperationUtil - * Author: shaozhuguang - * Department: Y事业部 - * Date: 2019/3/27 下午4:12 - * Description: - */ -package com.jd.blockchain.sdk.client; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.PubKey; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.data.*; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.codec.HexUtils; -import com.jd.blockchain.utils.io.BytesSlice; -import org.apache.commons.codec.binary.Base64; - -import java.lang.reflect.Field; - -/** - * - * @author shaozhuguang - * @create 2019/3/27 - * @since 1.0.0 - */ - -public class ClientOperationUtil { - - public static Operation read(Operation operation) { - - try { - // Class - Class clazz = operation.getClass(); - Field field = clazz.getSuperclass().getDeclaredField("h"); - field.setAccessible(true); - Object object = field.get(operation); - if (object instanceof JSONObject) { - JSONObject jsonObject = (JSONObject) object; - if (jsonObject.containsKey("accountID")) { - return convertDataAccountRegisterOperation(jsonObject); - } else if (jsonObject.containsKey("userID")) { - return convertUserRegisterOperation(jsonObject); - } else if (jsonObject.containsKey("contractID")) { - return convertContractCodeDeployOperation(jsonObject); - } else if (jsonObject.containsKey("writeSet")) { - return convertDataAccountKVSetOperation(jsonObject); - } else if (jsonObject.containsKey("initSetting")) { - return convertLedgerInitOperation(jsonObject); - } else if (jsonObject.containsKey("contractAddress")) { - return convertContractEventSendOperation(jsonObject); - } - } - } catch (Exception e) { - throw new RuntimeException(e); - } - - return null; - } - - public static Object readValueByBytesValue(BytesValue bytesValue) { - DataType dataType = bytesValue.getType(); - BytesSlice saveVal = bytesValue.getValue(); - Object showVal; - switch (dataType) { - case BYTES: - // return hex - showVal = HexUtils.encode(saveVal.getBytesCopy()); - break; - case TEXT: - case JSON: - showVal = saveVal.getString(); - break; - case INT64: - showVal = saveVal.getLong(); - break; - default: - showVal = HexUtils.encode(saveVal.getBytesCopy()); - break; - } - return showVal; - } - - public static DataAccountRegisterOperation convertDataAccountRegisterOperation(JSONObject jsonObject) { - JSONObject account = jsonObject.getJSONObject("accountID"); - return new DataAccountRegisterOpTemplate(blockchainIdentity(account)); - } - - public static DataAccountKVSetOperation convertDataAccountKVSetOperation(JSONObject jsonObject) { - // 写入集合处理 - JSONArray writeSetObj = jsonObject.getJSONArray("writeSet"); - JSONObject accountAddrObj = jsonObject.getJSONObject("accountAddress"); - String addressBase58 = accountAddrObj.getString("value"); - Bytes address = Bytes.fromBase58(addressBase58); - - DataAccountKVSetOpTemplate kvOperation = new DataAccountKVSetOpTemplate(address); - for (int i = 0; i + + + + sdk + com.jd.blockchain + 0.9.0-SNAPSHOT + + 4.0.0 + + sdk-mq + + + UTF-8 + 1.8 + 1.8 + + + + + junit + junit + 4.11 + test + + + com.jd.blockchain + sdk-base + ${project.version} + + + com.lmax + disruptor + + + io.nats + jnats + + + + + + + diff --git a/source/sdk/sdk-samples/pom.xml b/source/sdk/sdk-samples/pom.xml index 8c47ed65..bc85d375 100644 --- a/source/sdk/sdk-samples/pom.xml +++ b/source/sdk/sdk-samples/pom.xml @@ -24,13 +24,6 @@ tools-initializer ${project.version} - - - com.jd.blockchain - ledger-rpc - ${project.version} - - diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Contract.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Contract.java index 4f097128..d79764eb 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Contract.java +++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Contract.java @@ -1,11 +1,11 @@ package com.jd.blockchain.sdk.samples; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoUtils; import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; import com.jd.blockchain.crypto.asymmetric.SignatureFunction; import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.impl.AsymmtricCryptographyImpl; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeyPair; import com.jd.blockchain.ledger.PreparedTransaction; @@ -26,7 +26,7 @@ public class SDKDemo_Contract { public static BlockchainKeyPair CLIENT_CERT = BlockchainKeyGenerator.getInstance().generate(CryptoAlgorithm.ED25519); - public static AsymmetricCryptography asymmetricCryptography = new AsymmtricCryptographyImpl(); + public static AsymmetricCryptography asymmetricCryptography = CryptoUtils.asymmCrypto(); /** * 演示合约执行的过程; diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_DataAccount.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_DataAccount.java index 24fe6a56..fdcee7c2 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_DataAccount.java +++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_DataAccount.java @@ -1,13 +1,15 @@ package com.jd.blockchain.sdk.samples; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoUtils; import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; import com.jd.blockchain.crypto.asymmetric.SignatureFunction; import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.impl.AsymmtricCryptographyImpl; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.data.CryptoKeyEncoding; +import com.jd.blockchain.ledger.BlockchainKeyGenerator; +import com.jd.blockchain.ledger.BlockchainKeyPair; +import com.jd.blockchain.ledger.PreparedTransaction; +import com.jd.blockchain.ledger.TransactionTemplate; import com.jd.blockchain.sdk.BlockchainTransactionService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; import com.jd.blockchain.utils.net.NetworkAddress; @@ -16,7 +18,7 @@ public class SDKDemo_DataAccount { public static BlockchainKeyPair CLIENT_CERT = BlockchainKeyGenerator.getInstance().generate(CryptoAlgorithm.ED25519); - public static AsymmetricCryptography asymmetricCryptography = new AsymmtricCryptographyImpl(); + public static AsymmetricCryptography asymmetricCryptography = CryptoUtils.asymmCrypto(); /** * 生成一个区块链用户,并注册到区块链; diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_InsertData.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_InsertData.java index 485b1d5d..be38f91b 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_InsertData.java +++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_InsertData.java @@ -1,11 +1,11 @@ package com.jd.blockchain.sdk.samples; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoUtils; import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; import com.jd.blockchain.crypto.asymmetric.SignatureFunction; import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.impl.AsymmtricCryptographyImpl; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeyPair; import com.jd.blockchain.ledger.PreparedTransaction; @@ -25,7 +25,7 @@ public class SDKDemo_InsertData { public static BlockchainKeyPair CLIENT_CERT = BlockchainKeyGenerator.getInstance().generate(CryptoAlgorithm.ED25519); - public static AsymmetricCryptography asymmetricCryptography = new AsymmtricCryptographyImpl(); + public static AsymmetricCryptography asymmetricCryptography = CryptoUtils.asymmCrypto(); /** * 演示数据写入的调用过程; diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Params.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Params.java index 59c6bcfc..491abef8 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Params.java +++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Params.java @@ -8,8 +8,8 @@ */ package com.jd.blockchain.sdk.samples; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.tools.keygen.KeyGenCommand; /** diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterTest.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterTest.java index 3701e6fa..5148f62b 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterTest.java +++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterTest.java @@ -9,9 +9,9 @@ package com.jd.blockchain.sdk.samples; import com.jd.blockchain.binaryproto.DataContractRegistry; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.*; import com.jd.blockchain.sdk.BlockchainService; diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterUser.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterUser.java index fe5c18bc..859163df 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterUser.java +++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterUser.java @@ -9,9 +9,9 @@ package com.jd.blockchain.sdk.samples; import com.jd.blockchain.binaryproto.DataContractRegistry; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.*; import com.jd.blockchain.sdk.BlockchainService; diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_User.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_User.java index e6bb4e81..59c76c68 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_User.java +++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_User.java @@ -1,12 +1,15 @@ package com.jd.blockchain.sdk.samples; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoUtils; import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; import com.jd.blockchain.crypto.asymmetric.SignatureFunction; import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.impl.AsymmtricCryptographyImpl; -import com.jd.blockchain.ledger.*; +import com.jd.blockchain.ledger.BlockchainKeyGenerator; +import com.jd.blockchain.ledger.BlockchainKeyPair; +import com.jd.blockchain.ledger.PreparedTransaction; +import com.jd.blockchain.ledger.TransactionTemplate; import com.jd.blockchain.sdk.BlockchainTransactionService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; import com.jd.blockchain.utils.net.NetworkAddress; @@ -15,7 +18,7 @@ public class SDKDemo_User { public static BlockchainKeyPair CLIENT_CERT = BlockchainKeyGenerator.getInstance().generate(); - public static AsymmetricCryptography asymmetricCryptography = new AsymmtricCryptographyImpl(); + public static AsymmetricCryptography asymmetricCryptography = CryptoUtils.asymmCrypto(); /** * 生成一个区块链用户,并注册到区块链; diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_BatchInsertData_Test_.java b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_BatchInsertData_Test_.java index 933cf1ff..ee851828 100644 --- a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_BatchInsertData_Test_.java +++ b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_BatchInsertData_Test_.java @@ -8,26 +8,34 @@ */ package test.com.jd.blockchain.sdk.test; +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoUtils; import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; import com.jd.blockchain.crypto.asymmetric.SignatureFunction; import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.impl.AsymmtricCryptographyImpl; -import com.jd.blockchain.ledger.*; +import com.jd.blockchain.ledger.BlockchainKeyGenerator; +import com.jd.blockchain.ledger.BlockchainKeyPair; +import com.jd.blockchain.ledger.EndpointRequest; +import com.jd.blockchain.ledger.NodeRequest; +import com.jd.blockchain.ledger.PreparedTransaction; +import com.jd.blockchain.ledger.TransactionContent; +import com.jd.blockchain.ledger.TransactionContentBody; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.ledger.TransactionResponse; +import com.jd.blockchain.ledger.TransactionState; +import com.jd.blockchain.ledger.TransactionTemplate; import com.jd.blockchain.ledger.data.TxResponseMessage; -import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.BlockchainTransactionService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; import com.jd.blockchain.utils.codec.Base58Utils; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - /** * 插入数据测试 * @author shaozhuguang @@ -37,6 +45,8 @@ import static org.junit.Assert.assertTrue; public class SDK_GateWay_BatchInsertData_Test_ { + String ledgerHash = ""; + private BlockchainKeyPair CLIENT_CERT = null; private String GATEWAY_IPADDR = null; @@ -45,9 +55,9 @@ public class SDK_GateWay_BatchInsertData_Test_ { private boolean SECURE; - private BlockchainService service; + private BlockchainTransactionService service; - private AsymmetricCryptography asymmetricCryptography = new AsymmtricCryptographyImpl(); + private AsymmetricCryptography asymmetricCryptography = CryptoUtils.asymmCrypto(); @Before public void init() { @@ -55,15 +65,22 @@ public class SDK_GateWay_BatchInsertData_Test_ { GATEWAY_IPADDR = "127.0.0.1"; GATEWAY_PORT = 8000; SECURE = false; - GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect( - GATEWAY_IPADDR, GATEWAY_PORT, SECURE, CLIENT_CERT); + GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect(GATEWAY_IPADDR, GATEWAY_PORT, SECURE, + CLIENT_CERT); service = serviceFactory.getBlockchainService(); + + DataContractRegistry.register(TransactionContent.class); + DataContractRegistry.register(TransactionContentBody.class); + DataContractRegistry.register(TransactionRequest.class); + DataContractRegistry.register(NodeRequest.class); + DataContractRegistry.register(EndpointRequest.class); + DataContractRegistry.register(TransactionResponse.class); } @Test public void batchInsertData_Test() { - HashDigest ledgerHash = service.getLedgerHashs()[0]; - // 在本地定义TX模板 + HashDigest ledgerHash = getLedgerHash(); + // 在本地定义注册账号的 TX; TransactionTemplate txTemp = service.newTransaction(ledgerHash); // -------------------------------------- @@ -77,7 +94,6 @@ public class SDK_GateWay_BatchInsertData_Test_ { String key2 = "jd_key2"; byte[] val2 = "www.jd.com".getBytes(); - // 版本号根据实际情况进行调整 txTemp.dataAccount(dataAccount).set(key1, val1, -1); txTemp.dataAccount(dataAccount).set(key2, val2, -1); @@ -91,11 +107,38 @@ public class SDK_GateWay_BatchInsertData_Test_ { // 提交交易; TransactionResponse transactionResponse = prepTx.commit(); - assertTrue(transactionResponse.isSuccess()); + // 期望返回结果 + TransactionResponse expectResp = initResponse(); + + System.out.println("---------- assert start ----------"); + assertEquals(expectResp.isSuccess(), transactionResponse.isSuccess()); + assertEquals(expectResp.getExecutionState(), transactionResponse.getExecutionState()); + assertEquals(expectResp.getContentHash(), transactionResponse.getContentHash()); + assertEquals(expectResp.getBlockHeight(), transactionResponse.getBlockHeight()); + assertEquals(expectResp.getBlockHash(), transactionResponse.getBlockHash()); + System.out.println("---------- assert OK ----------"); } + private HashDigest getLedgerHash() { + byte[] hashBytes = Base58Utils.decode(ledgerHash); + return new HashDigest(hashBytes); + } + + private CryptoKeyPair getSponsorKey() { SignatureFunction signatureFunction = asymmetricCryptography.getSignatureFunction(CryptoAlgorithm.ED25519); return signatureFunction.generateKeyPair(); } + + private TransactionResponse initResponse() { + HashDigest contentHash = new HashDigest(CryptoAlgorithm.SHA256, "contentHash".getBytes()); + HashDigest blockHash = new HashDigest(CryptoAlgorithm.SHA256, "blockHash".getBytes()); + long blockHeight = 9998L; + + TxResponseMessage resp = new TxResponseMessage(contentHash); + resp.setBlockHash(blockHash); + resp.setBlockHeight(blockHeight); + resp.setExecutionState(TransactionState.SUCCESS); + return resp; + } } \ No newline at end of file diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_ContractDeploy_Test_.java b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_ContractDeploy_Test_.java deleted file mode 100644 index 41b30fdd..00000000 --- a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_ContractDeploy_Test_.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.sdk.test.SDK_GateWay_InsertData_Test - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/9/4 上午11:06 - * Description: 插入数据测试 - */ -package test.com.jd.blockchain.sdk.test; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; -import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.SignatureFunction; -import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.impl.AsymmtricCryptographyImpl; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.data.TxResponseMessage; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.BlockchainTransactionService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.utils.io.FileUtils; -import org.junit.Before; -import org.junit.Test; - -import java.io.File; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * 插入数据测试 - * @author shaozhuguang - * @create 2018/9/4 - * @since 1.0.0 - */ - -public class SDK_GateWay_ContractDeploy_Test_ { - - private BlockchainKeyPair CLIENT_CERT = null; - - private String GATEWAY_IPADDR = null; - - private int GATEWAY_PORT; - - private boolean SECURE; - - private BlockchainService service; - - private String CONTRACT_FILE = null; - - private AsymmetricCryptography asymmetricCryptography = new AsymmtricCryptographyImpl(); - - @Before - public void init() { - CLIENT_CERT = BlockchainKeyGenerator.getInstance().generate(CryptoAlgorithm.ED25519); - GATEWAY_IPADDR = "127.0.0.1"; - GATEWAY_PORT = 8000; - SECURE = false; - GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect(GATEWAY_IPADDR, GATEWAY_PORT, SECURE, - CLIENT_CERT); - service = serviceFactory.getBlockchainService(); - } - - @Test - public void contractDeploy_Test() { - HashDigest ledgerHash = service.getLedgerHashs()[0]; - // 在本地定义TX模板 - TransactionTemplate txTemp = service.newTransaction(ledgerHash); - - // 合约内容读取 - byte[] contractBytes = FileUtils.readBytes(new File(CONTRACT_FILE)); - - // 生成用户 - BlockchainIdentityData blockchainIdentity = new BlockchainIdentityData(getSponsorKey().getPubKey()); - - // 发布合约 - txTemp.contracts().deploy(blockchainIdentity, contractBytes); - - // TX 准备就绪; - PreparedTransaction prepTx = txTemp.prepare(); - - // 使用私钥进行签名; - CryptoKeyPair keyPair = getSponsorKey(); - - prepTx.sign(keyPair); - - // 提交交易; - TransactionResponse transactionResponse = prepTx.commit(); - - assertTrue(transactionResponse.isSuccess()); - - // 打印合约地址 - System.out.println(blockchainIdentity.getAddress().toBase58()); - } - - private CryptoKeyPair getSponsorKey() { - SignatureFunction signatureFunction = asymmetricCryptography.getSignatureFunction(CryptoAlgorithm.ED25519); - return signatureFunction.generateKeyPair(); - } -} \ No newline at end of file diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_ContractExec_Test_.java b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_ContractExec_Test_.java deleted file mode 100644 index ab6b8df3..00000000 --- a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_ContractExec_Test_.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Copyright: Copyright 2016-2020 JD.COM All Right Reserved - * FileName: test.com.jd.blockchain.sdk.test.SDK_GateWay_InsertData_Test - * Author: shaozhuguang - * Department: 区块链研发部 - * Date: 2018/9/4 上午11:06 - * Description: 插入数据测试 - */ -package test.com.jd.blockchain.sdk.test; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.crypto.CryptoAlgorithm; -import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; -import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.SignatureFunction; -import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.impl.AsymmtricCryptographyImpl; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.data.TxResponseMessage; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.BlockchainTransactionService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * 插入数据测试 - * @author shaozhuguang - * @create 2018/9/4 - * @since 1.0.0 - */ - -public class SDK_GateWay_ContractExec_Test_ { - - private BlockchainKeyPair CLIENT_CERT = null; - - private String GATEWAY_IPADDR = null; - - private int GATEWAY_PORT; - - private boolean SECURE; - - private BlockchainService service; - - private AsymmetricCryptography asymmetricCryptography = new AsymmtricCryptographyImpl(); - - @Before - public void init() { - CLIENT_CERT = BlockchainKeyGenerator.getInstance().generate(CryptoAlgorithm.ED25519); - GATEWAY_IPADDR = "127.0.0.1"; - GATEWAY_PORT = 8000; - SECURE = false; - GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect( - GATEWAY_IPADDR, GATEWAY_PORT, SECURE, CLIENT_CERT); - service = serviceFactory.getBlockchainService(); - } - - @Test - public void contractExec_Test() { - HashDigest ledgerHash = getLedgerHash(); - // 在本地定义TX模板 - TransactionTemplate txTemp = service.newTransaction(ledgerHash); - - // 合约地址 - String contractAddressBase58 = ""; - - // Event - String event = ""; - - // args(注意参数的格式) - byte[] args = "20##30##abc".getBytes(); - - - // 提交合约执行代码 - txTemp.contractEvents().send(contractAddressBase58, event, args); - - // TX 准备就绪; - PreparedTransaction prepTx = txTemp.prepare(); - - // 生成私钥并使用私钥进行签名; - CryptoKeyPair keyPair = getSponsorKey(); - - prepTx.sign(keyPair); - - // 提交交易; - TransactionResponse transactionResponse = prepTx.commit(); - - assertTrue(transactionResponse.isSuccess()); - } - - private HashDigest getLedgerHash() { - HashDigest ledgerHash = new HashDigest(CryptoAlgorithm.SHA256, "jd-gateway".getBytes()); - return ledgerHash; - } - - - private CryptoKeyPair getSponsorKey() { - SignatureFunction signatureFunction = asymmetricCryptography.getSignatureFunction(CryptoAlgorithm.ED25519); - return signatureFunction.generateKeyPair(); - } -} \ No newline at end of file diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_DataAccount_Test_.java b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_DataAccount_Test_.java index 3be8eb27..b203d2e4 100644 --- a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_DataAccount_Test_.java +++ b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_DataAccount_Test_.java @@ -8,23 +8,30 @@ */ package test.com.jd.blockchain.sdk.test; +import org.junit.Before; +import org.junit.Test; + import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoUtils; import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; import com.jd.blockchain.crypto.asymmetric.SignatureFunction; import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.impl.AsymmtricCryptographyImpl; -import com.jd.blockchain.ledger.*; +import com.jd.blockchain.ledger.BlockchainKeyGenerator; +import com.jd.blockchain.ledger.BlockchainKeyPair; +import com.jd.blockchain.ledger.EndpointRequest; +import com.jd.blockchain.ledger.NodeRequest; +import com.jd.blockchain.ledger.PreparedTransaction; +import com.jd.blockchain.ledger.TransactionContent; +import com.jd.blockchain.ledger.TransactionContentBody; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.ledger.TransactionResponse; +import com.jd.blockchain.ledger.TransactionState; +import com.jd.blockchain.ledger.TransactionTemplate; import com.jd.blockchain.ledger.data.TxResponseMessage; import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.BlockchainTransactionService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * 插入数据测试 @@ -45,7 +52,7 @@ public class SDK_GateWay_DataAccount_Test_ { private BlockchainService service; - private AsymmetricCryptography asymmetricCryptography = new AsymmtricCryptographyImpl(); + private AsymmetricCryptography asymmetricCryptography = CryptoUtils.asymmCrypto(); @Before public void init() { @@ -56,21 +63,33 @@ public class SDK_GateWay_DataAccount_Test_ { GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect(GATEWAY_IPADDR, GATEWAY_PORT, SECURE, CLIENT_CERT); service = serviceFactory.getBlockchainService(); + + DataContractRegistry.register(TransactionContent.class); + DataContractRegistry.register(TransactionContentBody.class); + DataContractRegistry.register(TransactionRequest.class); + DataContractRegistry.register(NodeRequest.class); + DataContractRegistry.register(EndpointRequest.class); + DataContractRegistry.register(TransactionResponse.class); } @Test public void registerDataAccount_Test() { +// HashDigest ledgerHash = getLedgerHash(); HashDigest[] ledgerHashs = service.getLedgerHashs(); - // 在本地定义TX模板 + // 在本地定义注册账号的 TX; TransactionTemplate txTemp = service.newTransaction(ledgerHashs[0]); +// SignatureFunction signatureFunction = getSignatureFunction(); +// +// CryptoKeyPair cryptoKeyPair = signatureFunction.generateKeyPair(); + //existed signer CryptoKeyPair keyPair = new BlockchainKeyPair(SDK_GateWay_KeyPair_Para.pubKey1, SDK_GateWay_KeyPair_Para.privkey1); - BlockchainKeyPair dataAccount = BlockchainKeyGenerator.getInstance().generate(); + BlockchainKeyPair dataAcount = BlockchainKeyGenerator.getInstance().generate(); // 注册 - txTemp.dataAccounts().register(dataAccount.getIdentity()); + txTemp.dataAccounts().register(dataAcount.getIdentity()); // TX 准备就绪; PreparedTransaction prepTx = txTemp.prepare(); @@ -80,10 +99,40 @@ public class SDK_GateWay_DataAccount_Test_ { // 提交交易; TransactionResponse transactionResponse = prepTx.commit(); - assertTrue(transactionResponse.isSuccess()); +// // 期望返回结果 +// TransactionResponse expectResp = initResponse(); +// +// System.out.println("---------- assert start ----------"); +// assertEquals(expectResp.isSuccess(), transactionResponse.isSuccess()); +// assertEquals(expectResp.getExecutionState(), transactionResponse.getExecutionState()); +// assertEquals(expectResp.getContentHash(), transactionResponse.getContentHash()); +// assertEquals(expectResp.getBlockHeight(), transactionResponse.getBlockHeight()); +// assertEquals(expectResp.getBlockHash(), transactionResponse.getBlockHash()); +// System.out.println("---------- assert OK ----------"); + } + + private HashDigest getLedgerHash() { + HashDigest ledgerHash = new HashDigest(CryptoAlgorithm.SHA256, "jd-gateway".getBytes()); + return ledgerHash; } private SignatureFunction getSignatureFunction() { return asymmetricCryptography.getSignatureFunction(CryptoAlgorithm.ED25519); } + + private CryptoKeyPair getSponsorKey() { + return getSignatureFunction().generateKeyPair(); + } + + private TransactionResponse initResponse() { + HashDigest contentHash = new HashDigest(CryptoAlgorithm.SHA256, "contentHash".getBytes()); + HashDigest blockHash = new HashDigest(CryptoAlgorithm.SHA256, "blockHash".getBytes()); + long blockHeight = 9998L; + + TxResponseMessage resp = new TxResponseMessage(contentHash); + resp.setBlockHash(blockHash); + resp.setBlockHeight(blockHeight); + resp.setExecutionState(TransactionState.SUCCESS); + return resp; + } } \ No newline at end of file diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_InsertData_Test_.java b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_InsertData_Test_.java index 668b540c..578c8143 100644 --- a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_InsertData_Test_.java +++ b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_InsertData_Test_.java @@ -8,27 +8,32 @@ */ package test.com.jd.blockchain.sdk.test; +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoUtils; import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; import com.jd.blockchain.crypto.asymmetric.SignatureFunction; import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.impl.AsymmtricCryptographyImpl; -import com.jd.blockchain.ledger.*; +import com.jd.blockchain.ledger.BlockchainKeyGenerator; +import com.jd.blockchain.ledger.BlockchainKeyPair; +import com.jd.blockchain.ledger.EndpointRequest; +import com.jd.blockchain.ledger.NodeRequest; +import com.jd.blockchain.ledger.PreparedTransaction; +import com.jd.blockchain.ledger.TransactionContent; +import com.jd.blockchain.ledger.TransactionContentBody; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.ledger.TransactionResponse; +import com.jd.blockchain.ledger.TransactionState; +import com.jd.blockchain.ledger.TransactionTemplate; import com.jd.blockchain.ledger.data.TxResponseMessage; -import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.BlockchainTransactionService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.sdk.samples.SDKDemo_InsertData; -import com.jd.blockchain.utils.io.ByteArray; -import com.jd.blockchain.utils.net.NetworkAddress; - -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * 插入数据测试 @@ -47,9 +52,9 @@ public class SDK_GateWay_InsertData_Test_ { private boolean SECURE; - private BlockchainService service; + private BlockchainTransactionService service; - private AsymmetricCryptography asymmetricCryptography = new AsymmtricCryptographyImpl(); + private AsymmetricCryptography asymmetricCryptography = CryptoUtils.asymmCrypto(); @Before public void init() { @@ -60,12 +65,19 @@ public class SDK_GateWay_InsertData_Test_ { GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect(GATEWAY_IPADDR, GATEWAY_PORT, SECURE, CLIENT_CERT); service = serviceFactory.getBlockchainService(); + + DataContractRegistry.register(TransactionContent.class); + DataContractRegistry.register(TransactionContentBody.class); + DataContractRegistry.register(TransactionRequest.class); + DataContractRegistry.register(NodeRequest.class); + DataContractRegistry.register(EndpointRequest.class); + DataContractRegistry.register(TransactionResponse.class); } @Test public void insertData_Test() { - HashDigest ledgerHash = service.getLedgerHashs()[0]; - // 在本地定义TX模板 + HashDigest ledgerHash = getLedgerHash(); + // 在本地定义注册账号的 TX; TransactionTemplate txTemp = service.newTransaction(ledgerHash); // -------------------------------------- @@ -74,7 +86,6 @@ public class SDK_GateWay_InsertData_Test_ { String dataAccount = "GGhhreGeasdfasfUUfehf9932lkae99ds66jf=="; String dataKey = "jd_code"; - byte[] dataVal = "www.jd.com".getBytes(); txTemp.dataAccount(dataAccount).set(dataKey, dataVal, -1); @@ -88,11 +99,39 @@ public class SDK_GateWay_InsertData_Test_ { // 提交交易; TransactionResponse transactionResponse = prepTx.commit(); - assertTrue(transactionResponse.isSuccess()); + + // 期望返回结果 + TransactionResponse expectResp = initResponse(); + + System.out.println("---------- assert start ----------"); + assertEquals(expectResp.isSuccess(), transactionResponse.isSuccess()); + assertEquals(expectResp.getExecutionState(), transactionResponse.getExecutionState()); + assertEquals(expectResp.getContentHash(), transactionResponse.getContentHash()); + assertEquals(expectResp.getBlockHeight(), transactionResponse.getBlockHeight()); + assertEquals(expectResp.getBlockHash(), transactionResponse.getBlockHash()); + System.out.println("---------- assert OK ----------"); } + private HashDigest getLedgerHash() { + HashDigest ledgerHash = new HashDigest(CryptoAlgorithm.SHA256, "jd-gateway".getBytes()); + return ledgerHash; + } + + private CryptoKeyPair getSponsorKey() { SignatureFunction signatureFunction = asymmetricCryptography.getSignatureFunction(CryptoAlgorithm.ED25519); return signatureFunction.generateKeyPair(); } + + private TransactionResponse initResponse() { + HashDigest contentHash = new HashDigest(CryptoAlgorithm.SHA256, "contentHash".getBytes()); + HashDigest blockHash = new HashDigest(CryptoAlgorithm.SHA256, "blockHash".getBytes()); + long blockHeight = 9998L; + + TxResponseMessage resp = new TxResponseMessage(contentHash); + resp.setBlockHash(blockHash); + resp.setBlockHeight(blockHeight); + resp.setExecutionState(TransactionState.SUCCESS); + return resp; + } } \ No newline at end of file diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_KeyPair_Para.java b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_KeyPair_Para.java index 94dddf05..916a3460 100644 --- a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_KeyPair_Para.java +++ b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_KeyPair_Para.java @@ -1,7 +1,7 @@ package test.com.jd.blockchain.sdk.test; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.tools.keygen.KeyGenCommand; /** diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Query_Test_.java b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Query_Test_.java index f68ed9ae..d3782d98 100644 --- a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Query_Test_.java +++ b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_Query_Test_.java @@ -8,19 +8,41 @@ */ package test.com.jd.blockchain.sdk.test; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.sdk.client.ClientOperationUtil; -import org.apache.commons.codec.binary.Hex; import org.junit.Before; import org.junit.Test; +import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoUtils; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; +import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; +import com.jd.blockchain.crypto.asymmetric.SignatureDigest; +import com.jd.blockchain.crypto.asymmetric.SignatureFunction; import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.crypto.impl.AsymmtricCryptographyImpl; +import com.jd.blockchain.crypto.serialize.ByteArrayObjectDeserializer; +import com.jd.blockchain.crypto.serialize.ByteArrayObjectSerializer; +import com.jd.blockchain.ledger.AccountHeader; +import com.jd.blockchain.ledger.BlockchainKeyGenerator; +import com.jd.blockchain.ledger.BlockchainKeyPair; +import com.jd.blockchain.ledger.DigitalSignature; +import com.jd.blockchain.ledger.EndpointRequest; +import com.jd.blockchain.ledger.KVDataEntry; +import com.jd.blockchain.ledger.LedgerBlock; +import com.jd.blockchain.ledger.LedgerInfo; +import com.jd.blockchain.ledger.LedgerTransaction; +import com.jd.blockchain.ledger.NodeRequest; +import com.jd.blockchain.ledger.ParticipantNode; +import com.jd.blockchain.ledger.Transaction; +import com.jd.blockchain.ledger.TransactionContent; +import com.jd.blockchain.ledger.TransactionContentBody; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.ledger.TransactionResponse; +import com.jd.blockchain.ledger.TransactionState; +import com.jd.blockchain.ledger.data.TxResponseMessage; import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; - +import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils; /** * 插入数据测试 @@ -31,6 +53,16 @@ import com.jd.blockchain.sdk.client.GatewayServiceFactory; public class SDK_GateWay_Query_Test_ { + private static Class[] byteArrayClasss = new Class[]{HashDigest.class, PubKey.class, SignatureDigest.class}; + + static { + for (Class byteArrayClass : byteArrayClasss) { + JSONSerializeUtils.configSerialization(byteArrayClass, + ByteArrayObjectSerializer.getInstance(byteArrayClass), + ByteArrayObjectDeserializer.getInstance(byteArrayClass)); + } + } + private BlockchainKeyPair CLIENT_CERT = null; private String GATEWAY_IPADDR = null; @@ -41,169 +73,82 @@ public class SDK_GateWay_Query_Test_ { private BlockchainService service; + private AsymmetricCryptography asymmetricCryptography = CryptoUtils.asymmCrypto(); + @Before public void init() { CLIENT_CERT = BlockchainKeyGenerator.getInstance().generate(CryptoAlgorithm.ED25519); GATEWAY_IPADDR = "127.0.0.1"; - GATEWAY_PORT = 8081; + GATEWAY_PORT = 11000; SECURE = false; GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect(GATEWAY_IPADDR, GATEWAY_PORT, SECURE, CLIENT_CERT); service = serviceFactory.getBlockchainService(); + + DataContractRegistry.register(TransactionContent.class); + DataContractRegistry.register(TransactionContentBody.class); + DataContractRegistry.register(TransactionRequest.class); + DataContractRegistry.register(NodeRequest.class); + DataContractRegistry.register(EndpointRequest.class); + DataContractRegistry.register(TransactionResponse.class); } @Test public void query_Test() { - // Get First Ledger - HashDigest ledgerHash = service.getLedgerHashs()[0]; - System.out.println("ledgerHash=" + ledgerHash.toBase58()); + HashDigest ledgerHash = service.getLedgerHashs()[0];; +// ParserConfig.global.setAutoTypeSupport(true); - // Show Ledger Info LedgerInfo ledgerInfo = service.getLedger(ledgerHash); - - // Get highest block height - long latestBlockHeight = ledgerInfo.getLatestBlockHeight(); - - // Get highest block hash - HashDigest latestBlockHash = ledgerInfo.getLatestBlockHash(); - - System.out.println("latestBlockHeight=" + latestBlockHeight); - - System.out.println("latestBlockHash=" + latestBlockHash.toBase58()); - - System.out.println("LedgerHash=" + ledgerInfo.getHash().toBase58()); - - // Get newest block - LedgerBlock latestBlock = service.getBlock(ledgerHash, latestBlockHeight); - + long ledgerNumber = ledgerInfo.getLatestBlockHeight(); + System.out.println(ledgerNumber); + HashDigest hashDigest = ledgerInfo.getHash(); + System.out.println(hashDigest); +// 最新区块; + LedgerBlock latestBlock = service.getBlock(ledgerHash, ledgerNumber); System.out.println("latestBlock.Hash=" + latestBlock.getHash()); - - // Get total contract size - long count = service.getContractCount(ledgerHash, latestBlockHeight); - + long count = service.getContractCount(ledgerHash, 3L); System.out.println("contractCount=" + count); - - count = service.getContractCount(ledgerHash, latestBlockHash); - + count = service.getContractCount(ledgerHash, hashDigest); System.out.println("contractCount=" + count); + AccountHeader contract = service.getContract(ledgerHash, "12345678"); + System.out.println(contract); - if (count != 0) { - AccountHeader[] accountHeaders = service.getContractAccounts(ledgerHash, 0, (int)count); - for (AccountHeader accountHeader : accountHeaders) { - String contractAddress = accountHeader.getAddress().toBase58(); - System.out.println("Contract address = " + contractAddress); - // Get one contract by contract address - AccountHeader contract = service.getContract(ledgerHash, contractAddress); - } - } - - // Get other block info - LedgerBlock block = service.getBlock(ledgerHash, latestBlockHeight - 1); + LedgerBlock block = service.getBlock(ledgerHash, hashDigest); System.out.println("block.Hash=" + block.getHash()); - // Get Total DataAccount Size - count = service.getDataAccountCount(ledgerHash, latestBlockHeight); - + count = service.getDataAccountCount(ledgerHash, 123456); System.out.println("dataAccountCount=" + count); - - count = service.getDataAccountCount(ledgerHash, latestBlockHash); - + count = service.getDataAccountCount(ledgerHash, hashDigest); System.out.println("dataAccountCount=" + count); - String queryDataAccountAddress = null; - - if (count > 0) { - AccountHeader[] accountHeaders = service.getDataAccounts(ledgerHash, 0, (int)count); - for (AccountHeader accountHeader : accountHeaders) { - String dataAccountAddress = accountHeader.getAddress().toBase58(); - System.out.println("DataAccount address = " + dataAccountAddress); - // Get one Data Account by address - AccountHeader dataAccount = service.getDataAccount(ledgerHash, dataAccountAddress); - queryDataAccountAddress = dataAccountAddress; - } - } + AccountHeader dataAccount = service.getDataAccount(ledgerHash, "1245633"); + System.out.println(dataAccount.getAddress()); - // Get total transaction size - count = service.getTransactionCount(ledgerHash, latestBlockHash); + count = service.getTransactionCount(ledgerHash, hashDigest); System.out.println("transactionCount=" + count); - - count = service.getTransactionCount(ledgerHash, latestBlockHeight); + count = service.getTransactionCount(ledgerHash, 12456); System.out.println("transactionCount=" + count); - // Get transaction list - LedgerTransaction[] txList = service.getTransactions(ledgerHash, 0, 0, 100); + LedgerTransaction[] txList = service.getTransactions(ledgerHash, ledgerNumber, 0, 100); for (LedgerTransaction ledgerTransaction : txList) { - System.out.println("transaction.executionState=" + ledgerTransaction.getExecutionState()); -// System.out.println("transaction.hash=" + ledgerTransaction.getHash().toBase58()); - TransactionContent txContent = ledgerTransaction.getTransactionContent(); - System.out.println("transactionContent.hash=" + txContent.getHash().toBase58()); - Operation[] operations = txContent.getOperations(); - if (operations != null && operations.length > 0) { - for (Operation operation : operations) { - operation = ClientOperationUtil.read(operation); - if (operation instanceof DataAccountRegisterOperation) { - DataAccountRegisterOperation daro = (DataAccountRegisterOperation) operation; - BlockchainIdentity blockchainIdentity = daro.getAccountID(); - System.out.println("register account = " + blockchainIdentity.getAddress().toBase58()); - } else if (operation instanceof UserRegisterOperation) { - UserRegisterOperation uro = (UserRegisterOperation) operation; - BlockchainIdentity blockchainIdentity = uro.getUserID(); - System.out.println("register user = " + blockchainIdentity.getAddress().toBase58()); - } else if (operation instanceof LedgerInitOperation) { - - LedgerInitOperation ledgerInitOperation = (LedgerInitOperation)operation; - LedgerInitSetting ledgerInitSetting = ledgerInitOperation.getInitSetting(); - - System.out.println(Hex.encodeHexString(ledgerInitSetting.getLedgerSeed())); - System.out.println(ledgerInitSetting.getConsensusProvider()); - System.out.println(ledgerInitSetting.getConsensusSettings().toBase58()); - - ParticipantNode[] participantNodes = ledgerInitSetting.getConsensusParticipants(); - if (participantNodes != null && participantNodes.length > 0) { - for (ParticipantNode participantNode : participantNodes) { - System.out.println("participantNode.id=" + participantNode.getId()); - System.out.println("participantNode.name=" + participantNode.getName()); - System.out.println("participantNode.address=" + participantNode.getAddress()); - System.out.println("participantNode.pubKey=" + participantNode.getPubKey().toBase58()); - } - } - - } else if (operation instanceof ContractCodeDeployOperation) { - ContractCodeDeployOperation ccdo = (ContractCodeDeployOperation) operation; - BlockchainIdentity blockchainIdentity = ccdo.getContractID(); - System.out.println("deploy contract = " + blockchainIdentity.getAddress()); - } else if (operation instanceof ContractEventSendOperation) { - ContractEventSendOperation ceso = (ContractEventSendOperation) operation; - System.out.println("event = " + ceso.getEvent()); - System.out.println("execute contract address = " + ceso.getContractAddress().toBase58()); - } else if (operation instanceof DataAccountKVSetOperation) { - DataAccountKVSetOperation.KVWriteEntry[] kvWriteEntries = - ((DataAccountKVSetOperation) operation).getWriteSet(); - if (kvWriteEntries != null && kvWriteEntries.length > 0) { - for (DataAccountKVSetOperation.KVWriteEntry kvWriteEntry : kvWriteEntries) { - System.out.println("writeSet.key=" + kvWriteEntry.getKey()); - BytesValue bytesValue = kvWriteEntry.getValue(); - DataType dataType = bytesValue.getType(); - Object showVal = ClientOperationUtil.readValueByBytesValue(bytesValue); - System.out.println("writeSet.value=" + showVal); - System.out.println("writeSet.type=" + dataType); - System.out.println("writeSet.version=" + kvWriteEntry.getExpectedVersion()); - } - } - } - } - } + System.out.println("ledgerTransaction.Hash=" + ledgerTransaction.getHash()); } - // Get txs by block height - txList = service.getTransactions(ledgerHash, latestBlockHash, 0, 100); + txList = service.getTransactions(ledgerHash, hashDigest, 0, 100); for (LedgerTransaction ledgerTransaction : txList) { System.out.println("ledgerTransaction.Hash=" + ledgerTransaction.getHash()); } + Transaction tx = service.getTransactionByContentHash(ledgerHash, hashDigest); + DigitalSignature[] signatures = tx.getEndpointSignatures(); + for (DigitalSignature signature : signatures) { + System.out.println(signature.getDigest().getAlgorithm()); + } + System.out.println("transaction.blockHeight=" + tx.getBlockHeight()); + System.out.println("transaction.executionState=" + tx.getExecutionState()); + - // Get total ParticipantNode array ParticipantNode[] participants = service.getConsensusParticipants(ledgerHash); for (ParticipantNode participant : participants) { System.out.println("participant.name=" + participant.getName()); @@ -214,27 +159,47 @@ public class SDK_GateWay_Query_Test_ { System.out.println("participant.getRawKeyBytes=" + participant.getPubKey().getRawKeyBytes()); System.out.println("participant.algorithm=" + participant.getPubKey().getAlgorithm()); } + + String commerceAccount = "GGhhreGeasdfasfUUfehf9932lkae99ds66jf=="; + String[] objKeys = new String[] { "x001", "x002" }; + KVDataEntry[] kvData = service.getDataEntries(ledgerHash, commerceAccount, objKeys); + for (KVDataEntry kvDatum : kvData) { + System.out.println("kvData.key=" + kvDatum.getKey()); + System.out.println("kvData.version=" + kvDatum.getVersion()); + System.out.println("kvData.value=" + kvDatum.getValue()); + } - // Get total kvs - KVDataEntry[] kvData = service.getDataEntries(ledgerHash, queryDataAccountAddress, 0, 100); - if (kvData != null && kvData.length > 0) { - for (KVDataEntry kvDatum : kvData) { - System.out.println("kvData.key=" + kvDatum.getKey()); - System.out.println("kvData.version=" + kvDatum.getVersion()); - System.out.println("kvData.type=" + kvDatum.getType()); - System.out.println("kvData.value=" + kvDatum.getValue()); - - // Get one kvData by key - KVDataEntry[] kvDataEntries = service.getDataEntries(ledgerHash, - queryDataAccountAddress, kvDatum.getKey()); - - for (KVDataEntry kv : kvDataEntries) { - System.out.println("kv.key=" + kv.getKey()); - System.out.println("kv.version=" + kv.getVersion()); - System.out.println("kv.type=" + kv.getType()); - System.out.println("kv.value=" + kv.getValue()); - } - } + HashDigest[] hashs = service.getLedgerHashs(); + for (HashDigest hash : hashs) { + System.out.println("hash.toBase58=" + hash.toBase58()); } } + + private HashDigest getLedgerHash() { + HashDigest ledgerHash = new HashDigest(CryptoAlgorithm.SHA256, "jd-gateway".getBytes()); + return ledgerHash; + } + + private SignatureFunction getSignatureFunction() { + return asymmetricCryptography.getSignatureFunction(CryptoAlgorithm.ED25519); + } + + private BlockchainKeyPair getSponsorKey() { + SignatureFunction signatureFunction = asymmetricCryptography.getSignatureFunction(CryptoAlgorithm.ED25519); + CryptoKeyPair cryptoKeyPair = signatureFunction.generateKeyPair(); + BlockchainKeyPair blockchainKeyPair = new BlockchainKeyPair(cryptoKeyPair.getPubKey(), cryptoKeyPair.getPrivKey()); + return blockchainKeyPair; + } + + private TransactionResponse initResponse() { + HashDigest contentHash = new HashDigest(CryptoAlgorithm.SHA256, "contentHash".getBytes()); + HashDigest blockHash = new HashDigest(CryptoAlgorithm.SHA256, "blockHash".getBytes()); + long blockHeight = 9998L; + + TxResponseMessage resp = new TxResponseMessage(contentHash); + resp.setBlockHash(blockHash); + resp.setBlockHeight(blockHeight); + resp.setExecutionState(TransactionState.SUCCESS); + return resp; + } } \ No newline at end of file diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_User_Test_.java b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_User_Test_.java index 2a571f85..74892d75 100644 --- a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_User_Test_.java +++ b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_User_Test_.java @@ -8,16 +8,34 @@ */ package test.com.jd.blockchain.sdk.test; -import com.jd.blockchain.crypto.asymmetric.*; -import com.jd.blockchain.crypto.hash.HashDigest; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.sdk.BlockchainService; -import com.jd.blockchain.sdk.client.GatewayServiceFactory; +import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertTrue; +import com.jd.blockchain.binaryproto.DataContractRegistry; +import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoUtils; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; +import com.jd.blockchain.crypto.asymmetric.AsymmetricCryptography; +import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; +import com.jd.blockchain.crypto.asymmetric.SignatureFunction; +import com.jd.blockchain.crypto.hash.HashDigest; +import com.jd.blockchain.ledger.BlockchainKeyGenerator; +import com.jd.blockchain.ledger.BlockchainKeyPair; +import com.jd.blockchain.ledger.EndpointRequest; +import com.jd.blockchain.ledger.NodeRequest; +import com.jd.blockchain.ledger.PreparedTransaction; +import com.jd.blockchain.ledger.TransactionContent; +import com.jd.blockchain.ledger.TransactionContentBody; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.ledger.TransactionResponse; +import com.jd.blockchain.ledger.TransactionState; +import com.jd.blockchain.ledger.TransactionTemplate; +import com.jd.blockchain.ledger.data.TxResponseMessage; +import com.jd.blockchain.sdk.BlockchainService; +import com.jd.blockchain.sdk.client.GatewayServiceFactory; /** * 插入数据测试 @@ -28,8 +46,13 @@ import static org.junit.Assert.assertTrue; public class SDK_GateWay_User_Test_ { - private PrivKey privKey; +// public static final String PASSWORD = SDK_GateWay_KeyPair_Para.PASSWORD; +// +// public static final String[] PUB_KEYS = SDK_GateWay_KeyPair_Para.PUB_KEYS; +// +// public static final String[] PRIV_KEYS = SDK_GateWay_KeyPair_Para.PRIV_KEYS; + private PrivKey privKey; private PubKey pubKey; private BlockchainKeyPair CLIENT_CERT = null; @@ -42,9 +65,21 @@ public class SDK_GateWay_User_Test_ { private BlockchainService service; + private AsymmetricCryptography asymmetricCryptography = CryptoUtils.asymmCrypto(); + @Before public void init() { +// PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); +// PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); +// PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); +// PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); +// +// PubKey pubKey0 = KeyGenCommand.decodePubKey(PUB_KEYS[0]); +// PubKey pubKey1 = KeyGenCommand.decodePubKey(PUB_KEYS[1]); +// PubKey pubKey2 = KeyGenCommand.decodePubKey(PUB_KEYS[2]); +// PubKey pubKey3 = KeyGenCommand.decodePubKey(PUB_KEYS[3]); + privKey = SDK_GateWay_KeyPair_Para.privkey1; pubKey = SDK_GateWay_KeyPair_Para.pubKey1; @@ -52,15 +87,22 @@ public class SDK_GateWay_User_Test_ { GATEWAY_IPADDR = "127.0.0.1"; GATEWAY_PORT = 8081; SECURE = false; - GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect( - GATEWAY_IPADDR, GATEWAY_PORT, SECURE, CLIENT_CERT); + GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect(GATEWAY_IPADDR, GATEWAY_PORT, SECURE, + CLIENT_CERT); service = serviceFactory.getBlockchainService(); + + DataContractRegistry.register(TransactionContent.class); + DataContractRegistry.register(TransactionContentBody.class); + DataContractRegistry.register(TransactionRequest.class); + DataContractRegistry.register(NodeRequest.class); + DataContractRegistry.register(EndpointRequest.class); + DataContractRegistry.register(TransactionResponse.class); } @Test public void registerUser_Test() { HashDigest[] ledgerHashs = service.getLedgerHashs(); - // 在本地定义TX模板 + // 在本地定义注册账号的 TX; TransactionTemplate txTemp = service.newTransaction(ledgerHashs[0]); //existed signer @@ -80,5 +122,38 @@ public class SDK_GateWay_User_Test_ { // 提交交易; TransactionResponse transactionResponse = prepTx.commit(); assertTrue(transactionResponse.isSuccess()); + + // 期望返回结果 +// TransactionResponse expectResp = initResponse(); +// +// System.out.println("---------- assert start ----------"); +// assertEquals(expectResp.isSuccess(), transactionResponse.isSuccess()); +// assertEquals(expectResp.getExecutionState(), transactionResponse.getExecutionState()); +// assertEquals(expectResp.getContentHash(), transactionResponse.getContentHash()); +// assertEquals(expectResp.getBlockHeight(), transactionResponse.getBlockHeight()); +// assertEquals(expectResp.getBlockHash(), transactionResponse.getBlockHash()); +// System.out.println("---------- assert OK ----------"); + } + +// private HashDigest getLedgerHash() { +// byte[] hashBytes = Base58Utils.decode(ledgerHashBase58); +// return new HashDigest(hashBytes); +// } + + private CryptoKeyPair getSponsorKey() { + SignatureFunction signatureFunction = asymmetricCryptography.getSignatureFunction(CryptoAlgorithm.ED25519); + return signatureFunction.generateKeyPair(); + } + + private TransactionResponse initResponse() { + HashDigest contentHash = new HashDigest(CryptoAlgorithm.SHA256, "contentHash".getBytes()); + HashDigest blockHash = new HashDigest(CryptoAlgorithm.SHA256, "blockHash".getBytes()); + long blockHeight = 9998L; + + TxResponseMessage resp = new TxResponseMessage(contentHash); + resp.setBlockHash(blockHash); + resp.setBlockHeight(blockHeight); + resp.setExecutionState(TransactionState.SUCCESS); + return resp; } } \ No newline at end of file diff --git a/source/test/test-integration/pom.xml b/source/test/test-integration/pom.xml index 26906981..dc29dca3 100644 --- a/source/test/test-integration/pom.xml +++ b/source/test/test-integration/pom.xml @@ -48,8 +48,15 @@ io.nats jnats - 2.2.0 + + + com.jd.blockchain + crypto-impl + ${project.version} + test + + diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/IntegrationTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/IntegrationTest.java index 49bbd6b5..63e9bad2 100644 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/IntegrationTest.java +++ b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/IntegrationTest.java @@ -16,9 +16,9 @@ import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; import com.jd.blockchain.ledger.AccountHeader; diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/consensus/ConsensusTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/consensus/ConsensusTest.java index f625fb08..3478478a 100644 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/consensus/ConsensusTest.java +++ b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/consensus/ConsensusTest.java @@ -14,8 +14,8 @@ import org.springframework.core.io.ClassPathResource; import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.ConsensusSettings; +import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/GlobalPerformanceTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/GlobalPerformanceTest.java index a58acae7..fa7ca816 100644 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/GlobalPerformanceTest.java +++ b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/GlobalPerformanceTest.java @@ -16,8 +16,8 @@ import org.springframework.core.io.ClassPathResource; import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.ConsensusSettings; +import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeTest.java index 8c8018b0..ffff2beb 100644 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeTest.java +++ b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeTest.java @@ -14,9 +14,9 @@ import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.LedgerBlock; diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeWebTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeWebTest.java index 647f9024..d8edf300 100644 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeWebTest.java +++ b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeWebTest.java @@ -17,8 +17,8 @@ import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoUtils; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.LedgerBlock; diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerPerformanceTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerPerformanceTest.java index 81bfdf43..4d9eb364 100644 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerPerformanceTest.java +++ b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerPerformanceTest.java @@ -5,8 +5,8 @@ import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.*; import com.jd.blockchain.ledger.core.LedgerDataSet; diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/Utils.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/Utils.java index c54680df..0913c094 100644 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/Utils.java +++ b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/Utils.java @@ -11,8 +11,8 @@ import org.springframework.core.io.ClassPathResource; import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.CryptoSetting; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBase.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBase.java index 6b8476f3..c50462c1 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBase.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBase.java @@ -158,28 +158,7 @@ public class IntegrationBase { return kvResponse; } - public static void testSDK_InsertData_morePage(CryptoKeyPair adminKey, HashDigest ledgerHash, BlockchainService blockchainService, - Bytes dataAccount) { - // 在本地定义注册账号的 TX; - TransactionTemplate txTemp = blockchainService.newTransaction(ledgerHash); - - // -------------------------------------- - // 将商品信息写入到指定的账户中; - // 对象将被序列化为 JSON 形式存储,并基于 JSON 结构建立查询索引; - for(int i=0;i<12;i++){ - String dataKey = "jingdong" + System.currentTimeMillis() + new Random().nextInt(100000); - byte[] dataVal = "www.jd.com".getBytes(); - txTemp.dataAccount(dataAccount).set(dataKey, dataVal, -1); - } - - // TX 准备就绪; - PreparedTransaction prepTx = txTemp.prepare(); - // 使用私钥进行签名; - prepTx.sign(adminKey); - // 提交交易; - prepTx.commit(); - } public static void validKeyPair(IntegrationBase.KeyPairResponse keyPairResponse, LedgerRepository ledgerRepository, KeyPairType keyPairType) { TransactionResponse txResp = keyPairResponse.txResp; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBaseTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBaseTest.java index 3161c06e..79fd67df 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBaseTest.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBaseTest.java @@ -3,8 +3,8 @@ package test.com.jd.blockchain.intgr; import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.ConsensusSettings; +import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; import com.jd.blockchain.ledger.LedgerBlock; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest2.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest2.java index c097cfa6..22bc3324 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest2.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest2.java @@ -18,8 +18,8 @@ import org.springframework.core.io.ClassPathResource; import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.ConsensusSettings; +import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; import com.jd.blockchain.ledger.BlockchainKeyGenerator; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Bftsmart.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Bftsmart.java index 79b9e189..d2cba7a5 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Bftsmart.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Bftsmart.java @@ -1,8 +1,8 @@ package test.com.jd.blockchain.intgr; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.gateway.GatewayConfigProperties; import com.jd.blockchain.ledger.BlockchainKeyPair; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4MQ.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4MQ.java index aae9912d..33f38eea 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4MQ.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4MQ.java @@ -1,8 +1,8 @@ package test.com.jd.blockchain.intgr; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; import com.jd.blockchain.ledger.*; @@ -130,8 +130,6 @@ public class IntegrationTest4MQ { BlockchainKeyPair da = dataAccountResponse.keyPair; IntegrationBase.KvResponse kvResponse = IntegrationBase.testSDK_InsertData(adminKey, ledgerHash, blockchainService, da.getAddress()); validKvWrite(kvResponse, ledgerRepository, blockchainService); - //more page - testSDK_InsertData_morePage(adminKey, ledgerHash, blockchainService, da.getAddress()); } } diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestAll4Redis.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestAll4Redis.java index 35d9ea09..bb0493ad 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestAll4Redis.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestAll4Redis.java @@ -16,9 +16,9 @@ import org.springframework.core.io.ClassPathResource; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; import com.jd.blockchain.ledger.BlockchainKeyGenerator; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestDataAccount.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestDataAccount.java index 24d58608..5e1a284e 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestDataAccount.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestDataAccount.java @@ -16,9 +16,9 @@ import com.alibaba.fastjson.JSON; import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.ConsensusSettings; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; import com.jd.blockchain.ledger.BlockchainKeyGenerator; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartLedgerInit.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartLedgerInit.java index bc1506c4..f2f5d3a8 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartLedgerInit.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartLedgerInit.java @@ -8,9 +8,9 @@ */ package test.com.jd.blockchain.intgr.batch.bftsmart; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.gateway.GatewayConfigProperties; import com.jd.blockchain.ledger.BlockchainKeyPair; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitSettingTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitSettingTest.java index b2cc5198..243be4bc 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitSettingTest.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitSettingTest.java @@ -8,7 +8,7 @@ import java.io.InputStream; import org.junit.Test; import org.springframework.core.io.ClassPathResource; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.tools.initializer.LedgerInitProperties; import com.jd.blockchain.tools.initializer.LedgerInitProperties.ConsensusParticipantConfig; import com.jd.blockchain.tools.keygen.KeyGenCommand; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeTest.java index 9bbb5c9e..a34d4311 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeTest.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeTest.java @@ -19,9 +19,9 @@ import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.LedgerBlock; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4Nodes.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4Nodes.java index 7c6ca543..a61a3342 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4Nodes.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4Nodes.java @@ -3,8 +3,8 @@ package test.com.jd.blockchain.intgr.initializer; import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.*; import com.jd.blockchain.ledger.core.*; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4SingleStepsTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4SingleStepsTest.java index 64e419b2..89712905 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4SingleStepsTest.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4SingleStepsTest.java @@ -23,8 +23,8 @@ import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoUtils; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.LedgerBlock; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/ledger/LedgerBlockGeneratingTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/ledger/LedgerBlockGeneratingTest.java index bd20870a..7251b97a 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/ledger/LedgerBlockGeneratingTest.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/ledger/LedgerBlockGeneratingTest.java @@ -16,8 +16,8 @@ import org.springframework.core.io.ClassPathResource; import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.ConsensusSettings; +import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeyPair; diff --git a/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/service/SettingsInit.java b/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/service/SettingsInit.java index 33820bc1..22c316d4 100644 --- a/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/service/SettingsInit.java +++ b/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/service/SettingsInit.java @@ -13,9 +13,9 @@ import com.jd.blockchain.capability.settings.CapabilitySettings; import com.jd.blockchain.consensus.action.ActionResponse; import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusSettings; import com.jd.blockchain.consensus.bftsmart.BftsmartNodeSettings; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.ContractCodeDeployOperation; import com.jd.blockchain.ledger.ContractEventSendOperation; diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitCommand.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitCommand.java index 4d307b86..d7ddf1b1 100644 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitCommand.java +++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitCommand.java @@ -15,8 +15,8 @@ import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.core.impl.LedgerManager; import com.jd.blockchain.tools.initializer.LedgerBindingConfig.BindingConfig; diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProcess.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProcess.java index c610bfad..5f2fcf2a 100644 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProcess.java +++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProcess.java @@ -3,7 +3,7 @@ package com.jd.blockchain.tools.initializer; import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.consensus.service.ConsensusServiceProvider; -import com.jd.blockchain.crypto.asymmetric.PrivKey; +import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.CryptoSetting; diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProperties.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProperties.java index dd6270f5..805315f9 100644 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProperties.java +++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProperties.java @@ -9,7 +9,7 @@ import java.util.List; import java.util.Properties; import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.ParticipantNode; import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.codec.HexUtils; diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitializeWebController.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitializeWebController.java index 28c21cb8..6c7ddcaa 100644 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitializeWebController.java +++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitializeWebController.java @@ -21,8 +21,8 @@ import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoUtils; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.SignatureDigest; import com.jd.blockchain.crypto.hash.HashDigest; import com.jd.blockchain.ledger.BlockchainIdentity; diff --git a/source/tools/tools-keygen/src/main/java/com/jd/blockchain/tools/keygen/KeyGenCommand.java b/source/tools/tools-keygen/src/main/java/com/jd/blockchain/tools/keygen/KeyGenCommand.java index 4b9f135d..81f2db5c 100644 --- a/source/tools/tools-keygen/src/main/java/com/jd/blockchain/tools/keygen/KeyGenCommand.java +++ b/source/tools/tools-keygen/src/main/java/com/jd/blockchain/tools/keygen/KeyGenCommand.java @@ -10,9 +10,9 @@ import javax.crypto.SecretKey; import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoUtils; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.asymmetric.CryptoKeyPair; -import com.jd.blockchain.crypto.asymmetric.PrivKey; -import com.jd.blockchain.crypto.asymmetric.PubKey; import com.jd.blockchain.utils.ArgumentSet; import com.jd.blockchain.utils.ConsoleUtils; import com.jd.blockchain.utils.ArgumentSet.ArgEntry; diff --git a/source/tools/tools-package/pom.xml b/source/tools/tools-package/pom.xml new file mode 100644 index 00000000..76dc72a4 --- /dev/null +++ b/source/tools/tools-package/pom.xml @@ -0,0 +1,45 @@ + + + + + tools + com.jd.blockchain + 0.9.0-SNAPSHOT + + 4.0.0 + + tools-package + + tools-package + + + UTF-8 + 1.8 + 1.8 + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + make-assembly + package + + single + + + jdchain + + src/main/resources/assemble/assemble.xml + + + + + + + + diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesUtils.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesUtils.java index bc740a3c..fc08418e 100644 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesUtils.java +++ b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/BytesUtils.java @@ -166,6 +166,8 @@ public class BytesUtils { /** * 将 int 值转为4字节的二进制数组; + *

+ * 以“高位在前”的方式转换,即:数值的高位保存在数组地址的低位; * * @param value * 要转换的int整数; @@ -183,23 +185,69 @@ public class BytesUtils { return 4; } -// public static int toBytes(int value, OutputStream out) { -// try { -// out.write((value >>> 24) & 0x00FF); -// out.write((value >>> 16) & 0x00FF); -// out.write((value >>> 8) & 0x00FF); -// out.write(value & 0x00FF); -// return 4; -// } catch (IOException e) { -// throw new RuntimeIOException(e.getMessage(), e); -// } -// } + /** + * 将 int 值转为4字节的二进制数组; + *

+ * 以“高位在后”的方式转换,即:数值的高位保存在数组地址的高位; + * + * @param value + * 要转换的int整数; + * @param bytes + * 要保存转换结果的二进制数组;转换结果将从高位至低位的顺序写入数组从 offset 指定位置开始的4个元素; + * @param offset + * 写入转换结果的起始位置; + * @return 返回写入的长度; + */ + public static int toBytesInReverse(int value, byte[] bytes, int offset) { + bytes[offset] = (byte) (value & 0x00FF); + bytes[offset + 1] = (byte) ((value >>> 8) & 0x00FF); + bytes[offset + 2] = (byte) ((value >>> 16) & 0x00FF); + bytes[offset + 3] = (byte) ((value >>> 24) & 0x00FF); + return 4; + } + + + /** + * 将 int 值转为4字节的二进制数组; + *

+ * 以“高位在后”的方式转换,即:数值的高位保存在数组地址的高位; + * + * @param value + * 要转换的int整数; + * @param bytes + * 要保存转换结果的二进制数组;转换结果将从高位至低位的顺序写入数组从 offset 指定位置开始的4个元素; + * @param offset + * 写入转换结果的起始位置; + * @param len 写入长度;必须大于 0 ,小于等于 4; + * @return 返回写入的长度; + */ + public static int toBytesInReverse(int value, byte[] bytes, int offset, int len) { + int i = 0; + int l = len > 4 ? 4 : len; + for (; i < l; i++) { + bytes[offset + i] = (byte) ((value >>> (8*i)) & 0x00FF); + } + + return i; + } + + + // public static int toBytes(int value, OutputStream out) { + // try { + // out.write((value >>> 24) & 0x00FF); + // out.write((value >>> 16) & 0x00FF); + // out.write((value >>> 8) & 0x00FF); + // out.write(value & 0x00FF); + // return 4; + // } catch (IOException e) { + // throw new RuntimeIOException(e.getMessage(), e); + // } + // } public static void toBytes(short value, byte[] bytes, int offset) { bytes[offset] = (byte) ((value >>> 8) & 0x00FF); bytes[offset + 1] = (byte) (value & 0x00FF); } - public static void toBytes(char value, byte[] bytes, int offset) { bytes[offset] = (byte) ((value >>> 8) & 0x00FF); @@ -229,21 +277,21 @@ public class BytesUtils { return 8; } -// public static int toBytes(long value, OutputStream out) { -// try { -// out.write((int) ((value >>> 56) & 0x00FF)); -// out.write((int) ((value >>> 48) & 0x00FF)); -// out.write((int) ((value >>> 40) & 0x00FF)); -// out.write((int) ((value >>> 32) & 0x00FF)); -// out.write((int) ((value >>> 24) & 0x00FF)); -// out.write((int) ((value >>> 16) & 0x00FF)); -// out.write((int) ((value >>> 8) & 0x00FF)); -// out.write((int) (value & 0x00FF)); -// return 8; -// } catch (IOException e) { -// throw new RuntimeIOException(e.getMessage(), e); -// } -// } + // public static int toBytes(long value, OutputStream out) { + // try { + // out.write((int) ((value >>> 56) & 0x00FF)); + // out.write((int) ((value >>> 48) & 0x00FF)); + // out.write((int) ((value >>> 40) & 0x00FF)); + // out.write((int) ((value >>> 32) & 0x00FF)); + // out.write((int) ((value >>> 24) & 0x00FF)); + // out.write((int) ((value >>> 16) & 0x00FF)); + // out.write((int) ((value >>> 8) & 0x00FF)); + // out.write((int) (value & 0x00FF)); + // return 8; + // } catch (IOException e) { + // throw new RuntimeIOException(e.getMessage(), e); + // } + // } public static byte[] toBytes(String str) { return toBytes(str, DEFAULT_CHARSET); @@ -261,11 +309,11 @@ public class BytesUtils { public static String toString(byte[] bytes) { return toString(bytes, DEFAULT_CHARSET); } - + public static String toString(byte[] bytes, int offset) { return toString(bytes, offset, bytes.length - offset, DEFAULT_CHARSET); } - + public static String toString(byte[] bytes, int offset, int len) { return toString(bytes, offset, len, DEFAULT_CHARSET); } @@ -273,7 +321,7 @@ public class BytesUtils { public static String toString(byte[] bytes, String charset) { return toString(bytes, 0, bytes.length, charset); } - + public static String toString(byte[] bytes, int offset, int len, String charset) { try { if (bytes == null) { @@ -321,17 +369,14 @@ public class BytesUtils { return value; } - - + public static char toChar(byte[] bytes, int offset) { char value = 0; value = (char) ((value | (bytes[offset] & 0xFF)) << 8); value = (char) (value | (bytes[offset + 1] & 0xFF)); - + return value; } - - /** * 按从高位到低位的顺序将指定二进制数组从 offset 参数指定的位置开始的 4 个字节转换为 int 整数; @@ -447,6 +492,17 @@ public class BytesUtils { * @return int */ public static int readInt(InputStream in) { +// try { +// byte[] buf = new byte[4]; +// if (in.read(buf) < 4) { +// throw new IllegalDataException("No enough data to read as integer from the specified input stream!"); + // specified input stream!"); +// } +// return toInt(buf); +// } catch (IOException e) { +// throw new RuntimeIOException(e.getMessage(), e); +// } + try { int value = 0; for (int i = 0; i < 4; i++) { @@ -465,7 +521,7 @@ public class BytesUtils { // } catch (IOException e) { // throw new RuntimeIOException(e.getMessage(), e); // } - + try { out.write((value >>> 24) & 0x00FF); out.write((value >>> 16) & 0x00FF); @@ -515,7 +571,7 @@ public class BytesUtils { // } catch (IOException e) { // throw new RuntimeIOException(e.getMessage(), e); // } - + try { out.write((int) ((value >>> 56) & 0x00FF)); out.write((int) ((value >>> 48) & 0x00FF)); diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/NumberMask.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/NumberMask.java index a77c5e7d..e13154d0 100644 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/NumberMask.java +++ b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/io/NumberMask.java @@ -139,13 +139,6 @@ public enum NumberMask { * @return */ public int getBoundarySize(int headerLength) { -// if (headerLength < 1) { -// throw new IllegalArgumentException("Header length is less than one!"); -// } -// if (headerLength > MAX_HEADER_LENGTH) { -// throw new IllegalArgumentException( -// "Header length is great than MAX_HEADER_LENGTH[" + MAX_HEADER_LENGTH + "]!"); -// } return boundarySizes[headerLength - 1]; } diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/security/AESUtils.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/security/AESUtils.java index ec1e2563..35408b67 100644 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/security/AESUtils.java +++ b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/security/AESUtils.java @@ -21,9 +21,9 @@ import com.jd.blockchain.utils.codec.HexUtils; public class AESUtils { /** - * 用指定的种子生成 128 位的秘钥;
+ * 用指定的种子生成 128 位的密钥;
* - * 如果指定的种子为空(null 或长度为 0 ),则生成随机的秘钥; + * 如果指定的种子为空(null 或长度为 0 ),则生成随机的密钥; * * @param seed * 种子; @@ -35,7 +35,7 @@ public class AESUtils { } /** - * 用指定的种子生成 128 位的秘钥; + * 用指定的种子生成 128 位的密钥; * * @param seed * 种子; @@ -47,7 +47,7 @@ public class AESUtils { } /** - * 用指定的种子生成 128 位的秘钥; + * 用指定的种子生成 128 位的密钥; * * @param seed * 种子; 不允许为空; @@ -57,7 +57,7 @@ public class AESUtils { if (seed == null || seed.length == 0) { throw new IllegalArgumentException("Empty seed!"); } - // 注:AES 算法只支持 128 位,不支持 192, 256 位的秘钥加密; + // 注:AES 算法只支持 128 位,不支持 192, 256 位的密钥加密; byte[] hashBytes = ShaUtils.hash_128(seed); return new SecretKeySpec(hashBytes, "AES"); @@ -67,7 +67,7 @@ public class AESUtils { } /** - * 生成 128 位的随机秘钥; + * 生成 128 位的随机密钥; * * @return */ @@ -77,7 +77,7 @@ public class AESUtils { } /** - * 生成以 16 进制编码的 128 位的随机秘钥; + * 生成以 16 进制编码的 128 位的随机密钥; * * @return */ @@ -92,11 +92,11 @@ public class AESUtils { } /** - * 用指定的 16 进制的AES秘钥进行加密; + * 用指定的 16 进制的AES密钥进行加密; * * @param content * @param key - * 16进制编码的 AES 秘钥; + * 16进制编码的 AES 密钥; * @return */ public static byte[] encrypt(byte[] content, String key) { diff --git a/source/utils/utils-http/src/test/java/test/my/utils/http/agent/HttpServiceAgentTest.java b/source/utils/utils-http/src/test/java/test/my/utils/http/agent/HttpServiceAgentTest.java index 2a1cf757..3bed4a46 100644 --- a/source/utils/utils-http/src/test/java/test/my/utils/http/agent/HttpServiceAgentTest.java +++ b/source/utils/utils-http/src/test/java/test/my/utils/http/agent/HttpServiceAgentTest.java @@ -23,6 +23,8 @@ import com.jd.blockchain.utils.http.agent.AuthorizationAlgs; import com.jd.blockchain.utils.http.agent.AuthorizationHeader; import com.jd.blockchain.utils.http.agent.HttpServiceAgent; import com.jd.blockchain.utils.http.agent.ServiceEndpoint; +import com.jd.blockchain.utils.io.BytesUtils; +import com.jd.blockchain.utils.security.ShaUtils; import com.jd.blockchain.utils.serialize.binary.BinarySerializeUtils; import com.jd.blockchain.utils.web.server.WebServer; @@ -30,7 +32,7 @@ public class HttpServiceAgentTest { private static final String host = "127.0.0.1"; - private static final int port = 10809; +// private static final int port = 10809; private static final String SENDER_NAME = "upush_test"; @@ -48,13 +50,22 @@ public class HttpServiceAgentTest { server.stop(); } } + + private int getRandomPort() { + byte[] nanoTime = BytesUtils.toBytes(System.nanoTime()); + byte[] hash = ShaUtils.hash_256(nanoTime); + return hash[0]; + } - private void prepareEnvironment(String contextPath, HttpServlet servlet, String servletMapping) { - int port = 10809; + private int prepareEnvironment(String contextPath, HttpServlet servlet, String servletMapping) { + //随机化端口,避免测试用例的端口冲突 + int port = 11000 + getRandomPort(); server = new WebServer(host, port); server.registServlet("test-servlet", servlet, servletMapping); server.setContextPath(contextPath); server.start(); + + return port; } @Test @@ -66,7 +77,7 @@ public class HttpServiceAgentTest { HttpRequestCollector servlet = new HttpRequestCollector(expectedResponseText); // 准备环境; - prepareEnvironment(contextPath, servlet, servicePath); + int port = prepareEnvironment(contextPath, servlet, servicePath); ServiceEndpoint endpoint = new ServiceEndpoint(host, port, false, contextPath); AuthorizationHeader authorization = new AuthorizationHeader(AuthorizationAlgs.DEFAULT, SENDER_NAME, SECRET_KEY); @@ -169,7 +180,7 @@ public class HttpServiceAgentTest { HttpRequestCollector servlet = new HttpRequestCollector(expectedResponseText); // 准备环境; - prepareEnvironment(contextPath, servlet, servicePath); + int port = prepareEnvironment(contextPath, servlet, servicePath); ServiceEndpoint setting = new ServiceEndpoint(host, port, false, contextPath); AuthorizationHeader authSetting = new AuthorizationHeader(AuthorizationAlgs.DEFAULT, SENDER_NAME, SECRET_KEY); HttpTestService testService = HttpServiceAgent.createService(HttpTestService.class, setting, authSetting); @@ -229,7 +240,7 @@ public class HttpServiceAgentTest { HttpRequestCollector servlet = new HttpRequestCollector(expectedResponseText); // 准备环境; - prepareEnvironment(contextPath, servlet, servicePath); + int port = prepareEnvironment(contextPath, servlet, servicePath); ServiceEndpoint setting = new ServiceEndpoint(host, port, false, contextPath); AuthorizationHeader authSetting = new AuthorizationHeader(AuthorizationAlgs.DEFAULT, SENDER_NAME, SECRET_KEY); @@ -267,7 +278,7 @@ public class HttpServiceAgentTest { HttpRequestCollector servlet = new HttpRequestCollector(expectedResponseText); // 准备环境; - prepareEnvironment(contextPath, servlet, servicePath); + int port = prepareEnvironment(contextPath, servlet, servicePath); ServiceEndpoint setting = new ServiceEndpoint(host, port, false, contextPath); AuthorizationHeader authSetting = new AuthorizationHeader(AuthorizationAlgs.DEFAULT, SENDER_NAME, SECRET_KEY); @@ -332,7 +343,7 @@ public class HttpServiceAgentTest { HttpRequestCollector servlet = new HttpRequestCollector(expectedResponseText); // 准备环境; - prepareEnvironment(contextPath, servlet, servicePath); + int port = prepareEnvironment(contextPath, servlet, servicePath); ServiceEndpoint setting = new ServiceEndpoint(host, port, false, contextPath); AuthorizationHeader authSetting = new AuthorizationHeader(AuthorizationAlgs.DEFAULT, SENDER_NAME, SECRET_KEY); @@ -373,7 +384,7 @@ public class HttpServiceAgentTest { HttpRequestCollector servlet = new HttpRequestCollector(expectedResponseText); // 准备环境; - prepareEnvironment(contextPath, servlet, servicePath); + int port = prepareEnvironment(contextPath, servlet, servicePath); ServiceEndpoint setting = new ServiceEndpoint(host, port, false, contextPath); AuthorizationHeader authSetting = new AuthorizationHeader(AuthorizationAlgs.DEFAULT, SENDER_NAME, SECRET_KEY); @@ -414,7 +425,7 @@ public class HttpServiceAgentTest { HttpRequestCollector servlet = new HttpRequestCollector(expectedResponseText); // 准备环境; - prepareEnvironment(contextPath, servlet, servicePath); + int port = prepareEnvironment(contextPath, servlet, servicePath); ServiceEndpoint setting = new ServiceEndpoint(host, port, false, contextPath); AuthorizationHeader authSetting = new AuthorizationHeader(AuthorizationAlgs.DEFAULT, SENDER_NAME, SECRET_KEY); @@ -453,7 +464,7 @@ public class HttpServiceAgentTest { HttpRequestCollector servlet = new HttpRequestCollector(expectedResponseBytes); // 准备环境; - prepareEnvironment(contextPath, servlet, servicePath); + int port = prepareEnvironment(contextPath, servlet, servicePath); ServiceEndpoint setting = new ServiceEndpoint(host, port, false, contextPath); AuthorizationHeader authSetting = new AuthorizationHeader(AuthorizationAlgs.DEFAULT, SENDER_NAME, SECRET_KEY); @@ -506,7 +517,7 @@ public class HttpServiceAgentTest { HttpRequestCollector servlet = new HttpRequestCollector(expectedResponseBytes); // 准备环境; - prepareEnvironment(contextPath, servlet, servicePath); + int port = prepareEnvironment(contextPath, servlet, servicePath); ServiceEndpoint setting = new ServiceEndpoint(host, port, false, contextPath); AuthorizationHeader authSetting = new AuthorizationHeader(AuthorizationAlgs.DEFAULT, SENDER_NAME, SECRET_KEY);