diff --git a/build.gradle b/build.gradle index 61e324d..4239292 100644 --- a/build.gradle +++ b/build.gradle @@ -35,7 +35,7 @@ if (!gradle.startParameter.isOffline()) { apply plugin: 'signing' } -version = "1.0.2" +version = "1.0.3" //设置jdk的版本 sourceCompatibility = 1.8 targetCompatibility = 1.8 @@ -53,23 +53,57 @@ repositories { } } +def spring_version = "4.3.27.RELEASE" +def log4j_version = "2.13.3"; +def slf4j_version = "1.7.30"; +def jackson_version = "2.11.0"; +def mysql_version = "8.0.20"; +def swagger_version = "2.9.2"; + List swagger = [ - "io.springfox:springfox-swagger2:2.9.2", - "io.springfox:springfox-swagger-ui:2.9.2" + "io.springfox:springfox-swagger2:$swagger_version", + "io.springfox:springfox-swagger-ui:$swagger_version" ] + List apache_commons = [ - "org.apache.commons:commons-collections4:4.1", - "org.apache.commons:commons-lang3:3.5", - "commons-cli:commons-cli:1.3.1", - 'com.github.fge:json-schema-validator:2.2.6', - "com.fasterxml.jackson.core:jackson-databind:2.10.0", - "com.fasterxml.jackson.core:jackson-core:2.10.0", - "com.fasterxml.jackson.core:jackson-annotations:2.10.0", - "com.github.reinert:jjschema:1.16", - "com.google.zxing:core:3.3.0", - "javassist:javassist:3.12.1.GA" + "org.apache.logging.log4j:log4j-api:$log4j_version", + "org.apache.logging.log4j:log4j-web:$log4j_version", + "org.apache.logging.log4j:log4j-core:$log4j_version", + "org.apache.logging.log4j:log4j-jcl:$log4j_version", + "org.apache.logging.log4j:log4j-slf4j-impl:$log4j_version", + "org.slf4j:jul-to-slf4j:$slf4j_version", + "org.slf4j:slf4j-api:$slf4j_version" +] + +List json = [ + "com.fasterxml.jackson.datatype:jackson-datatype-jdk8:$jackson_version", + "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version", + "com.fasterxml.jackson.module:jackson-module-parameter-names:$jackson_version", + "com.fasterxml.jackson.core:jackson-databind:$jackson_version", + "com.fasterxml.jackson.core:jackson-annotations:$jackson_version", + "com.fasterxml.jackson.core:jackson-core:$jackson_version", + "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:$jackson_version" +] + +List mysql_driver = [ + "mysql:mysql-connector-java:$mysql_version" ] +List spring = [ + "org.springframework:spring-core:$spring_version", + "org.springframework:spring-beans:$spring_version", + "org.springframework:spring-context:$spring_version", + "org.springframework:spring-tx:$spring_version", + "org.springframework:spring-jdbc:$spring_version", + "org.springframework:spring-test:$spring_version", + "org.springframework:spring-context-support:$spring_version", + "org.springframework:spring-web:$spring_version", + "org.springframework:spring-webmvc:$spring_version" +] + +List other = [ + "javassist:javassist:3.12.1.GA" +] configurations { localDeps @@ -77,14 +111,14 @@ configurations { //添加编译时的依赖 dependencies { - localDeps 'org.projectlombok:lombok:1.18.10' + localDeps 'org.projectlombok:lombok:1.18.12' // Check SDK pipeline dependency if (file("./dependencies/weid-java-sdk-pipeline.jar").exists()) { println "Pipeline jar for WeIdentity Java SDK found." compile files('./dependencies/weid-java-sdk-pipeline.jar') } else { println "No pipeline jar found for WeIdentity Java SDK, using gradle version.." - compile("com.webank:weid-java-sdk:1.5.0") { + compile("com.webank:weid-java-sdk:1.6.4") { exclude group:"org.slf4j", module: "slf4j-log4j12" } } @@ -96,21 +130,21 @@ dependencies { exclude group:"ch.qos.logback" } compile fileTree(dir:'libs', include:'*.jar') - compile apache_commons, swagger + compile apache_commons, swagger, json, mysql_driver, spring, other } } if (gradleVer.startsWith("5")) { if (!gradle.startParameter.isOffline()) { - compileOnly 'org.projectlombok:lombok:1.18.10' - annotationProcessor 'org.projectlombok:lombok:1.18.10' + compileOnly 'org.projectlombok:lombok:1.18.12' + annotationProcessor 'org.projectlombok:lombok:1.18.12' compile("org.springframework.boot:spring-boot-starter-web"){ exclude group:"ch.qos.logback" } compile fileTree(dir:'libs', include:'*.jar') - compile apache_commons, swagger + compile apache_commons, swagger, json, mysql_driver, spring, other } else { - compileOnly files('dist/lib/lombok-1.18.10.jar') - annotationProcessor files('dist/lib/lombok-1.18.10.jar') + compileOnly files('dist/lib/lombok-1.18.12.jar') + annotationProcessor files('dist/lib/lombok-1.18.12.jar') compile fileTree(dir: 'dist/lib', include: '*.jar') } } @@ -160,6 +194,12 @@ clean { delete("dist") } +eclipse { + classpath { + downloadSources = false + } +} + checkstyle { ignoreFailures false showViolations true diff --git a/claim/JsonSchema2.json b/claim/JsonSchema2.json index d9f2aa8..c35d994 100644 --- a/claim/JsonSchema2.json +++ b/claim/JsonSchema2.json @@ -1,46 +1,98 @@ { - "properties": { - "weid": { - "type": "string", - "description": "the weid of certificate owner" - }, - "name": { - "type": "string", - "description": "the name of certificate owner" - }, - "meta": { - "type": "object", - "properties": { - "code": { - "type": "number", - "description": "code" - }, - "error": { - "type": "string", - "description": "error" - }, - "info": { - "type": "string", - "description": "info" - } - } - }, - "data": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "info" - }, - "sipTellAddress": { - "type": "string", - "description": "sipTellAddress" - }, - "userlevel": { - "type": "integer", - "description": "userlevel" - } - } - } - } -} + "$id": "certs/v1.0", + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "StudentCert", + "type": "object", + "required": [ "did", "fullname", "cert", "issuers"], + "properties": { + "did": {"type": "string"}, + "weid": {"type": "string"}, + "fullname": { + "type": "object", + "properties": { + "cn": {"type": "string"}, + "en": {"type": "string"} + } + }, + + "cert":{ + "type": "object", + "required": ["code", "title", "category", "issueDate"], + "properties": { + "code": {"type": "string"}, + "title": { + "type": "object", + "properties": { + "cn": {"type": "string"}, + "en": {"type": "string"} + } + }, + "category": { + "type": "object", + "properties": { + "cn": {"type": "string"}, + "en": {"type": "string"} + } + }, + "totalDuration": { + "type": "number" + }, + "issueDate": { + "type": "string", + "format": "date-time" + }, + "validBefore": { + "type": "string", + "format": "date-time" + }, + "permanent": {"type": "boolean"} + } + }, + + "issuers": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "properties": { + "name": { + "type": "object", + "properties": { + "cn": {"type": "string"}, + "en": {"type": "string"} + } + } + } + } + }, + + "courses": { + "type": "array", + "items": { + "type": "object", + "properties": { + "code": {"type": "string"}, + "title": { + "type": "object", + "properties": { + "cn": {"type": "string"}, + "en": {"type": "string"} + } + }, + "startDate": { + "type": "string", + "format": "date" + }, + "endDate": { + "type": "string", + "format": "date" + }, + "duration": {"type": "number"}, + "grade": {"type": "string"}, + "score": {"type": "string"}, + "language": {"type": "string"} + } + } + } + } +} \ No newline at end of file diff --git a/claim/JsonSchema3.json b/claim/JsonSchema3.json index c35d994..d9f2aa8 100644 --- a/claim/JsonSchema3.json +++ b/claim/JsonSchema3.json @@ -1,98 +1,46 @@ { - "$id": "certs/v1.0", - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "StudentCert", - "type": "object", - "required": [ "did", "fullname", "cert", "issuers"], - "properties": { - "did": {"type": "string"}, - "weid": {"type": "string"}, - "fullname": { - "type": "object", - "properties": { - "cn": {"type": "string"}, - "en": {"type": "string"} - } - }, - - "cert":{ - "type": "object", - "required": ["code", "title", "category", "issueDate"], - "properties": { - "code": {"type": "string"}, - "title": { - "type": "object", - "properties": { - "cn": {"type": "string"}, - "en": {"type": "string"} - } - }, - "category": { - "type": "object", - "properties": { - "cn": {"type": "string"}, - "en": {"type": "string"} - } - }, - "totalDuration": { - "type": "number" - }, - "issueDate": { - "type": "string", - "format": "date-time" - }, - "validBefore": { - "type": "string", - "format": "date-time" - }, - "permanent": {"type": "boolean"} - } - }, - - "issuers": { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "properties": { - "name": { - "type": "object", - "properties": { - "cn": {"type": "string"}, - "en": {"type": "string"} - } - } - } - } - }, - - "courses": { - "type": "array", - "items": { - "type": "object", - "properties": { - "code": {"type": "string"}, - "title": { - "type": "object", - "properties": { - "cn": {"type": "string"}, - "en": {"type": "string"} - } - }, - "startDate": { - "type": "string", - "format": "date" - }, - "endDate": { - "type": "string", - "format": "date" - }, - "duration": {"type": "number"}, - "grade": {"type": "string"}, - "score": {"type": "string"}, - "language": {"type": "string"} - } - } - } - } -} \ No newline at end of file + "properties": { + "weid": { + "type": "string", + "description": "the weid of certificate owner" + }, + "name": { + "type": "string", + "description": "the name of certificate owner" + }, + "meta": { + "type": "object", + "properties": { + "code": { + "type": "number", + "description": "code" + }, + "error": { + "type": "string", + "description": "error" + }, + "info": { + "type": "string", + "description": "info" + } + } + }, + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "info" + }, + "sipTellAddress": { + "type": "string", + "description": "sipTellAddress" + }, + "userlevel": { + "type": "integer", + "description": "userlevel" + } + } + } + } +} diff --git a/settings.gradle b/settings.gradle index 856644d..0ad2a91 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1 @@ -rootProject.name='weid-sample' \ No newline at end of file +rootProject.name='WeIdentity-Sample' \ No newline at end of file diff --git a/src/main/java/com/webank/weid/demo/command/DemoCommand.java b/src/main/java/com/webank/weid/demo/command/DemoCommand.java index 6aaa6f4..0f4e564 100644 --- a/src/main/java/com/webank/weid/demo/command/DemoCommand.java +++ b/src/main/java/com/webank/weid/demo/command/DemoCommand.java @@ -39,6 +39,7 @@ import com.webank.weid.protocol.base.PresentationPolicyE; import com.webank.weid.protocol.response.CreateWeIdDataResult; import com.webank.weid.util.DataToolUtils; +import com.webank.weid.util.ScanCodeUtils; /** * command operation. @@ -266,7 +267,7 @@ private static void userAgent() { String imageName = System.currentTimeMillis() + ".jpg"; String fileName = DemoUtil.TEMP_DIR + imageName; Integer integer = - DataToolUtils.generateQrCode( + ScanCodeUtils.generateQrCode( url, ErrorCorrectionLevel.H, fileName diff --git a/src/main/java/com/webank/weid/demo/command/EndpointSample.java b/src/main/java/com/webank/weid/demo/command/EndpointSample.java index fce0616..16ce8c2 100644 --- a/src/main/java/com/webank/weid/demo/command/EndpointSample.java +++ b/src/main/java/com/webank/weid/demo/command/EndpointSample.java @@ -37,7 +37,7 @@ public class EndpointSample { private static class DuplicateFunctor implements EndpointFunctor { @Override - public String execute(String arg) { + public String callback(String arg) { return arg + arg + arg; } @@ -55,7 +55,7 @@ private static class DataAuthorizationFunctor implements EndpointFunctor { ConcurrentHashMap resourceMap = new ConcurrentHashMap<>(); @Override - public String execute(String resourceId) { + public String callback(String resourceId) { if (!resourceMap.containsKey(resourceId)) { return "Cannot find this resource: " + resourceId; } @@ -81,7 +81,7 @@ public static void main(String[] args) throws Exception { // Register a duplicate endpoint EndpointFunctor functor1 = new DuplicateFunctor(); String requestName1 = "duplicate-input"; - RpcServer.registerEndpoint(requestName1, functor1); + RpcServer.registerEndpoint(requestName1, functor1, null); // Register a data-authorization fetch endpoint EndpointFunctor functor2 = new DataAuthorizationFunctor(); @@ -142,10 +142,10 @@ public static void main(String[] args) throws Exception { resourceId也捎带到SDK侧过去。 9) SDK侧会收到这RPC请求,并触发0)步中注册的functor的execute(),解析resourceId并返回授权数据。 */ - RpcServer.registerEndpoint("fetch-data", functor2); + RpcServer.registerEndpoint("fetch-data", functor2, null); // Start the RPC server instance - RpcServer.main(null); + RpcServer.run(); // You can also try to add endpoint here too after it is booted and running. //RpcServer.registerEndpoint("fetch-data-backup", functor2, null); } diff --git a/src/main/java/com/webank/weid/demo/command/MultiGroupEvidenceSample.java b/src/main/java/com/webank/weid/demo/command/MultiGroupEvidenceSample.java new file mode 100644 index 0000000..4684ec4 --- /dev/null +++ b/src/main/java/com/webank/weid/demo/command/MultiGroupEvidenceSample.java @@ -0,0 +1,179 @@ +/* + * Copyright© (2019-2020) WeBank Co., Ltd. + * + * This file is part of weidentity-sample. + * + * weidentity-sample is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * weidentity-sample is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with weidentity-sample. If not, see . + */ + +package com.webank.weid.demo.command; + +import java.util.HashMap; +import java.util.Map; + +import com.webank.weid.constant.CredentialType; +import com.webank.weid.constant.ProcessingMode; +import com.webank.weid.protocol.base.CredentialPojo; +import com.webank.weid.protocol.base.CredentialPojoList; +import com.webank.weid.protocol.base.EvidenceInfo; +import com.webank.weid.protocol.base.PublicKeyProperty; +import com.webank.weid.protocol.base.WeIdAuthentication; +import com.webank.weid.protocol.base.WeIdDocument; +import com.webank.weid.protocol.request.CreateCredentialPojoArgs; +import com.webank.weid.protocol.response.CreateWeIdDataResult; +import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.rpc.CredentialPojoService; +import com.webank.weid.rpc.EvidenceService; +import com.webank.weid.rpc.WeIdService; +import com.webank.weid.service.impl.CredentialPojoServiceImpl; +import com.webank.weid.service.impl.EvidenceServiceImpl; +import com.webank.weid.service.impl.WeIdServiceImpl; +import com.webank.weid.suite.api.crypto.CryptoServiceFactory; +import com.webank.weid.suite.api.crypto.params.CryptoType; + +public class MultiGroupEvidenceSample { + + static WeIdService weidService = new WeIdServiceImpl(); + + static CredentialPojoService credentialPojoService = new CredentialPojoServiceImpl(); + + static EvidenceService evidenceService = new EvidenceServiceImpl(ProcessingMode.IMMEDIATE, 2); + + /** + * Demo过程说明 + * 1. 创建weid + * 2. 创建lite Credential1 创建lite Credential2 + * 3. 将两个Credential放入CredentialPojoList中 + * 4. CredentialPojoList转json + * 5. CredentialPojoList json 加密 + * 6. CredentialPojoList json 解密 + * 7. CredentialPojoList json 转 CredentialPojoList + * 8. 验证Credential + * 9. 根据Credential创建Evidence + * 10. 获取存证数据 + * 11. 验证存在数据 + * + * @param args + */ + public static void main(String[] args) { + // 1. 创建weid + ResponseData createWeIdRes = weidService.createWeId(); + System.out.println("创建weid结果:" + createWeIdRes); + CreateWeIdDataResult createWeId = createWeIdRes.getResult(); + // 省略返回code判断 + + // 2. 创建lite Credential + ResponseData weIdDocumentRes = + weidService.getWeIdDocument(createWeId.getWeId()); + String publicKeyId = null; + for (PublicKeyProperty publicKey : weIdDocumentRes.getResult().getPublicKey()) { + if (publicKey.getOwner().equals(createWeId.getWeId())) { + publicKeyId = publicKey.getId(); + break; + } + } + // 构造WeIdAuthentication + WeIdAuthentication weIdAuthentication = buildWeIdAuthority(createWeId, publicKeyId); + CreateCredentialPojoArgs> createArgs = + buildCreateCredentialPojoArgs(weIdAuthentication); + ResponseData createCredential1 = + credentialPojoService.createCredential(createArgs); + System.out.println("lite Credential1 创建结果:" + createCredential1); + ResponseData createCredential2 = + credentialPojoService.createCredential(createArgs); + System.out.println("lite Credential2 创建结果:" + createCredential2); + // 省略返回code判断 + + // 3.将CredentialPojo放入CredentialPojoList中 + CredentialPojoList credentialPojoList = new CredentialPojoList(); + credentialPojoList.add(createCredential1.getResult()); + credentialPojoList.add(createCredential2.getResult()); + + // 4. CredentialPojoList转json + String credentialListJson = credentialPojoList.toJson(); + System.out.println("CredentialPojoList 转Json 结果:" + credentialListJson); + + // 5. 加密Credential Json + String encrypt = CryptoServiceFactory.getCryptoService(CryptoType.ECIES).encrypt( + credentialListJson, createWeId.getUserWeIdPublicKey().getPublicKey()); + System.out.println("credentialList Json 加密结果:" + encrypt); + + // 6. 解密 Credential Json + String decrypt = CryptoServiceFactory.getCryptoService(CryptoType.ECIES).decrypt( + encrypt, createWeId.getUserWeIdPrivateKey().getPrivateKey()); + System.out.println("credentialList Json 解密结果:" + decrypt); + + // 7. Credential Json 转Credential + CredentialPojoList credential = CredentialPojoList.fromJson(credentialListJson); + System.out.println("解密后的credentialList Json 转 credentialList结果:" + credential); + + for (CredentialPojo credentialPojo : credential) { + // 8. 验证Credential + ResponseData verifyRes = + credentialPojoService.verify(createWeId.getWeId(), credentialPojo); + System.out.println("Credential 验证结果:" + verifyRes); + // 省略返回code判断 + + // 9. 创建Evidence + ResponseData createEvidence = + evidenceService.createEvidence(credentialPojo, createWeId.getUserWeIdPrivateKey()); + System.out.println("存证创建结果:" + createEvidence); + // 省略返回code判断 + + // 10. 获取存证 + ResponseData evidenceRes = + evidenceService.getEvidence(createEvidence.getResult()); + System.out.println("获取存证结果:" + evidenceRes); + // 省略返回code判断 + + // 11. 验证存证 + ResponseData verifySigner = + evidenceService.verifySigner(evidenceRes.getResult(), createWeId.getWeId()); + System.out.println("存证验证结果:" + verifySigner); + // 省略返回code判断 + } + } + + public static CreateCredentialPojoArgs> buildCreateCredentialPojoArgs( + WeIdAuthentication weIdAuthentication + ) { + CreateCredentialPojoArgs> createArgs = new CreateCredentialPojoArgs<>(); + createArgs.setIssuer(weIdAuthentication.getWeId()); + createArgs.setExpirationDate( + System.currentTimeMillis() + (1000 * 60 * 60 * 24)); + createArgs.setWeIdAuthentication(weIdAuthentication); + Map claimMap = new HashMap(); + claimMap.put("name", "zhang san"); + claimMap.put("gender", "F"); + claimMap.put("age", 23); + createArgs.setClaim(claimMap); + createArgs.setCptId(1000); + createArgs.setType(CredentialType.LITE1); + return createArgs; + } + + /** + * build weId authority. + */ + public static WeIdAuthentication buildWeIdAuthority( + CreateWeIdDataResult createWeId, + String publicKeyId + ) { + return new WeIdAuthentication( + createWeId.getWeId(), + createWeId.getUserWeIdPrivateKey().getPrivateKey(), + publicKeyId + ); + } +} \ No newline at end of file diff --git a/src/main/java/com/webank/weid/demo/command/TransportaionIssuer.java b/src/main/java/com/webank/weid/demo/command/TransportaionIssuer.java new file mode 100644 index 0000000..e06642b --- /dev/null +++ b/src/main/java/com/webank/weid/demo/command/TransportaionIssuer.java @@ -0,0 +1,219 @@ +/* + * Copyright© (2019-2020) WeBank Co., Ltd. + * + * This file is part of weidentity-sample. + * + * weidentity-sample is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * weidentity-sample is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with weidentity-sample. If not, see . + */ + +package com.webank.weid.demo.command; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.webank.weid.constant.JsonSchemaConstant; +import com.webank.weid.protocol.base.CptBaseInfo; +import com.webank.weid.protocol.base.CredentialPojo; +import com.webank.weid.protocol.base.CredentialPojoList; +import com.webank.weid.protocol.base.PublicKeyProperty; +import com.webank.weid.protocol.base.WeIdAuthentication; +import com.webank.weid.protocol.base.WeIdDocument; +import com.webank.weid.protocol.base.WeIdPublicKey; +import com.webank.weid.protocol.request.CptMapArgs; +import com.webank.weid.protocol.request.CreateCredentialPojoArgs; +import com.webank.weid.protocol.response.CreateWeIdDataResult; +import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.rpc.CptService; +import com.webank.weid.rpc.CredentialPojoService; +import com.webank.weid.rpc.WeIdService; +import com.webank.weid.service.impl.CptServiceImpl; +import com.webank.weid.service.impl.CredentialPojoServiceImpl; +import com.webank.weid.service.impl.WeIdServiceImpl; +import com.webank.weid.suite.api.transportation.TransportationFactory; +import com.webank.weid.suite.api.transportation.params.EncodeType; +import com.webank.weid.suite.api.transportation.params.ProtocolProperty; +import com.webank.weid.suite.api.transportation.params.TransMode; +import com.webank.weid.suite.api.transportation.params.TransportationType; + +public class TransportaionIssuer { + + static WeIdService weidService = new WeIdServiceImpl(); + static CptService cptService = new CptServiceImpl(); + static CredentialPojoService credentialPojoService = new CredentialPojoServiceImpl(); + + public static void main(String[] args) throws IOException { + + // 创建weid + CreateWeIdDataResult result = weidService.createWeId().getResult(); + ResponseData weIdDocumentRes =weidService.getWeIdDocument(result.getWeId()); + String publicKeyId = null; + for (PublicKeyProperty publicKey : weIdDocumentRes.getResult().getPublicKey()) { + if (publicKey.getOwner().equals(result.getWeId())) { + publicKeyId = publicKey.getId(); + break; + } + } + // 构造WeIdAuthentication + WeIdAuthentication weIdAuthentication = buildWeIdAuthority(result, publicKeyId); + + // 注册cpt + CptMapArgs registerCptArgs = buildCptArgs(weIdAuthentication); + CptBaseInfo cptBaseInfo = cptService.registerCpt(registerCptArgs).getResult(); + + // 创建凭证 + CreateCredentialPojoArgs> createCredentialPojoArgs = + buildCreateCredentialPojoArgs(weIdAuthentication); + createCredentialPojoArgs.setCptId(cptBaseInfo.getCptId()); + ResponseData CredentialPojoRes = + credentialPojoService.createCredential(createCredentialPojoArgs); + System.out.println("创建凭证结果:"); + System.out.println(CredentialPojoRes); + + WeIdPublicKey weidPublicKey = new WeIdPublicKey(); + weidPublicKey.setPublicKey(result.getUserWeIdPublicKey().getPublicKey()); + ResponseData verify2 = credentialPojoService.verify( + weidPublicKey, CredentialPojoRes.getResult()); + System.out.println("根据公钥验证结果:" + verify2); + + + // 凭证放入CredentialPojoList中 + CredentialPojoList list = new CredentialPojoList(); + list.add(CredentialPojoRes.getResult()); + + // 指定可以解析二维码的机构白名单 + List verifierWeIdList = new ArrayList(); + verifierWeIdList.add("did:weid:101:0xa7af4461084b76aecfd9361a49e21cc34e6c4074"); + verifierWeIdList.add(result.getWeId()); + + // 调用序列化接口,生成条码编码 + // 如果序列化Presentation 将list修改成Presentation对象 + ResponseData serialize = + TransportationFactory.build(TransportationType.QR_CODE) + .specify(verifierWeIdList) + .serialize( + weIdAuthentication, + list, + new ProtocolProperty(EncodeType.CIPHER, TransMode.DOWNLOAD_MODE ) + ); + System.out.println("将凭证序列化成条码编码:"); + System.out.println(serialize); + + // 调用反序列化接口,根据条码编码获取对应数据,自己机构间走本地模式 + // 如果想获取的是PresentationE 将CredentialPojoList修改成PresentationE + ResponseData deserialize = + TransportationFactory.build(TransportationType.QR_CODE) + .deserialize(weIdAuthentication, serialize.getResult(), CredentialPojo.class); + System.out.println("根据条码编号获取凭证:"); + System.out.println(deserialize); + + // 验证获取到凭证 + ResponseData verify = + credentialPojoService.verify(result.getWeId(), deserialize.getResult()); + System.out.println("凭证验证结果:"); + System.out.println(verify); + } + + public static CreateCredentialPojoArgs> buildCreateCredentialPojoArgs( + WeIdAuthentication weIdAuthentication + ) { + + CreateCredentialPojoArgs> createCredentialPojoArgs = + new CreateCredentialPojoArgs>(); + + createCredentialPojoArgs.setIssuer(weIdAuthentication.getWeId()); + createCredentialPojoArgs.setExpirationDate( + System.currentTimeMillis() + (1000 * 60 * 60 * 24)); + createCredentialPojoArgs.setWeIdAuthentication(weIdAuthentication); + Map claimMap = new HashMap(); + claimMap.put("name", "zhang san"); + claimMap.put("gender", "F"); + claimMap.put("age", 23); + claimMap.put("id", weIdAuthentication.getWeId()); + createCredentialPojoArgs.setClaim(claimMap); + return createCredentialPojoArgs; + } + + /** + * build default CptMapArgs. + * + * @param createWeId WeId + * @return CptMapArgs + */ + public static CptMapArgs buildCptArgs(WeIdAuthentication weIdAuthentication) { + + CptMapArgs cptMapArgs = new CptMapArgs(); + cptMapArgs.setCptJsonSchema(buildCptJsonSchema()); + cptMapArgs.setWeIdAuthentication(weIdAuthentication); + + return cptMapArgs; + } + + /** + * build cpt json schema. + * + * @return HashMap + */ + public static HashMap buildCptJsonSchema() { + + HashMap cptJsonSchemaNew = new HashMap(3); + cptJsonSchemaNew.put(JsonSchemaConstant.TITLE_KEY, "Digital Identity"); + cptJsonSchemaNew.put(JsonSchemaConstant.DESCRIPTION_KEY, "this is a cpt template"); + + HashMap propertitesMap1 = new HashMap(2); + propertitesMap1.put(JsonSchemaConstant.TYPE_KEY, JsonSchemaConstant.DATA_TYPE_STRING); + propertitesMap1.put(JsonSchemaConstant.DESCRIPTION_KEY, "this is name"); + + String[] genderEnum = {"F", "M"}; + HashMap propertitesMap2 = new HashMap(2); + propertitesMap2.put(JsonSchemaConstant.TYPE_KEY, JsonSchemaConstant.DATA_TYPE_STRING); + propertitesMap2.put(JsonSchemaConstant.DATA_TYPE_ENUM, genderEnum); + + HashMap propertitesMap3 = new HashMap(2); + propertitesMap3.put(JsonSchemaConstant.TYPE_KEY, JsonSchemaConstant.DATA_TYPE_NUMBER); + propertitesMap3.put(JsonSchemaConstant.DESCRIPTION_KEY, "this is age"); + + HashMap propertitesMap4 = new HashMap(2); + propertitesMap4.put(JsonSchemaConstant.TYPE_KEY, JsonSchemaConstant.DATA_TYPE_STRING); + propertitesMap4.put(JsonSchemaConstant.DESCRIPTION_KEY, "this is weid"); + + HashMap cptJsonSchema = new HashMap(3); + cptJsonSchema.put("name", propertitesMap1); + cptJsonSchema.put("gender", propertitesMap2); + cptJsonSchema.put("age", propertitesMap3); + cptJsonSchema.put("id", propertitesMap4); + cptJsonSchemaNew.put(JsonSchemaConstant.PROPERTIES_KEY, cptJsonSchema); + + String[] genderRequired = {"id", "name", "gender"}; + cptJsonSchemaNew.put(JsonSchemaConstant.REQUIRED_KEY, genderRequired); + + return cptJsonSchemaNew; + } + + /** + * build weId authority. + */ + public static WeIdAuthentication buildWeIdAuthority( + CreateWeIdDataResult createWeId, + String publicKeyId + ) { + return new WeIdAuthentication( + createWeId.getWeId(), + createWeId.getUserWeIdPrivateKey().getPrivateKey(), + publicKeyId + ); + } +} diff --git a/src/main/java/com/webank/weid/demo/command/TransportationVerifier.java b/src/main/java/com/webank/weid/demo/command/TransportationVerifier.java new file mode 100644 index 0000000..91df2fa --- /dev/null +++ b/src/main/java/com/webank/weid/demo/command/TransportationVerifier.java @@ -0,0 +1,74 @@ +/* + * Copyright© (2019-2020) WeBank Co., Ltd. + * + * This file is part of weidentity-sample. + * + * weidentity-sample is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * weidentity-sample is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with weidentity-sample. If not, see . + */ + +package com.webank.weid.demo.command; + +import com.webank.weid.protocol.base.CredentialPojo; +import com.webank.weid.protocol.base.CredentialPojoList; +import com.webank.weid.protocol.base.WeIdAuthentication; +import com.webank.weid.protocol.base.WeIdPrivateKey; +import com.webank.weid.protocol.response.CreateWeIdDataResult; +import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.rpc.CredentialPojoService; +import com.webank.weid.rpc.WeIdService; +import com.webank.weid.service.impl.CredentialPojoServiceImpl; +import com.webank.weid.service.impl.WeIdServiceImpl; +import com.webank.weid.suite.api.transportation.TransportationFactory; +import com.webank.weid.suite.api.transportation.params.TransportationType; + +public class TransportationVerifier { + + public static void main(String[] args) { + System.out.println(System.currentTimeMillis()); + // TODO Auto-generated method stub + // 创建weid + WeIdService weidService = new WeIdServiceImpl(); + CreateWeIdDataResult result = weidService.createWeId().getResult(); + System.out.println(result); + // verifier WeId信息 + String weId = "did:weid:101:0xa7af4461084b76aecfd9361a49e21cc34e6c4074"; + WeIdPrivateKey privateKey = new WeIdPrivateKey(); + privateKey.setPrivateKey( + "89119831904759961853601218812211426488644695651785968136169259389312366556150"); + + // 构造verifier的身份信息 + WeIdAuthentication weIdAuthentication = + new WeIdAuthentication(weId, privateKey.getPrivateKey()); + + ResponseData deserialize = + TransportationFactory.build(TransportationType.QR_CODE) + .deserialize( + weIdAuthentication, + "2|1000orgB|993ecb3ffdbd47e5a3e2e7a798060ef1",//issuer通过serialize生成的条码编码 + CredentialPojoList.class + ); + System.out.println("根据条码编码获取到的凭证:"); + System.out.println(deserialize); + + // 验证获取到凭证 + CredentialPojoService credentialPojoService = new CredentialPojoServiceImpl(); + CredentialPojoList credentialPojoList = deserialize.getResult(); + for (CredentialPojo credentialPojo2 : credentialPojoList) { + ResponseData verify = + credentialPojoService.verify(credentialPojo2.getIssuer(), credentialPojo2); + System.out.println("凭证验证结果:"); + System.out.println(verify); + } + } +} diff --git a/src/main/java/com/webank/weid/demo/config/WebConfig.java b/src/main/java/com/webank/weid/demo/config/WebConfig.java index 603330c..e8bab6a 100644 --- a/src/main/java/com/webank/weid/demo/config/WebConfig.java +++ b/src/main/java/com/webank/weid/demo/config/WebConfig.java @@ -8,6 +8,8 @@ import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import com.webank.weid.demo.filter.XssFilter; + /** * web mvc support. * @author darwindu @@ -33,4 +35,22 @@ public FilterRegistrationBean corsFilter() { return bean; } + + /** + * XSS过滤器. + * @return + */ + @Bean + public FilterRegistrationBean xssFilter() { + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + + CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues(); + config.setAllowCredentials(false); + source.registerCorsConfiguration("/**", config); + + FilterRegistrationBean bean = new FilterRegistrationBean(new XssFilter()); + bean.setOrder(1); + + return bean; + } } diff --git a/src/main/java/com/webank/weid/demo/controller/DemoOtherEvidenceController.java b/src/main/java/com/webank/weid/demo/controller/DemoOtherEvidenceController.java index d07fce8..b2ab136 100644 --- a/src/main/java/com/webank/weid/demo/controller/DemoOtherEvidenceController.java +++ b/src/main/java/com/webank/weid/demo/controller/DemoOtherEvidenceController.java @@ -60,39 +60,13 @@ public ResponseData createEvidence( } - @ApiOperation(value = "根据传入的凭证存证地址,在链上查找凭证存证信息。") + @ApiOperation(value = "根据传入的凭证存证Hash,在链上查找凭证存证信息。") @PostMapping("/step2/getEvidence") public ResponseData getEvidence( @ApiParam(name = "evidenceAddress", - value = "凭证存证地址", example = "0x788bfde9ad99376673ed46847294e9b858728045") + value = "凭证存证Hash", example = "0x788bfde9ad99376673ed46847294e9b85872804573ed46847294e9b858728045") @RequestParam(value = "evidenceAddress") String evidenceAddress) { return demoOtherService.getEvidence(evidenceAddress); } - - @ApiOperation(value = "对传入的Object及链上地址,加一个签名存入链上的存证。要求:传入的签名方必须隶属于在创建存证时传入多个签名方的WeID之一。") - @PostMapping("/step3/addSignatureCredentialPojo") - public ResponseData addSignature( - @ApiParam(name = "addSignatureCredentialPojo", value = "加签模板") - @RequestBody AddSignatureModel addSignatureModel) { - return demoOtherService.addSignature(addSignatureModel); - } - - @ApiOperation(value = "根据传入的Object计算存证Hash值和链上值对比,验证其是否遭到篡改。" - + "当存证包含多个签名时,将会依次验证每个签名,必须确实由签名者列表中的某个WeID所签发才算验证成功。") - @PostMapping("/step4/verifyEvidence") - public ResponseData verifyEvidence( - @ApiParam(name = "verifyEvidenceModel", value = "存证验签模板") - @RequestBody VerifyEvidenceModel verifyEvidenceModel) { - return demoOtherService.verifyEvidence(verifyEvidenceModel); - } - - @ApiOperation(value = "对指定的空存证地址,将其链上的Hash值设定为所传入的Hash值。" - + "传入的私钥必须是创建存证时所声明的签名者之一。注意:当存证非空时,接口将返回失败。") - @PostMapping("/step5/setHashValue") - public ResponseData setHashValue( - @ApiParam(name = "setHashValueModel", value = "对指定的空存证地址设值模板") - @RequestBody SetHashValueModel setHashValueModel) { - return demoOtherService.setHashValue(setHashValueModel); - } } diff --git a/src/main/java/com/webank/weid/demo/filter/XssFilter.java b/src/main/java/com/webank/weid/demo/filter/XssFilter.java new file mode 100644 index 0000000..72cb1a1 --- /dev/null +++ b/src/main/java/com/webank/weid/demo/filter/XssFilter.java @@ -0,0 +1,35 @@ +package com.webank.weid.demo.filter; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; + +public class XssFilter implements Filter { + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + } + + @Override + public void doFilter( + ServletRequest servletRequest, + ServletResponse servletResponse, + FilterChain filterChain + ) throws IOException, ServletException { + filterChain.doFilter( + new XssHttpServletRequestWraper((HttpServletRequest) servletRequest), + servletResponse + ); + } + + @Override + public void destroy() { + + } +} \ No newline at end of file diff --git a/src/main/java/com/webank/weid/demo/filter/XssHttpServletRequestWraper.java b/src/main/java/com/webank/weid/demo/filter/XssHttpServletRequestWraper.java new file mode 100644 index 0000000..2a5a1d8 --- /dev/null +++ b/src/main/java/com/webank/weid/demo/filter/XssHttpServletRequestWraper.java @@ -0,0 +1,46 @@ +package com.webank.weid.demo.filter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; + +import org.apache.commons.lang.StringEscapeUtils; + + +public class XssHttpServletRequestWraper extends HttpServletRequestWrapper { + + public XssHttpServletRequestWraper(HttpServletRequest request) { + super(request); + } + + @Override + public String getHeader(String name) { + String str = StringEscapeUtils.escapeHtml(super.getHeader(name)); + return str; + } + + @Override + public String getQueryString() { + String str = StringEscapeUtils.escapeHtml(super.getQueryString()); + return str; + } + + @Override + public String getParameter(String name) { + String str = StringEscapeUtils.escapeHtml(super.getParameter(name)); + return str; + } + + @Override + public String[] getParameterValues(String name) { + String[] values = super.getParameterValues(name); + if(values != null) { + int length = values.length; + String[] escapseValues = new String[length]; + for(int i = 0; i < length; i++){ + escapseValues[i] = StringEscapeUtils.escapeHtml(values[i]); + } + return escapseValues; + } + return super.getParameterValues(name); + } +} \ No newline at end of file diff --git a/src/main/java/com/webank/weid/demo/service/DemoOtherService.java b/src/main/java/com/webank/weid/demo/service/DemoOtherService.java index ffa892c..d330494 100644 --- a/src/main/java/com/webank/weid/demo/service/DemoOtherService.java +++ b/src/main/java/com/webank/weid/demo/service/DemoOtherService.java @@ -129,37 +129,6 @@ ResponseData addSignatureCredentialPojo( */ ResponseData getEvidence(String evidenceAddress); - - /** - * 对传入的Object及链上地址,加一个签名存入链上的存证. - * 要求:传入的签名方必须隶属于在创建存证时传入多个签名方的WeID之一. - * - * @param addSignatureModel 加签模板 - * @return - */ - ResponseData addSignature(AddSignatureModel addSignatureModel); - - - /** - * 根据传入的Object计算存证Hash值和链上值对比,验证其是否遭到篡改. - * 当存证包含多个签名时,将会依次验证每个签名,必须确实由签名者列表中的某个WeID所签发才算验证成功. - * - * @param verifyEvidenceModel 验签模板 - * @return - */ - ResponseData verifyEvidence(VerifyEvidenceModel verifyEvidenceModel); - - - /** - * 对指定的空存证地址,将其链上的Hash值设定为所传入的Hash值。传入的私钥必须是创建存证时所声明的签名者之一. - * 注意:当存证非空时,接口将返回失败. - * - * @param setHashValueModel 设置hash - * @return - */ - ResponseData setHashValue(SetHashValueModel setHashValueModel); - - /** * 指定transportation的认证者,用于权限控制. * @param jsonTransportationSpecifyModel 参数模板 diff --git a/src/main/java/com/webank/weid/demo/service/impl/DemoOtherServiceImpl.java b/src/main/java/com/webank/weid/demo/service/impl/DemoOtherServiceImpl.java index 0cd19e5..db85976 100644 --- a/src/main/java/com/webank/weid/demo/service/impl/DemoOtherServiceImpl.java +++ b/src/main/java/com/webank/weid/demo/service/impl/DemoOtherServiceImpl.java @@ -1,516 +1,453 @@ -package com.webank.weid.demo.service.impl; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import com.webank.weid.constant.ErrorCode; -import com.webank.weid.demo.common.model.AddSignatureModel; -import com.webank.weid.demo.common.model.CreateCredentialPojoModel; -import com.webank.weid.demo.common.model.CreateEvidenceModel; -import com.webank.weid.demo.common.model.CreatePresentationModel; -import com.webank.weid.demo.common.model.CreatePresentationPolicyEModel; -import com.webank.weid.demo.common.model.CreateSelectiveCredentialModel; -import com.webank.weid.demo.common.model.CredentialPoJoAddSignature; -import com.webank.weid.demo.common.model.GetCredentialHashModel; -import com.webank.weid.demo.common.model.JsonTransportationSerializeModel; -import com.webank.weid.demo.common.model.JsonTransportationSpecifyModel; -import com.webank.weid.demo.common.model.SetHashValueModel; -import com.webank.weid.demo.common.model.VerifyCredentialModel; -import com.webank.weid.demo.common.model.VerifyCredentialPoJoModel; -import com.webank.weid.demo.common.model.VerifyEvidenceModel; -import com.webank.weid.demo.common.util.PrivateKeyUtil; -import com.webank.weid.demo.service.DemoOtherService; -import com.webank.weid.protocol.base.Challenge; -import com.webank.weid.protocol.base.ClaimPolicy; -import com.webank.weid.protocol.base.Credential; -import com.webank.weid.protocol.base.CredentialPojo; -import com.webank.weid.protocol.base.EvidenceInfo; -import com.webank.weid.protocol.base.HashString; -import com.webank.weid.protocol.base.PresentationE; -import com.webank.weid.protocol.base.PresentationPolicyE; -import com.webank.weid.protocol.base.WeIdAuthentication; -import com.webank.weid.protocol.base.WeIdPrivateKey; -import com.webank.weid.protocol.inf.Hashable; -import com.webank.weid.protocol.request.CreateCredentialPojoArgs; -import com.webank.weid.protocol.response.ResponseData; -import com.webank.weid.rpc.CredentialPojoService; -import com.webank.weid.rpc.CredentialService; -import com.webank.weid.rpc.EvidenceService; -import com.webank.weid.service.impl.CredentialPojoServiceImpl; -import com.webank.weid.service.impl.CredentialServiceImpl; -import com.webank.weid.service.impl.EvidenceServiceImpl; -import com.webank.weid.suite.api.transportation.TransportationFactory; -import com.webank.weid.suite.api.transportation.inf.JsonTransportation; -import com.webank.weid.suite.api.transportation.params.EncodeType; -import com.webank.weid.suite.api.transportation.params.ProtocolProperty; -import com.webank.weid.util.DataToolUtils; - -/** - * other interface. - * - * @author darwindu - * @date 2020/1/3 - **/ -@Service -public class DemoOtherServiceImpl implements DemoOtherService { - - private static final Logger logger = LoggerFactory.getLogger(DemoOtherServiceImpl.class); - - private CredentialService credentialService = new CredentialServiceImpl(); - - private CredentialPojoService credentialPojoService = new CredentialPojoServiceImpl(); - - private EvidenceService evidenceService = new EvidenceServiceImpl(); - - @Override - public ResponseData getCredentialHash(VerifyCredentialModel verifyCredentialModel) { - - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - try { - logger.info("verifyCredentialModel:{}", - DataToolUtils.objToJsonStrWithNoPretty(verifyCredentialModel)); - if (null == verifyCredentialModel || null == verifyCredentialModel.getCredential()) { - return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); - } - String credentialJson - = DataToolUtils.mapToCompactJson(verifyCredentialModel.getCredential()); - Credential credential = DataToolUtils.deserialize(credentialJson, Credential.class); - ResponseData responseData = credentialService.getCredentialHash(credential); - logger.info("{} responseData: {}", - methodName, DataToolUtils.objToJsonStrWithNoPretty(responseData)); - return responseData; - } catch (Exception e) { - logger.error("{} error", methodName, e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - @Override - public ResponseData createCredentialPoJo( - CreateCredentialPojoModel createCredentialPojoModel) { - - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - logger.info("{} createCredentialPojoModel: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(createCredentialPojoModel)); - - if (null == createCredentialPojoModel - || StringUtils.isBlank(createCredentialPojoModel.getIssuer()) - || null == createCredentialPojoModel.getCptId() - || null == createCredentialPojoModel.getClaimData() - || createCredentialPojoModel.getClaimData().isEmpty() - ) { - return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); - } - - CreateCredentialPojoArgs> createCredentialPojoArgs - = new CreateCredentialPojoArgs<>(); - createCredentialPojoArgs.setCptId(createCredentialPojoModel.getCptId()); - createCredentialPojoArgs.setIssuer(createCredentialPojoModel.getIssuer()); - createCredentialPojoArgs.setExpirationDate( - System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 365 * 100); - - WeIdAuthentication weIdAuthentication = - getWeIdAuthentication(createCredentialPojoModel.getIssuer()); - createCredentialPojoArgs.setWeIdAuthentication(weIdAuthentication); - - createCredentialPojoArgs.setClaim(createCredentialPojoModel.getClaimData()); - - ResponseData responseData - = credentialPojoService.createCredential(createCredentialPojoArgs); - logger.info("{} responseData:{}", - methodName, DataToolUtils.objToJsonStrWithNoPretty(responseData)); - return responseData; - } - - @Override - public ResponseData createSelectiveCredential( - CreateSelectiveCredentialModel createSelectiveCredentialModel) { - - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - try { - logger.info("{} createSelectiveCredentialModel: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(createSelectiveCredentialModel)); - - if (null == createSelectiveCredentialModel - || null == createSelectiveCredentialModel.getCredential() - || createSelectiveCredentialModel.getCredential().isEmpty() - || null == createSelectiveCredentialModel.getFieldsToBeDisclosed() - || createSelectiveCredentialModel.getFieldsToBeDisclosed().isEmpty() - ) { - return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); - } - - CredentialPojo credentialPojo = DataToolUtils.mapToObj( - createSelectiveCredentialModel.getCredential(), CredentialPojo.class); - - // 选择性披露 - ClaimPolicy claimPolicy = new ClaimPolicy(); - claimPolicy.setFieldsToBeDisclosed( - DataToolUtils.objToJsonStrWithNoPretty( - createSelectiveCredentialModel.getFieldsToBeDisclosed())); - - ResponseData selectiveResponse = - credentialPojoService.createSelectiveCredential(credentialPojo, claimPolicy); - logger.info("{} selectiveResponse: {}", - methodName, DataToolUtils.objToJsonStrWithNoPretty(selectiveResponse)); - return selectiveResponse; - } catch (Exception e) { - logger.error("{} error", methodName, e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - @Override - public ResponseData verify(VerifyCredentialPoJoModel verifyCredentialPoJoModel) { - - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - try { - logger.info("{} verifyCredentialPoJoModel: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(verifyCredentialPoJoModel)); - - if (null == verifyCredentialPoJoModel - || StringUtils.isBlank(verifyCredentialPoJoModel.getIssuerWeId()) - || null == verifyCredentialPoJoModel.getCredential() - || verifyCredentialPoJoModel.getCredential().isEmpty()) { - return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); - } - - CredentialPojo credentialPojo = DataToolUtils.mapToObj( - verifyCredentialPoJoModel.getCredential(), CredentialPojo.class); - - ResponseData responseVerify = credentialPojoService.verify( - verifyCredentialPoJoModel.getIssuerWeId(), credentialPojo); - logger.info("{} responseVerify: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(responseVerify)); - return responseVerify; - } catch (Exception e) { - logger.error("{} error", methodName, e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - @Override - public ResponseData createPresentationPolicyE( - CreatePresentationPolicyEModel createPresentationPolicyEModel) { - - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - try { - logger.info("{} verifyCredentialPoJoModel: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(createPresentationPolicyEModel)); - if (null == createPresentationPolicyEModel - || createPresentationPolicyEModel.getPresentationPolicyE().isEmpty()) { - return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); - } - - //创建PresentationPolicyE - PresentationPolicyE presentationPolicyE - = PresentationPolicyE.fromJson( - DataToolUtils.mapToCompactJson( - createPresentationPolicyEModel.getPresentationPolicyE())); - logger.info("{} presentationPolicyE: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(presentationPolicyE)); - return new ResponseData<>(presentationPolicyE, ErrorCode.SUCCESS); - } catch (Exception e) { - logger.error("{} error", methodName, e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - @Override - public ResponseData getCredentialPoJoHash( - GetCredentialHashModel getCredentialHashModel) { - - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - try { - logger.info("{} getCredentialHashModel: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(getCredentialHashModel)); - if (null == getCredentialHashModel.getCredential() - || getCredentialHashModel.getCredential().isEmpty()) { - return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); - } - - CredentialPojo credentialPojo = - DataToolUtils.mapToObj( - getCredentialHashModel.getCredential(), CredentialPojo.class); - ResponseData responseData - = credentialPojoService.getCredentialPojoHash(credentialPojo); - logger.info("{} responseData: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(responseData)); - return responseData; - } catch (Exception e) { - logger.error("{} error", methodName, e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - @Override - public ResponseData createPresentation( - CreatePresentationModel createPresentationModel) { - - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - try { - logger.info("{} createPresentationModel: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(createPresentationModel)); - - if (null == createPresentationModel - || null == createPresentationModel.getCredentialList() - || createPresentationModel.getCredentialList().isEmpty() - || StringUtils.isBlank(createPresentationModel.getChallengeUserWeId()) - || null == createPresentationModel.getPresentationPolicyE() - || createPresentationModel.getPresentationPolicyE().isEmpty() - || StringUtils.isBlank(createPresentationModel.getWeId())) { - return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); - } - - List credentialList = new ArrayList(); - for (Map map : createPresentationModel.getCredentialList()) { - CredentialPojo credentialPojo = DataToolUtils.mapToObj(map, CredentialPojo.class); - credentialList.add(credentialPojo); - } - - //创建Challenge - Challenge challenge = Challenge.create( - createPresentationModel.getChallengeUserWeId(), - String.valueOf(System.currentTimeMillis())); - - //创建PresentationPolicyE - PresentationPolicyE presentationPolicyE - = PresentationPolicyE.fromJson( - DataToolUtils.mapToCompactJson( - createPresentationModel.getPresentationPolicyE())); - - WeIdAuthentication weIdAuthentication - = getWeIdAuthentication(createPresentationModel.getWeId()); - - //创建Presentation - ResponseData presentationE = - credentialPojoService.createPresentation( - credentialList, presentationPolicyE, challenge, weIdAuthentication); - logger.info("{} presentationE: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(presentationE)); - return presentationE; - } catch (Exception e) { - logger.error("{} error", methodName, e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - @Override - public ResponseData addSignatureCredentialPojo( - CredentialPoJoAddSignature credentialPoJoAddSignature) { - - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - try { - logger.info("credentialPoJoAddSignature:{}", - DataToolUtils.objToJsonStrWithNoPretty(credentialPoJoAddSignature)); - if (null == credentialPoJoAddSignature - || null == credentialPoJoAddSignature.getCredentialList() - || 0 == credentialPoJoAddSignature.getCredentialList().size() - || StringUtils.isBlank(credentialPoJoAddSignature.getWeid())) { - return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); - } - - List credentialList = new ArrayList(); - for (Map map : credentialPoJoAddSignature.getCredentialList()) { - CredentialPojo credentialPojo = DataToolUtils.mapToObj(map, CredentialPojo.class); - credentialList.add(credentialPojo); - } - - ResponseData responseData = credentialPojoService.addSignature( - credentialList, - getWeIdAuthentication(credentialPoJoAddSignature.getWeid())); - logger.info("{} responseData: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(responseData)); - return responseData; - } catch (Exception e) { - logger.error("{} error", methodName, e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - @Override - public ResponseData createEvidence(CreateEvidenceModel createEvidenceModel) { - - logger.info("createEvidenceModel:{}", - DataToolUtils.objToJsonStrWithNoPretty(createEvidenceModel)); - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - if (null == createEvidenceModel - || StringUtils.isBlank(createEvidenceModel.getHashable()) - || StringUtils.isBlank(createEvidenceModel.getWeid())) { - return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); - } - // Hashable为接口,创建Hashable可以new实现类,例如:credentail - Hashable hashable = new HashString(createEvidenceModel.getHashable()); - - ResponseData responseData = evidenceService.createEvidence(hashable, - getWeIdPrivateKey(createEvidenceModel.getWeid())); - logger.info("{} responseData: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(responseData)); - return responseData; - } - - @Override - public ResponseData getEvidence(String evidenceAddress) { - - logger.info("evidenceAddress:{}", - DataToolUtils.objToJsonStrWithNoPretty(evidenceAddress)); - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - ResponseData responseData = evidenceService.getEvidence(evidenceAddress); - logger.info("{} responseData: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(responseData)); - return responseData; - } - - @Override - public ResponseData addSignature(AddSignatureModel addSignatureModel) { - - logger.info("addSignatureModel:{}", - DataToolUtils.objToJsonStrWithNoPretty(addSignatureModel)); - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - if (null == addSignatureModel - || StringUtils.isBlank(addSignatureModel.getEvidenceAddress()) - || StringUtils.isBlank(addSignatureModel.getHashable()) - || StringUtils.isBlank(addSignatureModel.getWeid())) { - return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); - } - // Hashable为接口,创建Hashable可以new实现类,例如:credentail - Hashable hashable = new HashString(addSignatureModel.getHashable()); - ResponseData responseData = evidenceService.addSignature( - hashable, - addSignatureModel.getEvidenceAddress(), - getWeIdPrivateKey(addSignatureModel.getWeid())); - logger.info("{} responseData: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(responseData)); - return responseData; - } - - @Override - public ResponseData verifyEvidence(VerifyEvidenceModel verifyEvidenceModel) { - - logger.info("verifyEvidenceModel:{}", - DataToolUtils.objToJsonStrWithNoPretty(verifyEvidenceModel)); - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - if (null == verifyEvidenceModel - || StringUtils.isBlank(verifyEvidenceModel.getHashable()) - || StringUtils.isBlank(verifyEvidenceModel.getEvidenceAddress())) { - return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); - } - Hashable hashable = new HashString(verifyEvidenceModel.getHashable()); - ResponseData responseData = evidenceService.verify( - hashable, - verifyEvidenceModel.getEvidenceAddress()); - logger.info("{} responseData: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(responseData)); - return responseData; - } - - @Override - public ResponseData setHashValue(SetHashValueModel setHashValueModel) { - - logger.info("setHashValueModel:{}", setHashValueModel); - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - if (null == setHashValueModel - || StringUtils.isBlank(setHashValueModel.getHashValue()) - || StringUtils.isBlank(setHashValueModel.getEvidenceAddress()) - || StringUtils.isBlank(setHashValueModel.getWeid())) { - return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); - } - - ResponseData responseData = evidenceService.setHashValue( - setHashValueModel.getHashValue(), - setHashValueModel.getEvidenceAddress(), - getWeIdPrivateKey(setHashValueModel.getWeid())); - logger.info("{} responseData: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(responseData)); - return responseData; - } - - @Override - public ResponseData specify( - JsonTransportationSpecifyModel jsonTransportationSpecifyModel) { - - logger.info("jsonTransportationSpecifyModel:{}", DataToolUtils.objToJsonStrWithNoPretty( - jsonTransportationSpecifyModel)); - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - if (null == jsonTransportationSpecifyModel - || null == jsonTransportationSpecifyModel.getVerifierWeIdList() - || 0 == jsonTransportationSpecifyModel.getVerifierWeIdList().size()) { - return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); - } - - JsonTransportation jsonTransportation = TransportationFactory - .newJsonTransportation() - .specify(jsonTransportationSpecifyModel.getVerifierWeIdList()); - logger.info("{} jsonTransportation: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(jsonTransportation)); - ResponseData responseData = new ResponseData<>(); - responseData.setResult(DataToolUtils.objToJsonStrWithNoPretty(jsonTransportation)); - return responseData; - } - - @Override - public ResponseData serialize( - JsonTransportationSerializeModel jsonTransportationSerializeModel) { - - String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); - - try { - logger.info("jsonTransportationSerializeModel:{}", - DataToolUtils.objToJsonStrWithNoPretty(jsonTransportationSerializeModel)); - - if (null == jsonTransportationSerializeModel - || null == jsonTransportationSerializeModel.getVerifierWeIdList() - || 0 == jsonTransportationSerializeModel.getVerifierWeIdList().size() - || StringUtils.isBlank(jsonTransportationSerializeModel.getEncodeType()) - || null == jsonTransportationSerializeModel.getPresentationE() - || jsonTransportationSerializeModel.getPresentationE().isEmpty()) { - return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); - } - - PresentationE presentation - = DataToolUtils.mapToObj( - jsonTransportationSerializeModel.getPresentationE(), PresentationE.class); - - //原文方式调用 - ResponseData responseData = - TransportationFactory - .newJsonTransportation() - .specify(jsonTransportationSerializeModel.getVerifierWeIdList()) - .serialize( - presentation, - new ProtocolProperty( - EncodeType.getObject( - jsonTransportationSerializeModel.getEncodeType()))); - logger.info("{} responseData: {}", methodName, - DataToolUtils.objToJsonStrWithNoPretty(responseData)); - return responseData; - } catch (Exception e) { - logger.error("{} error", methodName, e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - private WeIdPrivateKey getWeIdPrivateKey(String weid) { - String privateKey = PrivateKeyUtil - .getPrivateKeyByWeId(PrivateKeyUtil.KEY_DIR, weid); - WeIdPrivateKey weIdPrivateKey = new WeIdPrivateKey(); - weIdPrivateKey.setPrivateKey(privateKey); - return weIdPrivateKey; - } - - private WeIdAuthentication getWeIdAuthentication(String weid) { - - WeIdAuthentication weIdAuthentication = new WeIdAuthentication(); - weIdAuthentication.setWeId(weid); - WeIdPrivateKey weIdPrivateKey = getWeIdPrivateKey(weid); - weIdAuthentication.setWeIdPrivateKey(weIdPrivateKey); - weIdAuthentication.setWeIdPublicKeyId(weid + "#key0"); - return weIdAuthentication; - } -} +package com.webank.weid.demo.service.impl; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import com.webank.weid.constant.ErrorCode; +import com.webank.weid.demo.common.model.AddSignatureModel; +import com.webank.weid.demo.common.model.CreateCredentialPojoModel; +import com.webank.weid.demo.common.model.CreateEvidenceModel; +import com.webank.weid.demo.common.model.CreatePresentationModel; +import com.webank.weid.demo.common.model.CreatePresentationPolicyEModel; +import com.webank.weid.demo.common.model.CreateSelectiveCredentialModel; +import com.webank.weid.demo.common.model.CredentialPoJoAddSignature; +import com.webank.weid.demo.common.model.GetCredentialHashModel; +import com.webank.weid.demo.common.model.JsonTransportationSerializeModel; +import com.webank.weid.demo.common.model.JsonTransportationSpecifyModel; +import com.webank.weid.demo.common.model.SetHashValueModel; +import com.webank.weid.demo.common.model.VerifyCredentialModel; +import com.webank.weid.demo.common.model.VerifyCredentialPoJoModel; +import com.webank.weid.demo.common.model.VerifyEvidenceModel; +import com.webank.weid.demo.common.util.PrivateKeyUtil; +import com.webank.weid.demo.service.DemoOtherService; +import com.webank.weid.protocol.base.Challenge; +import com.webank.weid.protocol.base.ClaimPolicy; +import com.webank.weid.protocol.base.Credential; +import com.webank.weid.protocol.base.CredentialPojo; +import com.webank.weid.protocol.base.EvidenceInfo; +import com.webank.weid.protocol.base.HashString; +import com.webank.weid.protocol.base.PresentationE; +import com.webank.weid.protocol.base.PresentationPolicyE; +import com.webank.weid.protocol.base.WeIdAuthentication; +import com.webank.weid.protocol.base.WeIdPrivateKey; +import com.webank.weid.protocol.inf.Hashable; +import com.webank.weid.protocol.request.CreateCredentialPojoArgs; +import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.rpc.CredentialPojoService; +import com.webank.weid.rpc.CredentialService; +import com.webank.weid.rpc.EvidenceService; +import com.webank.weid.service.impl.CredentialPojoServiceImpl; +import com.webank.weid.service.impl.CredentialServiceImpl; +import com.webank.weid.service.impl.EvidenceServiceImpl; +import com.webank.weid.suite.api.transportation.TransportationFactory; +import com.webank.weid.suite.api.transportation.inf.JsonTransportation; +import com.webank.weid.suite.api.transportation.inf.Transportation; +import com.webank.weid.suite.api.transportation.params.EncodeType; +import com.webank.weid.suite.api.transportation.params.ProtocolProperty; +import com.webank.weid.suite.api.transportation.params.TransportationType; +import com.webank.weid.util.DataToolUtils; + +/** + * other interface. + * + * @author darwindu + * @date 2020/1/3 + **/ +@Service +public class DemoOtherServiceImpl implements DemoOtherService { + + private static final Logger logger = LoggerFactory.getLogger(DemoOtherServiceImpl.class); + + private CredentialService credentialService = new CredentialServiceImpl(); + + private CredentialPojoService credentialPojoService = new CredentialPojoServiceImpl(); + + private EvidenceService evidenceService = new EvidenceServiceImpl(); + + @Override + public ResponseData getCredentialHash(VerifyCredentialModel verifyCredentialModel) { + + String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); + try { + logger.info("verifyCredentialModel:{}", + DataToolUtils.objToJsonStrWithNoPretty(verifyCredentialModel)); + if (null == verifyCredentialModel || null == verifyCredentialModel.getCredential()) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + String credentialJson + = DataToolUtils.mapToCompactJson(verifyCredentialModel.getCredential()); + Credential credential = DataToolUtils.deserialize(credentialJson, Credential.class); + ResponseData responseData = credentialService.getCredentialHash(credential); + logger.info("{} responseData: {}", + methodName, DataToolUtils.objToJsonStrWithNoPretty(responseData)); + return responseData; + } catch (Exception e) { + logger.error("{} error", methodName, e); + return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); + } + } + + @Override + public ResponseData createCredentialPoJo( + CreateCredentialPojoModel createCredentialPojoModel) { + + String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); + logger.info("{} createCredentialPojoModel: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(createCredentialPojoModel)); + + if (null == createCredentialPojoModel + || StringUtils.isBlank(createCredentialPojoModel.getIssuer()) + || null == createCredentialPojoModel.getCptId() + || null == createCredentialPojoModel.getClaimData() + || createCredentialPojoModel.getClaimData().isEmpty() + ) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + + CreateCredentialPojoArgs> createCredentialPojoArgs + = new CreateCredentialPojoArgs<>(); + createCredentialPojoArgs.setCptId(createCredentialPojoModel.getCptId()); + createCredentialPojoArgs.setIssuer(createCredentialPojoModel.getIssuer()); + createCredentialPojoArgs.setExpirationDate( + System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 365 * 100); + + WeIdAuthentication weIdAuthentication = + getWeIdAuthentication(createCredentialPojoModel.getIssuer()); + createCredentialPojoArgs.setWeIdAuthentication(weIdAuthentication); + + createCredentialPojoArgs.setClaim(createCredentialPojoModel.getClaimData()); + + ResponseData responseData + = credentialPojoService.createCredential(createCredentialPojoArgs); + logger.info("{} responseData:{}", + methodName, DataToolUtils.objToJsonStrWithNoPretty(responseData)); + return responseData; + } + + @Override + public ResponseData createSelectiveCredential( + CreateSelectiveCredentialModel createSelectiveCredentialModel) { + + String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); + try { + logger.info("{} createSelectiveCredentialModel: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(createSelectiveCredentialModel)); + + if (null == createSelectiveCredentialModel + || null == createSelectiveCredentialModel.getCredential() + || createSelectiveCredentialModel.getCredential().isEmpty() + || null == createSelectiveCredentialModel.getFieldsToBeDisclosed() + || createSelectiveCredentialModel.getFieldsToBeDisclosed().isEmpty() + ) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + + CredentialPojo credentialPojo = DataToolUtils.mapToObj( + createSelectiveCredentialModel.getCredential(), CredentialPojo.class); + + // 选择性披露 + ClaimPolicy claimPolicy = new ClaimPolicy(); + claimPolicy.setFieldsToBeDisclosed( + DataToolUtils.objToJsonStrWithNoPretty( + createSelectiveCredentialModel.getFieldsToBeDisclosed())); + + ResponseData selectiveResponse = + credentialPojoService.createSelectiveCredential(credentialPojo, claimPolicy); + logger.info("{} selectiveResponse: {}", + methodName, DataToolUtils.objToJsonStrWithNoPretty(selectiveResponse)); + return selectiveResponse; + } catch (Exception e) { + logger.error("{} error", methodName, e); + return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); + } + } + + @Override + public ResponseData verify(VerifyCredentialPoJoModel verifyCredentialPoJoModel) { + + String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); + try { + logger.info("{} verifyCredentialPoJoModel: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(verifyCredentialPoJoModel)); + + if (null == verifyCredentialPoJoModel + || StringUtils.isBlank(verifyCredentialPoJoModel.getIssuerWeId()) + || null == verifyCredentialPoJoModel.getCredential() + || verifyCredentialPoJoModel.getCredential().isEmpty()) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + + CredentialPojo credentialPojo = DataToolUtils.mapToObj( + verifyCredentialPoJoModel.getCredential(), CredentialPojo.class); + + ResponseData responseVerify = credentialPojoService.verify( + verifyCredentialPoJoModel.getIssuerWeId(), credentialPojo); + logger.info("{} responseVerify: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(responseVerify)); + return responseVerify; + } catch (Exception e) { + logger.error("{} error", methodName, e); + return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); + } + } + + @Override + public ResponseData createPresentationPolicyE( + CreatePresentationPolicyEModel createPresentationPolicyEModel) { + + String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); + try { + logger.info("{} verifyCredentialPoJoModel: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(createPresentationPolicyEModel)); + if (null == createPresentationPolicyEModel + || createPresentationPolicyEModel.getPresentationPolicyE().isEmpty()) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + + //创建PresentationPolicyE + PresentationPolicyE presentationPolicyE + = PresentationPolicyE.fromJson( + DataToolUtils.mapToCompactJson( + createPresentationPolicyEModel.getPresentationPolicyE())); + logger.info("{} presentationPolicyE: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(presentationPolicyE)); + return new ResponseData<>(presentationPolicyE, ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("{} error", methodName, e); + return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); + } + } + + @Override + public ResponseData getCredentialPoJoHash( + GetCredentialHashModel getCredentialHashModel) { + + String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); + try { + logger.info("{} getCredentialHashModel: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(getCredentialHashModel)); + if (null == getCredentialHashModel.getCredential() + || getCredentialHashModel.getCredential().isEmpty()) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + + CredentialPojo credentialPojo = + DataToolUtils.mapToObj( + getCredentialHashModel.getCredential(), CredentialPojo.class); + ResponseData responseData + = credentialPojoService.getCredentialPojoHash(credentialPojo); + logger.info("{} responseData: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(responseData)); + return responseData; + } catch (Exception e) { + logger.error("{} error", methodName, e); + return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); + } + } + + @Override + public ResponseData createPresentation( + CreatePresentationModel createPresentationModel) { + + String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); + try { + logger.info("{} createPresentationModel: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(createPresentationModel)); + + if (null == createPresentationModel + || null == createPresentationModel.getCredentialList() + || createPresentationModel.getCredentialList().isEmpty() + || StringUtils.isBlank(createPresentationModel.getChallengeUserWeId()) + || null == createPresentationModel.getPresentationPolicyE() + || createPresentationModel.getPresentationPolicyE().isEmpty() + || StringUtils.isBlank(createPresentationModel.getWeId())) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + + List credentialList = new ArrayList(); + for (Map map : createPresentationModel.getCredentialList()) { + CredentialPojo credentialPojo = DataToolUtils.mapToObj(map, CredentialPojo.class); + credentialList.add(credentialPojo); + } + + //创建Challenge + Challenge challenge = Challenge.create( + createPresentationModel.getChallengeUserWeId(), + String.valueOf(System.currentTimeMillis())); + + //创建PresentationPolicyE + PresentationPolicyE presentationPolicyE + = PresentationPolicyE.fromJson( + DataToolUtils.mapToCompactJson( + createPresentationModel.getPresentationPolicyE())); + + WeIdAuthentication weIdAuthentication + = getWeIdAuthentication(createPresentationModel.getWeId()); + + //创建Presentation + ResponseData presentationE = + credentialPojoService.createPresentation( + credentialList, presentationPolicyE, challenge, weIdAuthentication); + logger.info("{} presentationE: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(presentationE)); + return presentationE; + } catch (Exception e) { + logger.error("{} error", methodName, e); + return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); + } + } + + @Override + public ResponseData addSignatureCredentialPojo( + CredentialPoJoAddSignature credentialPoJoAddSignature) { + + String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); + try { + logger.info("credentialPoJoAddSignature:{}", + DataToolUtils.objToJsonStrWithNoPretty(credentialPoJoAddSignature)); + if (null == credentialPoJoAddSignature + || null == credentialPoJoAddSignature.getCredentialList() + || 0 == credentialPoJoAddSignature.getCredentialList().size() + || StringUtils.isBlank(credentialPoJoAddSignature.getWeid())) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + + List credentialList = new ArrayList(); + for (Map map : credentialPoJoAddSignature.getCredentialList()) { + CredentialPojo credentialPojo = DataToolUtils.mapToObj(map, CredentialPojo.class); + credentialList.add(credentialPojo); + } + + ResponseData responseData = credentialPojoService.addSignature( + credentialList, + getWeIdAuthentication(credentialPoJoAddSignature.getWeid())); + logger.info("{} responseData: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(responseData)); + return responseData; + } catch (Exception e) { + logger.error("{} error", methodName, e); + return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); + } + } + + @Override + public ResponseData createEvidence(CreateEvidenceModel createEvidenceModel) { + + logger.info("createEvidenceModel:{}", + DataToolUtils.objToJsonStrWithNoPretty(createEvidenceModel)); + String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); + if (null == createEvidenceModel + || StringUtils.isBlank(createEvidenceModel.getHashable()) + || StringUtils.isBlank(createEvidenceModel.getWeid())) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + // Hashable为接口,创建Hashable可以new实现类,例如:credentail + Hashable hashable = new HashString(createEvidenceModel.getHashable()); + + ResponseData responseData = evidenceService.createEvidence(hashable, + getWeIdPrivateKey(createEvidenceModel.getWeid())); + logger.info("{} responseData: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(responseData)); + return responseData; + } + + @Override + public ResponseData getEvidence(String evidenceAddress) { + + logger.info("evidenceAddress:{}", + DataToolUtils.objToJsonStrWithNoPretty(evidenceAddress)); + String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); + ResponseData responseData = evidenceService.getEvidence(evidenceAddress); + logger.info("{} responseData: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(responseData)); + return responseData; + } + + @Override + public ResponseData specify( + JsonTransportationSpecifyModel jsonTransportationSpecifyModel) { + + logger.info("jsonTransportationSpecifyModel:{}", DataToolUtils.objToJsonStrWithNoPretty( + jsonTransportationSpecifyModel)); + String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); + if (null == jsonTransportationSpecifyModel + || null == jsonTransportationSpecifyModel.getVerifierWeIdList() + || 0 == jsonTransportationSpecifyModel.getVerifierWeIdList().size()) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + + Transportation transportation = TransportationFactory.build(TransportationType.JSON) + .specify(jsonTransportationSpecifyModel.getVerifierWeIdList()); + logger.info("{} jsonTransportation: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(transportation)); + ResponseData responseData = new ResponseData<>(); + responseData.setResult(DataToolUtils.objToJsonStrWithNoPretty(transportation)); + return responseData; + } + + @Override + public ResponseData serialize( + JsonTransportationSerializeModel jsonTransportationSerializeModel) { + + String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); + + try { + logger.info("jsonTransportationSerializeModel:{}", + DataToolUtils.objToJsonStrWithNoPretty(jsonTransportationSerializeModel)); + + if (null == jsonTransportationSerializeModel + || null == jsonTransportationSerializeModel.getVerifierWeIdList() + || 0 == jsonTransportationSerializeModel.getVerifierWeIdList().size() + || StringUtils.isBlank(jsonTransportationSerializeModel.getEncodeType()) + || null == jsonTransportationSerializeModel.getPresentationE() + || jsonTransportationSerializeModel.getPresentationE().isEmpty()) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + + PresentationE presentation + = DataToolUtils.mapToObj( + jsonTransportationSerializeModel.getPresentationE(), PresentationE.class); + + //原文方式调用 + ResponseData responseData = + TransportationFactory + .newJsonTransportation() + .specify(jsonTransportationSerializeModel.getVerifierWeIdList()) + .serialize( + presentation, + new ProtocolProperty( + EncodeType.getEncodeType( + Integer.valueOf(jsonTransportationSerializeModel.getEncodeType())))); + logger.info("{} responseData: {}", methodName, + DataToolUtils.objToJsonStrWithNoPretty(responseData)); + return responseData; + } catch (Exception e) { + logger.error("{} error", methodName, e); + return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); + } + } + + private WeIdPrivateKey getWeIdPrivateKey(String weid) { + String privateKey = PrivateKeyUtil + .getPrivateKeyByWeId(PrivateKeyUtil.KEY_DIR, weid); + WeIdPrivateKey weIdPrivateKey = new WeIdPrivateKey(); + weIdPrivateKey.setPrivateKey(privateKey); + return weIdPrivateKey; + } + + private WeIdAuthentication getWeIdAuthentication(String weid) { + + WeIdAuthentication weIdAuthentication = new WeIdAuthentication(); + weIdAuthentication.setWeId(weid); + WeIdPrivateKey weIdPrivateKey = getWeIdPrivateKey(weid); + weIdAuthentication.setWeIdPrivateKey(weIdPrivateKey); + weIdAuthentication.setWeIdPublicKeyId(weid + "#key0"); + return weIdAuthentication; + } +} diff --git a/src/main/resources/fisco.properties.tpl b/src/main/resources/fisco.properties.tpl deleted file mode 100644 index 9108533..0000000 --- a/src/main/resources/fisco.properties.tpl +++ /dev/null @@ -1,32 +0,0 @@ -# Fisco-bcos blockchain node related properties - -# Version -bcos.version=1 - -# contract address -weId.contractaddress=0x0 -cpt.contractaddress=0x0 -issuer.contractaddress=0x0 -evidence.contractaddress=0x0 -specificissuer.contractaddress=0x0 - -# blockchain connection params -chain.id=101 -web3sdk.timeout=10 -web3sdk.core-pool-size=100 -web3sdk.max-pool-size=200 -web3sdk.queue-capacity=1000 -web3sdk.keep-alive-seconds=60 - -# Fisco-Bcos 2.x params, including Group ID and Encrypt Type -group.id=1 -encrypt.type=0 - -# config files params -v1.ca-crt-path=ca.crt -v1.client-crt-password=123456 -v1.client-key-store-path=client.keystore -v1.key-store-password=123456 -v2.ca-crt-path=ca.crt -v2.node-crt-path=node.crt -v2.node-key-path=node.key diff --git a/src/main/resources/weidentity.properties.tpl b/src/main/resources/weidentity.properties.tpl deleted file mode 100644 index 8523c3c..0000000 --- a/src/main/resources/weidentity.properties.tpl +++ /dev/null @@ -1,67 +0,0 @@ -# The organization ID for AMOP communication. -blockchain.orgid=organizationName - -# Persistence Layer configurations. Do NOT change this if you are not using Persistence Layer features! -# MySQL connection config -# Support multiple data source configurations with comma-separated multiple data sources. -datasource.name=datasource1 - -# The configuration of each data source is prefixed by the name of the data source. -datasource1.jdbc.url=jdbc:mysql://0.0.0.0:3306/mysql?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false -datasource1.jdbc.username=user -datasource1.jdbc.password=password -datasource1.jdbc.maxActive=50 -datasource1.jdbc.minIdle=5 -datasource1.jdbc.maxIdle=5 -datasource1.jdbc.maxWait=10000 -datasource1.jdbc.timeBetweenEvictionRunsMillis=600000 -datasource1.jdbc.numTestsPerEvictionRun=5 -datasource1.jdbc.minEvictableIdleTimeMillis=1800000 - -# Domain configuration, which divides colons into two segments, the first segment is the name of the data source, -# the second segment is the name of the table, and if not, the default is the first data source and the default table `sdk_all_data`, -# Multiple domains can be configured at the same time. -# example: -# domain.credential=datasource1:credential_data -# domain.credential.timeout=86400000 -# domain.weidDocument=datasource1:weid_document_data -# domain.credential.timeout=86400000 - -domain.default=datasource1:default_data -domain.default.timeout=86400000 - -domain.encryptKey=datasource1:encryptKey_data -domain.encryptKey.timeout=86400000 - -domain.zkp=datasource1:zkp_data - -domain.templateSecret=datasource1:template_secret -domain.templateSecret.timeout=31556908799941 - -domain.masterKey=datasource1:master_secret - -domain.credentialSignature=datasource1:credential_signature - -# Salt length for Proof creation. -salt.length=5 - -# Default length of array value in CPT when creating credential based on ZKP. -zkp.cpt.array.length=5 - -# AMOP Config -# Timeout for amop request, default: 5000ms -amop.request.timeout=5000 - -# Blockchain node info. -nodes=${BLOCKCHIAN_NODE_INFO} - -# Endpoint Service Integration-side parameters -# Listener port required to be opened for RPC Server, default: 6010 -rpc.listener.port=6010 - -# Timestamp Service Parameters -wesign.accessTokenUrl= -wesign.signTicketUrl= -wesign.timestampUrl= -wesign.appId= -wesign.secret= \ No newline at end of file