├── README.md ├── README_ZH.md ├── SafetyDetect-SysIntegrity-Server-Sample ├── LICENSE ├── README.md ├── README_ZH.md ├── Third Party Open Source Software Notice.docx ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── huawei │ └── hms │ └── safetydetect │ └── sample │ └── sysintegrity │ ├── Main.java │ ├── entity │ └── Jws.java │ └── utils │ └── VerifySignatureUtil.java └── SafetyDetect-UserDetect-Server-Sample ├── LICENSE ├── README.md ├── README_ZH.md ├── Third Party Open Source Software Notice.docx ├── pom.xml └── src └── main ├── java └── com │ └── huawei │ └── safetydetect │ └── userdetect │ ├── UserDetectApplication.java │ ├── controller │ └── UserDetectController.java │ └── service │ ├── UserDetectService.java │ └── impl │ └── UserDetectServiceImpl.java └── resources ├── application.properties └── logback.xml /README.md: -------------------------------------------------------------------------------- 1 | # HMS Safetydetect Server Demo 2 | 3 | English | [中文](https://github.com/HMS-Core/hms-safetydetect-demo-java/blob/master/README_ZH.md) 4 | 5 | ## Introduction 6 | 7 | This project contains SafetyDetect Server Sample.The project directory is as follows: 8 | 9 | 1. [SafetyDetect-SysIntegrity-Server-Sample](https://github.com/HMS-Core/hms-safetydetect-demo-java/tree/master/SafetyDetect-SysIntegrity-Server-Sample): SafetyDetect SysIntegrity Server Sample provides sample program to verify the check result on your server. 10 | 2. [SafetyDetect-UserDetect-Server-Sample](https://github.com/HMS-Core/hms-safetydetect-demo-java/tree/master/SafetyDetect-UserDetect-Server-Sample): SafetyDetect UserDetect Server Sample provides sample program to obtain the detection result. 11 | 12 | ## Question or issues 13 | If you want to evaluate more about HMS Core, [r/HMSCore on Reddit](https://www.reddit.com/r/HuaweiDevelopers/) is for you to keep up with latest news about HMS Core, and to exchange insights with other developers. 14 | 15 | If you have questions about how to use HMS samples, try the following options: 16 | - [Stack Overflow](https://stackoverflow.com/questions/tagged/huawei-mobile-services) is the best place for any programming questions. Be sure to tag your question with 17 | `huawei-mobile-services`. 18 | - [Huawei Developer Forum](https://forums.developer.huawei.com/forumPortal/en/home?fid=0101187876626530001) HMS Core Module is great for general questions, or seeking recommendations and opinions. 19 | 20 | If you run into a bug in our samples, please submit an [issue](https://github.com/HMS-Core/hms-safetydetect-demo-java/issues) to the Repository. Even better you can submit a [Pull Request](https://github.com/HMS-Core/hms-safetydetect-demo-java/pulls) with a fix. 21 | -------------------------------------------------------------------------------- /README_ZH.md: -------------------------------------------------------------------------------- 1 | # HMS Safetydetect Server Demo 2 | 3 | [English](https://github.com/HMS-Core/hms-safetydetect-demo-java/blob/master/README.md) | 中文 4 | 5 | ## Introduction 6 | 7 | 本项目包含SafetyDetect 服务端代码示例.工程目录如下: 8 | 9 | 1. [SafetyDetect-SysIntegrity-Server-Sample](https://github.com/HMS-Core/hms-safetydetect-demo-java/tree/master/SafetyDetect-SysIntegrity-Server-Sample): 提供SysIntegrity服务端代码示例。 10 | 2. [SafetyDetect-UserDetect-Server-Sample](https://github.com/HMS-Core/hms-safetydetect-demo-java/tree/master/SafetyDetect-UserDetect-Server-Sample): 提供UserDetect服务端代码示例。 11 | 12 | ## 技术支持 13 | 如果您对HMS Core还处于评估阶段,可在[Reddit社区](https://www.reddit.com/r/HuaweiDevelopers/)获取关于HMS Core的最新讯息,并与其他开发者交流见解。 14 | 15 | 如果您对使用HMS示例代码有疑问,请尝试: 16 | - 开发过程遇到问题上[Stack Overflow](https://stackoverflow.com/questions/tagged/huawei-mobile-services),在`huawei-mobile-services`标签下提问,有华为研发专家在线一对一解决您的问题。 17 | - 到[华为开发者论坛](https://developer.huawei.com/consumer/cn/forum/blockdisplay?fid=18) HMS Core板块与其他开发者进行交流。 18 | 19 | 如果您在尝试示例代码中遇到问题,请向仓库提交[issue](https://github.com/HMS-Core/hms-safetydetect-demo-java/issues),也欢迎您提交[Pull Request](https://github.com/HMS-Core/hms-safetydetect-demo-java)。 20 | -------------------------------------------------------------------------------- /SafetyDetect-SysIntegrity-Server-Sample/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | 3 | Version 2.0, January 2004 4 | 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 16 | 17 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 18 | 19 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 20 | 21 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 22 | 23 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 24 | 25 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 26 | 27 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 28 | 29 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 30 | 31 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 32 | 33 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 34 | 35 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 36 | 37 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 38 | You must cause any modified files to carry prominent notices stating that You changed the files; and 39 | You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 40 | If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 41 | 42 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 43 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 44 | 45 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 46 | 47 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 48 | 49 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 50 | 51 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 52 | 53 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /SafetyDetect-SysIntegrity-Server-Sample/README.md: -------------------------------------------------------------------------------- 1 | # SafetyDetect SysIntegrity Server Sample 2 | 3 | English | [中文](https://github.com/HMS-Core/hms-safetydetect-demo-java/blob/master/SafetyDetect-SysIntegrity-Server-Sample/README_ZH.md) 4 | 5 | ## Table of Contents 6 | 7 | * [Introduction](#introduction) 8 | * [Installation](#installation) 9 | * [Configuration ](#configuration ) 10 | * [Supported Environments](#supported-environments) 11 | * [Sample Code](#sample-code) 12 | * [License](#license) 13 | 14 | 15 | ## Introduction 16 | SafetyDetect SysIntegrity Server Sample provides sample program to verify the check result on your server. 17 | 18 | ## Getting Started 19 | Before using SafetyDetect SysIntegrity Server Sample code, check whether java environment and Maven has been installed. 20 | Decompress the SafetyDetect SysIntegrity Server sample code package. 21 | 22 | ## Supported Environments 23 | Java 1.7 or a later version is recommended. 24 | 25 | ## Configuration 26 | No additional configuration is required. 27 | 28 | ## Sample Code 29 | 30 | 1. Parse the JWS-format result to obtain header, payload, and signature. 31 | 2. Obtain the certificate chain from header and use the HUAWEI CBG Root CA certificate to verify it. 32 | 3. Verify the domain name of the leaf certificate in the certificate chain. The correct domain name is sysintegrity.platform.hicloud.com. 33 | 4. Obtain the signature from signature and verify it. 34 | 5. Obtain the integrity verification result from payload. The format and example are as follows: 35 | ```json 36 | { 37 | "advice":"RESTORE_TO_FACTORY_ROM", 38 | "apkCertificateDigestSha256":[ 39 | "yT5JtXRgeIgXssx1gQTsMA9GzM9ER4xAgCsCC69Fz3I=" 40 | ], 41 | "apkDigestSha256":"6Ihk8Wcv1MLm0O5KUCEVYCI/0KWzAHn9DyN38R3WYu8=", 42 | "apkPackageName":"com.huawei.hms.safetydetectsample", 43 | "basicIntegrity":false, 44 | "nonce":"R2Rra24fVm5xa2Mg", 45 | "timestampMs":1571708929141 46 | } 47 | ``` 48 | More API information please visit 49 | https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/SafetyDetectSysIntegrityDevelopment 50 | 51 | ## License 52 | SafetyDetect SysIntegrity Server Sample is licensed under the [Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). 53 | 54 | -------------------------------------------------------------------------------- /SafetyDetect-SysIntegrity-Server-Sample/README_ZH.md: -------------------------------------------------------------------------------- 1 | # SafetyDetect SysIntegrity Server Sample 2 | 3 | [English](https://github.com/HMS-Core/hms-safetydetect-demo-java/blob/master/SafetyDetect-SysIntegrity-Server-Sample/README.md) | 中文 4 | 5 | ## 目录 6 | 7 | * [介绍](#介绍) 8 | * [运行步骤](#运行步骤) 9 | * [支持环境](#支持环境) 10 | * [示例代码](#示例代码) 11 | * [许可证](#许可证) 12 | 13 | 14 | ## 介绍 15 | SafetyDetect SysIntegrity Server Sample 提供了在服务端验证结果的示例代码。 16 | ## 运行步骤 17 | 在运行SafetyDetect SysIntegrity Server Sample之前,请检查是否安装Java以及Maven。 18 | 19 | ## 支持环境 20 | Java 1.7 及以上 21 | 22 | ## 示例代码 23 | 24 | 1. 解析JWS,获取header,payload,signature。 25 | 2. 从header中获取证书链,使用HUAWEI CBG root证书对其进行验证。 26 | 3. 校验证书链中的叶证书域名,域名:sysintegrity.platform.hicloud.com。 27 | 4. 从signature中获取签名,校验其签名。 28 | 5. 从payload中获取完整性验证结果,格式和样例摘录如下: 29 | ```json 30 | { 31 | "advice":"RESTORE_TO_FACTORY_ROM", 32 | "apkCertificateDigestSha256":[ 33 | "yT5JtXRgeIgXssx1gQTsMA9GzM9ER4xAgCsCC69Fz3I=" 34 | ], 35 | "apkDigestSha256":"6Ihk8Wcv1MLm0O5KUCEVYCI/0KWzAHn9DyN38R3WYu8=", 36 | "apkPackageName":"com.huawei.hms.safetydetectsample", 37 | "basicIntegrity":false, 38 | "nonce":"R2Rra24fVm5xa2Mg", 39 | "timestampMs":1571708929141 40 | } 41 | ``` 42 | 更多信息请访问 43 | https://developer.huawei.com/consumer/cn/doc/development/HMS-Guides/SafetyDetectSysIntegrityDevelopment 44 | 45 | ## 许可证 46 | 此代码已获得 [Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). 47 | 48 | -------------------------------------------------------------------------------- /SafetyDetect-SysIntegrity-Server-Sample/Third Party Open Source Software Notice.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HMS-Core/hms-safetydetect-demo-java/5e7ea83710e889e597e4531354d60e9da13472da/SafetyDetect-SysIntegrity-Server-Sample/Third Party Open Source Software Notice.docx -------------------------------------------------------------------------------- /SafetyDetect-SysIntegrity-Server-Sample/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.huawei.hms.safetydetect.sample 8 | safety-detect-server-sample 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 1.8 13 | 1.8 14 | 15 | 16 | 17 | 18 | com.alibaba 19 | fastjson 20 | 1.2.62 21 | 22 | 23 | org.apache.httpcomponents 24 | httpclient 25 | 4.5.7 26 | 27 | 28 | 29 | 30 | 31 | 32 | org.apache.maven.plugins 33 | maven-compiler-plugin 34 | 3.6.1 35 | 36 | 1.8 37 | 1.8 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /SafetyDetect-SysIntegrity-Server-Sample/src/main/java/com/huawei/hms/safetydetect/sample/sysintegrity/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. 3 | 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.huawei.hms.safetydetect.sample.sysintegrity; 19 | 20 | import com.huawei.hms.safetydetect.sample.sysintegrity.entity.Jws; 21 | import com.huawei.hms.safetydetect.sample.sysintegrity.utils.VerifySignatureUtil; 22 | 23 | import java.security.NoSuchAlgorithmException; 24 | import java.util.Scanner; 25 | 26 | /** 27 | * Description: Main Entry 28 | * 29 | */ 30 | public class Main { 31 | 32 | public static void main(String[] args) 33 | throws NoSuchAlgorithmException { 34 | System.out.println("Paste your jws here:"); 35 | Scanner scanner = new Scanner(System.in); 36 | String jwsStr = scanner.nextLine(); 37 | //todo Please download cbg root cert from https://developer.huawei.com/consumer/cn/doc/development/HMS-Guides/SafetyDetectSysIntegrityDevelopment 38 | System.out.println("Input your certPath here:"); 39 | String filepath = scanner.nextLine(); 40 | scanner.close(); 41 | 42 | Jws jws = new Jws(jwsStr); 43 | boolean verify = VerifySignatureUtil.verifySignature(jws,filepath); 44 | 45 | if (verify) { 46 | System.out.println(jws.getPayload().toString()); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /SafetyDetect-SysIntegrity-Server-Sample/src/main/java/com/huawei/hms/safetydetect/sample/sysintegrity/entity/Jws.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. 3 | 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.huawei.hms.safetydetect.sample.sysintegrity.entity; 18 | 19 | import com.alibaba.fastjson.JSON; 20 | 21 | import java.util.Base64; 22 | import java.util.List; 23 | 24 | /** 25 | * Description: JSON Web Signature 26 | * 27 | */ 28 | public class Jws { 29 | 30 | private JwsHeader header; 31 | 32 | private JwsPayload payload; 33 | 34 | private String signContent; 35 | 36 | private byte[] signature; 37 | 38 | public Jws(String jwsStr) { 39 | String[] jwsSplit = jwsStr.split("\\."); 40 | 41 | header = JSON.parseObject(Base64.getUrlDecoder().decode(jwsSplit[0]), JwsHeader.class); 42 | payload = JSON.parseObject(Base64.getUrlDecoder().decode(jwsSplit[1]), JwsPayload.class); 43 | int index = jwsStr.lastIndexOf("."); 44 | signContent = jwsStr.substring(0, index); 45 | signature = Base64.getUrlDecoder().decode(jwsSplit[2]); 46 | } 47 | 48 | public JwsHeader getHeader() { 49 | return header; 50 | } 51 | 52 | public void setHeader(JwsHeader header) { 53 | this.header = header; 54 | } 55 | 56 | public JwsPayload getPayload() { 57 | return payload; 58 | } 59 | 60 | public void setPayload(JwsPayload payload) { 61 | this.payload = payload; 62 | } 63 | 64 | public String getSignContent() { 65 | return signContent; 66 | } 67 | 68 | public void setSignContent(String signContent) { 69 | this.signContent = signContent; 70 | } 71 | 72 | public byte[] getSignature() { 73 | return signature; 74 | } 75 | 76 | public void setSignature(byte[] signature) { 77 | this.signature = signature; 78 | } 79 | 80 | public static class JwsHeader { 81 | 82 | private String alg; 83 | 84 | private List x5c; 85 | 86 | public String getAlg() { 87 | return alg; 88 | } 89 | 90 | public void setAlg(String alg) { 91 | this.alg = alg; 92 | } 93 | 94 | public List getX5c() { 95 | return x5c; 96 | } 97 | 98 | public void setX5c(List x5c) { 99 | this.x5c = x5c; 100 | } 101 | } 102 | 103 | public static class JwsPayload { 104 | 105 | private String nonce; 106 | 107 | private String apkPackageName; 108 | 109 | private String apkDigestSha256; 110 | 111 | private String[] apkCertificateDigestSha256; 112 | 113 | private boolean basicIntegrity; 114 | 115 | private String timestampMs; 116 | 117 | private String advice; 118 | 119 | public String getNonce() { 120 | return nonce; 121 | } 122 | 123 | public void setNonce(String nonce) { 124 | this.nonce = nonce; 125 | } 126 | 127 | public String getApkPackageName() { 128 | return apkPackageName; 129 | } 130 | 131 | public void setApkPackageName(String apkPackageName) { 132 | this.apkPackageName = apkPackageName; 133 | } 134 | 135 | public String getApkDigestSha256() { 136 | return apkDigestSha256; 137 | } 138 | 139 | public void setApkDigestSha256(String apkDigestSha256) { 140 | this.apkDigestSha256 = apkDigestSha256; 141 | } 142 | 143 | public String[] getApkCertificateDigestSha256() { 144 | return apkCertificateDigestSha256; 145 | } 146 | 147 | public void setApkCertificateDigestSha256(String[] apkCertificateDigestSha256) { 148 | this.apkCertificateDigestSha256 = apkCertificateDigestSha256; 149 | } 150 | 151 | 152 | public boolean isBasicIntegrity() { 153 | return basicIntegrity; 154 | } 155 | 156 | public void setBasicIntegrity(boolean basicIntegrity) { 157 | this.basicIntegrity = basicIntegrity; 158 | } 159 | 160 | public String getTimestampMs() { 161 | return timestampMs; 162 | } 163 | 164 | public void setTimestampMs(String timestampMs) { 165 | this.timestampMs = timestampMs; 166 | } 167 | 168 | public String getAdvice() { 169 | return advice; 170 | } 171 | 172 | public void setAdvice(String advice) { 173 | this.advice = advice; 174 | } 175 | 176 | @Override 177 | public String toString() { 178 | return JSON.toJSONString(this); 179 | } 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /SafetyDetect-SysIntegrity-Server-Sample/src/main/java/com/huawei/hms/safetydetect/sample/sysintegrity/utils/VerifySignatureUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. 3 | 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.huawei.hms.safetydetect.sample.sysintegrity.utils; 19 | 20 | import com.huawei.hms.safetydetect.sample.sysintegrity.Main; 21 | import com.huawei.hms.safetydetect.sample.sysintegrity.entity.Jws; 22 | import org.apache.http.conn.ssl.DefaultHostnameVerifier; 23 | 24 | import javax.net.ssl.SSLException; 25 | import java.io.ByteArrayInputStream; 26 | import java.io.FileInputStream; 27 | import java.io.IOException; 28 | import java.io.InputStream; 29 | import java.nio.charset.StandardCharsets; 30 | import java.security.InvalidKeyException; 31 | import java.security.NoSuchAlgorithmException; 32 | import java.security.NoSuchProviderException; 33 | import java.security.PublicKey; 34 | import java.security.Signature; 35 | import java.security.SignatureException; 36 | import java.security.cert.CertificateException; 37 | import java.security.cert.CertificateFactory; 38 | import java.security.cert.X509Certificate; 39 | import java.util.Base64; 40 | import java.util.List; 41 | import java.util.Scanner; 42 | 43 | /** 44 | * Description: Verify cert chain, signature and hostname 45 | * 46 | */ 47 | public class VerifySignatureUtil { 48 | 49 | private static final DefaultHostnameVerifier HOSTNAME_VERIFIER = new DefaultHostnameVerifier(); 50 | 51 | private static X509Certificate caCert; 52 | 53 | public static boolean verifySignature(Jws jws,String filepath) 54 | throws NoSuchAlgorithmException { 55 | 56 | try (FileInputStream in = new FileInputStream(filepath)) { 57 | CertificateFactory cf = CertificateFactory.getInstance("X.509"); 58 | caCert = (X509Certificate) cf.generateCertificate(in); 59 | } catch (IOException | CertificateException e) { 60 | e.printStackTrace(); 61 | } 62 | 63 | String algorithm = jws.getHeader().getAlg(); 64 | if ("RS256".equals(algorithm)) { 65 | Signature signatureAlg = Signature.getInstance("SHA256withRSA"); 66 | return verify(signatureAlg, jws); 67 | } 68 | return false; 69 | } 70 | 71 | private static boolean verify(Signature signatureAlgorithm, Jws jws) { 72 | // Verify cert chain 73 | List certs = jws.getHeader().getX5c(); 74 | X509Certificate[] certificates = new X509Certificate[certs.size()]; 75 | try { 76 | for (int i = 0; i < certs.size(); i++) { 77 | X509Certificate tmp = readCert(certs.get(i)); 78 | certificates[i] = tmp; 79 | } 80 | verifyCertChain(certificates); 81 | } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException e) { 82 | return false; 83 | } 84 | 85 | //verify hostname 86 | try { 87 | HOSTNAME_VERIFIER.verify("sysintegrity.platform.hicloud.com", certificates[0]); 88 | } catch (SSLException e) { 89 | return false; 90 | } 91 | 92 | //verify signature 93 | PublicKey pubKey = certificates[0].getPublicKey(); 94 | try { 95 | signatureAlgorithm.initVerify(pubKey); 96 | signatureAlgorithm.update(jws.getSignContent().getBytes(StandardCharsets.UTF_8)); 97 | return signatureAlgorithm.verify(jws.getSignature()); 98 | } catch (InvalidKeyException | SignatureException e) { 99 | return false; 100 | } 101 | } 102 | 103 | private static void verifyCertChain(X509Certificate[] certs) 104 | throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, 105 | SignatureException { 106 | // verify except the last 107 | for (int i = 0; i < certs.length - 1; ++i) { 108 | // Verify that the certificate has not expired. 109 | certs[i].checkValidity(); 110 | PublicKey pubKey = certs[i + 1].getPublicKey(); 111 | certs[i].verify(pubKey); 112 | } 113 | PublicKey caPubKey = caCert.getPublicKey(); 114 | certs[certs.length - 1].verify(caPubKey); 115 | } 116 | 117 | private static X509Certificate readCert(String cert) 118 | throws CertificateException { 119 | try (InputStream in = new ByteArrayInputStream(Base64.getDecoder().decode(cert))) { 120 | CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); 121 | return (X509Certificate) certFactory.generateCertificate(in); 122 | } catch (IOException e) { 123 | throw new CertificateException("io exception when read cert", e); 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /SafetyDetect-UserDetect-Server-Sample/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2018 HUAWEI 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /SafetyDetect-UserDetect-Server-Sample/README.md: -------------------------------------------------------------------------------- 1 | # SafetyDetect UserDetect Server Sample 2 | 3 | English | [中文](https://github.com/HMS-Core/hms-safetydetect-demo-java/blob/master/SafetyDetect-UserDetect-Server-Sample/README_ZH.md) 4 | 5 | 6 | ## Table of Contents 7 | 8 | * [Introduction](#introduction) 9 | * [Installation](#installation) 10 | * [Configuration ](#configuration ) 11 | * [Supported Environments](#supported-environments) 12 | * [Sample Code](#sample-code) 13 | * [License](#license) 14 | 15 | 16 | ## Introduction 17 | SafetyDetect UserDetect Server Sample provides sample program to obtain the detection result. 18 | 19 | ## Getting Started 20 | Before using SafetyDetect UserDetect Server Sample code, check whether java environment and Maven has been installed. 21 | Decompress the SafetyDetect UserDetect Server sample code package. 22 | 23 | ## Supported Environments 24 | Java 1.7 or a later version is recommended. 25 | 26 | ## Configuration 27 | No additional configuration is required. 28 | 29 | ## Sample Code 30 | Perform the following steps on the server: 31 | 1. Obtain an access token. 32 | 2. Call the cloud-side API to obtain the detection result. 33 | 34 | The procedure is as follows: 35 | Obtain an access token. 36 | For details, please refer to Open Platform Authentication. 37 | Call the cloud-side API to obtain the detection result. The following is a request example: 38 | 39 | ```json 40 | POST https://hirms.cloud.huawei.com/rms/v1/userRisks/verify?appId=123456 HTTP/1.1 41 | Content-Type: application/json;charset=utf-8 42 | { 43 | "accessToken":"AAWWHI94sgUR2RU5_P1ZptUiwLq7W8XWJO2LxaAPuXw4_HOJFXnBlN-q5_3bwlxVW_SHeDPx_s5bWW-9DjtWZsvcm9CwXe1FHJg0u-D2pcQPcb3sTxDTJeiwEb9WBPl_9w", 44 | "response":"bc9d6e73-b422-4d7c-8464-2a8b5ad5b525" 45 | } 46 | ``` 47 | More API information please visit 48 | https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/SafetyDetectUserDetectDevelopment 49 | 50 | ## License 51 | SafetyDetect UserDetect Server Sample is licensed under the [Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). 52 | 53 | -------------------------------------------------------------------------------- /SafetyDetect-UserDetect-Server-Sample/README_ZH.md: -------------------------------------------------------------------------------- 1 | # SafetyDetect UserDetect Server Sample 2 | 3 | [English](https://github.com/HMS-Core/hms-safetydetect-demo-java/blob/master/SafetyDetect-UserDetect-Server-Sample/README.md) | 中文 4 | 5 | 6 | ## 目录 7 | 8 | * [介绍](#介绍) 9 | * [运行步骤](#运行步骤) 10 | * [支持环境](#支持环境) 11 | * [示例代码](#示例代码) 12 | * [许可证](#许可证) 13 | 14 | 15 | ## 介绍 16 | SafetyDetect UserDetect Server Sample提供了获取服务端结果的示例代码. 17 | 18 | ## 运行步骤 19 | 在运行SafetyDetect UserDetect Server Sample之前,请检查是否安装Java以及Maven。 20 | ## 支持环境 21 | Java 1.7 及以上 22 | 23 | ## 示例代码 24 | 服务端主要分为两步: 25 | 1. 获取accessToken。 26 | 2. 调用云侧API获取检测结果。 27 | 28 | 具体步骤如下: 29 | 获取accessToken. 30 | 详细请参见[开放平台鉴权相关内容描述](https://developer.huawei.com/consumer/cn/doc/HMSCore-Guides-V5/open-platform-oauth-0000001050123437-V5)。 31 | 调用云侧API获取检测结果:调用云侧获取结果。消息请求示例如下所示: 32 | 33 | ```json 34 | POST https://hirms.cloud.huawei.com/rms/v1/userRisks/verify?appId=123456 HTTP/1.1 35 | Content-Type: application/json;charset=utf-8 36 | { 37 | "accessToken":"AAWWHI94sgUR2RU5_P1ZptUiwLq7W8XWJO2LxaAPuXw4_HOJFXnBlN-q5_3bwlxVW_SHeDPx_s5bWW-9DjtWZsvcm9CwXe1FHJg0u-D2pcQPcb3sTxDTJeiwEb9WBPl_9w", 38 | "response":"bc9d6e73-b422-4d7c-8464-2a8b5ad5b525" 39 | } 40 | ``` 41 | 更多信息请访问 42 | https://developer.huawei.com/consumer/cn/doc/development/HMS-Guides/SafetyDetectUserDetectDevelopment 43 | 44 | ## 许可证 45 | 此示例代码已获得 [Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). 46 | 47 | -------------------------------------------------------------------------------- /SafetyDetect-UserDetect-Server-Sample/Third Party Open Source Software Notice.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HMS-Core/hms-safetydetect-demo-java/5e7ea83710e889e597e4531354d60e9da13472da/SafetyDetect-UserDetect-Server-Sample/Third Party Open Source Software Notice.docx -------------------------------------------------------------------------------- /SafetyDetect-UserDetect-Server-Sample/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.6.RELEASE 9 | 10 | 11 | com.huawei.safetydetect 12 | userDetect 13 | 0.0.1-SNAPSHOT 14 | userDetect 15 | Demo project for userDetect 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter 25 | 26 | 27 | org.projectlombok 28 | lombok 29 | 1.18.6 30 | provided 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-test 35 | test 36 | 37 | 38 | org.junit.vintage 39 | junit-vintage-engine 40 | 41 | 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-starter-web 46 | 2.1.6.RELEASE 47 | 48 | 49 | com.alibaba 50 | fastjson 51 | 1.2.62 52 | 53 | 54 | org.apache.httpcomponents 55 | httpclient 56 | 4.5.7 57 | 58 | 59 | 60 | 61 | 62 | 63 | org.springframework.boot 64 | spring-boot-maven-plugin 65 | 66 | 67 | org.apache.maven.plugins 68 | maven-compiler-plugin 69 | 70 | 7 71 | 7 72 | 73 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /SafetyDetect-UserDetect-Server-Sample/src/main/java/com/huawei/safetydetect/userdetect/UserDetectApplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. 3 | 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.huawei.safetydetect.userdetect; 18 | 19 | import org.springframework.boot.SpringApplication; 20 | import org.springframework.boot.autoconfigure.SpringBootApplication; 21 | 22 | @SpringBootApplication 23 | public class UserDetectApplication { 24 | public static void main(String[] args) { 25 | SpringApplication.run(UserDetectApplication.class, args); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /SafetyDetect-UserDetect-Server-Sample/src/main/java/com/huawei/safetydetect/userdetect/controller/UserDetectController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. 3 | 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.huawei.safetydetect.userdetect.controller; 17 | 18 | import com.huawei.safetydetect.userdetect.service.UserDetectService; 19 | 20 | import org.springframework.beans.factory.annotation.Autowired; 21 | import org.springframework.stereotype.Controller; 22 | import org.springframework.web.bind.annotation.RequestBody; 23 | import org.springframework.web.bind.annotation.RequestMapping; 24 | import org.springframework.web.bind.annotation.RequestMethod; 25 | import org.springframework.web.bind.annotation.ResponseBody; 26 | 27 | @Controller 28 | public class UserDetectController { 29 | private UserDetectService userDetectService; 30 | 31 | @Autowired 32 | public UserDetectController(UserDetectService userDetectService) { 33 | this.userDetectService = userDetectService; 34 | } 35 | 36 | @RequestMapping(value = "/userdetect/verify", method = {RequestMethod.POST}) 37 | @ResponseBody 38 | public String verify(@RequestBody String responseToken) { 39 | return userDetectService.verify(responseToken); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /SafetyDetect-UserDetect-Server-Sample/src/main/java/com/huawei/safetydetect/userdetect/service/UserDetectService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. 3 | 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.huawei.safetydetect.userdetect.service; 18 | 19 | public interface UserDetectService { 20 | String verify(String responseToken); 21 | } 22 | -------------------------------------------------------------------------------- /SafetyDetect-UserDetect-Server-Sample/src/main/java/com/huawei/safetydetect/userdetect/service/impl/UserDetectServiceImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. 3 | 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.huawei.safetydetect.userdetect.service.impl; 18 | 19 | import com.huawei.safetydetect.userdetect.service.UserDetectService; 20 | 21 | import com.alibaba.fastjson.JSON; 22 | import com.alibaba.fastjson.JSONObject; 23 | 24 | import org.apache.http.HttpEntity; 25 | import org.apache.http.HttpResponse; 26 | import org.apache.http.NameValuePair; 27 | import org.apache.http.client.HttpClient; 28 | import org.apache.http.client.entity.UrlEncodedFormEntity; 29 | import org.apache.http.client.methods.HttpPost; 30 | import org.apache.http.client.utils.URIBuilder; 31 | import org.apache.http.conn.ssl.NoopHostnameVerifier; 32 | import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 33 | import org.apache.http.entity.StringEntity; 34 | import org.apache.http.impl.client.HttpClients; 35 | import org.apache.http.message.BasicNameValuePair; 36 | import org.apache.http.ssl.SSLContexts; 37 | import org.apache.http.ssl.TrustStrategy; 38 | import org.apache.http.util.EntityUtils; 39 | import org.slf4j.Logger; 40 | import org.slf4j.LoggerFactory; 41 | import org.springframework.stereotype.Service; 42 | 43 | import java.io.IOException; 44 | import java.io.UnsupportedEncodingException; 45 | import java.net.URI; 46 | import java.net.URISyntaxException; 47 | import java.nio.charset.StandardCharsets; 48 | import java.security.KeyManagementException; 49 | import java.security.KeyStoreException; 50 | import java.security.NoSuchAlgorithmException; 51 | import java.security.cert.X509Certificate; 52 | import java.util.ArrayList; 53 | import java.util.List; 54 | 55 | import javax.net.ssl.SSLContext; 56 | 57 | @Service 58 | public class UserDetectServiceImpl implements UserDetectService { 59 | private static final Logger LOGGER = LoggerFactory.getLogger(UserDetectServiceImpl.class); 60 | 61 | private static final int SUCCESS_CODE = 200; 62 | 63 | private static final String OAUTH2_URL = "https://oauth-login.cloud.huawei.com/oauth2/v2/token"; 64 | //TODO(developer):replace the APP_ID id with your own app id 65 | private static final String APP_ID = "XXXXXXXX"; 66 | //TODO(developer):replace the SECRET_KEY id with your own secret key 67 | private static final String SECRET_KEY = "XXXXXXXX"; 68 | //TODO(developer):replace the VERIFY_URL id with rms website depends on area 69 | private static final String VERIFY_URL = "https://hirms.cloud.huawei.com/rms/v1/userRisks/verify"; 70 | 71 | @Override 72 | public String verify(String responseToken) { 73 | // apply access token from OAUTH2 74 | String accessToken = applyAccessToken(OAUTH2_URL, APP_ID, SECRET_KEY); 75 | // get user detect result 76 | return verifyUserRisks(VERIFY_URL, APP_ID, accessToken, responseToken); 77 | } 78 | 79 | /** 80 | * apply access token 81 | * 82 | * @param baseUrl the address of OAUTH2 83 | * @param appId app id 84 | * @param secretKey Secret Key 85 | */ 86 | private static String applyAccessToken(String baseUrl, String appId, String secretKey) { 87 | HttpPost httpPostRequest = new HttpPost(baseUrl); 88 | httpPostRequest.setHeader("content-type", "application/x-www-form-urlencoded"); 89 | 90 | List entityData = new ArrayList<>(); 91 | entityData.add(new BasicNameValuePair("grant_type", "client_credentials")); 92 | entityData.add(new BasicNameValuePair("client_id", appId)); 93 | entityData.add(new BasicNameValuePair("client_secret", secretKey)); 94 | UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(entityData, StandardCharsets.UTF_8); 95 | httpPostRequest.setEntity(urlEncodedFormEntity); 96 | 97 | String response = execute(httpPostRequest); 98 | return JSON.parseObject(response).get("access_token").toString(); 99 | } 100 | 101 | private static String execute(HttpPost httpPostRequest) { 102 | SSLContext sslcontext = null; 103 | try { 104 | sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { 105 | @Override 106 | public boolean isTrusted(X509Certificate[] chain, String authType) { 107 | return true; 108 | } 109 | }).build(); 110 | } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { 111 | LOGGER.error("fail to build sslcontext, msg:{}, class:{}", e.getMessage(), e.getClass().getSimpleName()); 112 | } 113 | SSLConnectionSocketFactory sslConnectionSocketFactory = 114 | new SSLConnectionSocketFactory(sslcontext, null, null, new NoopHostnameVerifier()); 115 | 116 | HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build(); 117 | HttpResponse httpResponse; 118 | try { 119 | httpResponse = httpClient.execute(httpPostRequest); 120 | } catch (IOException e) { 121 | LOGGER.error("fail to create HttpResponse, msg:{}, class:{}", e.getMessage(), e.getClass().getSimpleName()); 122 | return ""; 123 | } 124 | 125 | String responseContent = ""; 126 | if (httpResponse.getStatusLine().getStatusCode() == SUCCESS_CODE) { 127 | HttpEntity httpEntity = httpResponse.getEntity(); 128 | if (httpEntity != null) { 129 | try { 130 | responseContent = EntityUtils.toString(httpEntity, "UTF-8"); 131 | } catch (IOException e) { 132 | LOGGER.error("fail to get the entity content as a String, msg:{}, class:{}", e.getMessage(), 133 | e.getClass().getSimpleName()); 134 | } 135 | try { 136 | EntityUtils.consume(httpEntity); 137 | } catch (IOException e) { 138 | LOGGER.error("fail to consume HttpEntity, msg:{}, class:{}", e.getMessage(), 139 | e.getClass().getSimpleName()); 140 | } 141 | } 142 | } 143 | return responseContent; 144 | } 145 | 146 | /** 147 | * get user detect result 148 | * 149 | * @param appId app id 150 | * @param accessToken the access token which apply from OAUTH2 151 | * @param responseToken the response token that returned by userDetection function 152 | */ 153 | private String verifyUserRisks(String verifyUrl, String appId, String accessToken, String responseToken) { 154 | URIBuilder uriBuilder; 155 | URI uri; 156 | try { 157 | uriBuilder = new URIBuilder(verifyUrl); 158 | uriBuilder.addParameter("appId", appId); 159 | uri = uriBuilder.build(); 160 | } catch (URISyntaxException e) { 161 | LOGGER.error("fail to create URI, msg:{}, class:{}", e.getMessage(), e.getClass().getSimpleName()); 162 | return ""; 163 | } 164 | 165 | HttpPost httpPostRequest; 166 | httpPostRequest = new HttpPost(uri); 167 | httpPostRequest.addHeader("content-type", "application/json"); 168 | JSONObject jsonObject = new JSONObject(); 169 | jsonObject.put("accessToken", accessToken); 170 | jsonObject.put("response", JSONObject.parseObject(responseToken).get("response")); 171 | StringEntity entityData; 172 | try { 173 | entityData = new StringEntity(jsonObject.toString()); 174 | } catch (UnsupportedEncodingException e) { 175 | LOGGER.error("fail to new StringEntity, msg:{}, class:{}", e.getMessage(), e.getClass().getSimpleName()); 176 | return ""; 177 | } 178 | httpPostRequest.setEntity(entityData); 179 | 180 | return execute(httpPostRequest); 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /SafetyDetect-UserDetect-Server-Sample/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8084 2 | -------------------------------------------------------------------------------- /SafetyDetect-UserDetect-Server-Sample/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | ${LOG_HOME}/logs/run.log 14 | 15 | %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n 16 | 17 | 18 | ${LOG_HOME}/logs/run/recapcha_%d{yyyyMMdd}_%i.log 19 | 5 20 | 21 | 50mb 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | --------------------------------------------------------------------------------