├── .classpath ├── .github └── workflows │ └── docker.yml ├── .gitignore ├── .project ├── .settings ├── org.eclipse.buildship.core.prefs └── org.eclipse.jdt.core.prefs ├── Changelog.md ├── LICENSE ├── README.md ├── bin └── .gitignore ├── build.gradle ├── docker └── build │ ├── Dockerfile │ └── build.sh ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── release_note.txt ├── sider.yml ├── src └── main │ ├── java │ └── com │ │ └── webank │ │ └── webase │ │ └── sign │ │ ├── Application.java │ │ ├── api │ │ ├── controller │ │ │ ├── SignController.java │ │ │ ├── UserController.java │ │ │ └── VersionController.java │ │ ├── dao │ │ │ └── UserDao.java │ │ └── service │ │ │ ├── KeyStoreService.java │ │ │ ├── SignService.java │ │ │ └── UserService.java │ │ ├── aspect │ │ └── LogAspect.java │ │ ├── config │ │ ├── BeanConfig.java │ │ ├── SwaggerConfig.java │ │ ├── TableInitConfig.java │ │ └── TomcatConfig.java │ │ ├── constant │ │ ├── ConstantProperties.java │ │ └── VersionProperties.java │ │ ├── enums │ │ ├── CodeMessageEnums.java │ │ ├── EncryptTypes.java │ │ └── KeyStatus.java │ │ ├── exception │ │ ├── BaseException.java │ │ ├── ExceptionsHandler.java │ │ └── ParamException.java │ │ ├── manager │ │ └── LoggerManager.java │ │ ├── pojo │ │ ├── bo │ │ │ ├── BaseQueryParam.java │ │ │ ├── KeyStoreInfo.java │ │ │ └── UserParam.java │ │ ├── po │ │ │ └── UserInfoPo.java │ │ └── vo │ │ │ ├── BasePageRspVo.java │ │ │ ├── BaseRspVo.java │ │ │ ├── ReqEncodeInfoVo.java │ │ │ ├── ReqNewUserVo.java │ │ │ ├── ReqSignMessageHashVo.java │ │ │ ├── ReqUserInfoVo.java │ │ │ ├── RspSignVo.java │ │ │ └── RspUserInfoVo.java │ │ ├── task │ │ └── SynUsrTask.java │ │ └── util │ │ ├── AesUtils.java │ │ ├── CommonUtils.java │ │ └── JsonUtils.java │ └── resources │ ├── application-docker.yml │ ├── application.yml │ ├── log4j2.xml │ ├── mapper │ └── UserDao.xml │ └── swagger │ ├── favicon-16x16.png │ ├── favicon-32x32.png │ ├── index.html │ ├── swagger-ui-bundle.js │ ├── swagger-ui-bundle.js.map │ ├── swagger-ui-standalone-preset.js │ ├── swagger-ui-standalone-preset.js.map │ ├── swagger-ui.css │ ├── swagger-ui.css.map │ ├── swagger-ui.js │ └── swagger-ui.js.map ├── start.sh ├── status.sh └── stop.sh /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | -------------------------------------------------------------------------------- /.github/workflows/docker.yml: -------------------------------------------------------------------------------- 1 | name: Docker Build And Push To Docker Hub 2 | 3 | on: 4 | # schedule: 5 | # - cron: '0 10 * * *' # everyday at 10am 6 | push: 7 | tags: 8 | - 'v*.*.*' 9 | # pull_request: 10 | 11 | env: 12 | DOCKER_REPOSITORY: webase-sign 13 | 14 | 15 | jobs: 16 | main: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Checkout 20 | uses: actions/checkout@v2 21 | - uses: actions/setup-java@v1 22 | with: 23 | java-version: 8 24 | - uses: eskatos/gradle-command-action@v1 25 | with: 26 | arguments: clean build -x test 27 | 28 | - name: Get branch name 29 | uses: nelonoel/branch-name@v1.0.1 30 | 31 | - name: Fetch tag 32 | run: | 33 | git fetch --tags --force 34 | 35 | - name: Get git tag 36 | uses: little-core-labs/get-git-tag@v3.0.1 37 | id: tag_data 38 | with: 39 | tagRegex: (.*) # Optional. Returns specified group text as tag name. Full tag string is returned if regex is not defined. 40 | tagRegexGroup: 1 # Optional. Default is 1. 41 | 42 | - name: Set docker tag from tag 43 | id: set_docker_tag 44 | run: | 45 | [[ ${{github.ref}} == */tags/* ]] && DOCKER_TAG="${GIT_TAG_NAME}" || DOCKER_TAG="${BRANCH_NAME}" 46 | DOCKER_TAG="${{ secrets.DOCKER_WEBASEPRO_ORG }}/${DOCKER_REPOSITORY}:${DOCKER_TAG}" 47 | 48 | 49 | echo "New docker tag is ${DOCKER_TAG}" 50 | echo "::set-output name=docker_tag::$(echo ${DOCKER_TAG})" 51 | 52 | - name: Set up QEMU 53 | uses: docker/setup-qemu-action@v1 54 | 55 | - name: Set up Docker Buildx 56 | uses: docker/setup-buildx-action@v1 57 | 58 | - name: Login to DockerHub 59 | uses: docker/login-action@v1 60 | with: 61 | username: ${{ secrets.DOCKER_WEBASEPRO_USERNAME }} 62 | password: ${{ secrets.DOCKER_WEBASEPRO_TOKEN }} 63 | 64 | # - name: Copy nginx config file 65 | # id: copy-nginx-file 66 | # run: | 67 | # cp ./docker/weoracle-web.conf dist/ 68 | 69 | - name: Build and push 70 | id: docker_build 71 | uses: docker/build-push-action@v2 72 | with: 73 | context: ./dist 74 | push: true 75 | file: ./docker/build/Dockerfile 76 | platforms: linux/amd64 77 | tags: ${{ steps.set_docker_tag.outputs.docker_tag }} 78 | 79 | - name: Image digest 80 | run: echo ${{ steps.docker_build.outputs.digest }} 81 | 82 | # 83 | # - name: send custom message with args 84 | # uses: appleboy/telegram-action@master 85 | # with: 86 | # to: ${{ secrets.TELEGRAM_TO }} 87 | # token: ${{ secrets.TELEGRAM_TOKEN }} 88 | # args: ${{ steps.set_docker_tag.outputs.docker_tag }} of ${{github.repository }} build success. 89 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Java template 3 | *.class 4 | 5 | 6 | # Package Files # 7 | *.war 8 | *.ear 9 | 10 | ### Gradle template 11 | .gradle 12 | /build 13 | gradle.properties 14 | 15 | 16 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 17 | !gradle-wrapper.jar 18 | 19 | # Cache of project 20 | .gradletasknamecache 21 | 22 | # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 23 | # gradle/wrapper/gradle-wrapper.properties 24 | 25 | .idea 26 | *.iml 27 | .settings 28 | 29 | # OS X 30 | .DS_Store 31 | 32 | /target 33 | /out 34 | /log 35 | /dist 36 | 37 | application-test.yml 38 | 39 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | WeBASE-Sign 4 | 5 | 6 | 7 | org.eclipse.jdt.core.javanature 8 | org.eclipse.buildship.core.gradleprojectnature 9 | 10 | 11 | 12 | org.eclipse.jdt.core.javabuilder 13 | 14 | 15 | 16 | org.eclipse.buildship.core.gradleprojectbuilder 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /.settings/org.eclipse.buildship.core.prefs: -------------------------------------------------------------------------------- 1 | #Tue Jul 09 14:12:44 CST 2019 2 | connection.project.dir= 3 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | # 2 | #Tue Jul 09 14:13:09 CST 2019 3 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 4 | org.eclipse.jdt.core.compiler.compliance=1.8 5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 6 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 7 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 8 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 9 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 10 | eclipse.preferences.version=1 11 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 12 | org.eclipse.jdt.core.compiler.source=1.8 13 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 14 | -------------------------------------------------------------------------------- /Changelog.md: -------------------------------------------------------------------------------- 1 | ### v1.5.5(2023-04-17) 2 | 3 | **Fix** 4 | - 升级依赖包 5 | 6 | **兼容性** 7 | - WeBASE-Front v1.5.0+ 8 | - WeBASE-Transaction v1.3.0+ 9 | 10 | 详细了解,请阅读[**技术文档**](https://webasedoc.readthedocs.io/zh_CN/latest/)。 11 | 12 | 13 | ### v1.5.3(2021-09-27) 14 | 15 | **Add** 16 | - 新增私钥托管与签名服务Docker镜像,`webasepro/webase-sign:v1.5.3` 17 | 18 | **兼容性** 19 | - WeBASE-Front v1.5.0+ 20 | - WeBASE-Transaction v1.3.0+ 21 | 22 | 详细了解,请阅读[**技术文档**](https://webasedoc.readthedocs.io/zh_CN/latest/)。 23 | 24 | ### v1.5.0(2021-03-31) 25 | 26 | **Add** 27 | - 增加配置项`supportPrivateKeyTransfer: true`,接口支持私钥传输(aes加密后的私钥),配置项为`false`时不支持 28 | 29 | **Fix** 30 | - jar包升级:mysql-connector-java:8.0.22、bcprov-jdk15on:1.67 31 | - 修复ECDSA签名结果序列化bug 32 | 33 | **兼容性** 34 | - WeBASE-Front v1.5.0+ 35 | - WeBASE-Transaction v1.3.0+ 36 | 37 | 详细了解,请阅读[**技术文档**](https://webasedoc.readthedocs.io/zh_CN/latest/)。 38 | 39 | ### v1.4.3(2021-01-27) 40 | 41 | **Add** 42 | - 增加数据签名接口 43 | 44 | **Fix** 45 | - 数据库密码支持特殊字符 46 | 47 | **兼容性** 48 | - WeBASE-Front v1.4.0+ 49 | - WeBASE-Transaction v1.3.0+ 50 | 51 | 详细了解,请阅读[**技术文档**](https://webasedoc.readthedocs.io/zh_CN/latest/)。 52 | 53 | 54 | ### v1.4.2(2020-11-19) 55 | 56 | **Add** 57 | - 适配FISCO BCOS java-sdk 58 | 59 | **兼容性** 60 | - WeBASE-Front v1.4.0+ 61 | - WeBASE-Transaction v1.3.0+ 62 | 63 | 详细了解,请阅读[**技术文档**](https://webasedoc.readthedocs.io/zh_CN/latest/)。 64 | 65 | ### v1.4.1(2020-09-29) 66 | 67 | 68 | **Fix** 69 | - 更新gradlew版本 70 | - 修复用户KeyStatus状态判断问题 71 | - 修复用户分页的用户总数问题 72 | 73 | 74 | **兼容性** 75 | - WeBASE-Front v1.4.0+ 76 | - WeBASE-Transaction v1.3.0+ 77 | 78 | 详细了解,请阅读[**技术文档**](https://webasedoc.readthedocs.io/zh_CN/latest/)。 79 | 80 | 81 | ### v1.4.0(2020-08-06) 82 | 83 | **Add** 84 | - 增加返回 Version 版本接口; 85 | 86 | **Fix** 87 | - 默认Aes加密模式由ECB改为更安全的CBC,同时支持在配置选择CBC与ECB 88 | 89 | 90 | **兼容性** 91 | - WeBASE-Front v1.4.0+ 92 | - WeBASE-Transaction v1.3.0+ 93 | 94 | 详细了解,请阅读[**技术文档**](https://webasedoc.readthedocs.io/zh_CN/latest/)。 95 | 96 | 97 | 98 | ### v1.3.2(2020-06-17) 99 | 100 | **Fix** 101 | - 移除Fastjson,替换为Jackson 2.11.0; web3sdk升级为2.4.1 102 | - 升级依赖包:spring: 4.3.27; log4j: 2.13.3; slf4j: 1.7.30; netty-all: 4.1.44+; guava: 29.0; 103 | 104 | **兼容性** 105 | - WeBASE-Front v1.3.0+ 106 | - WeBASE-Transaction v1.3.0+ 107 | 108 | 详细了解,请阅读[**技术文档**](https://webasedoc.readthedocs.io/zh_CN/latest/)。 109 | 110 | 111 | ### v1.3.1 112 | 113 | (2020-06-01) 114 | 115 | **Add** 116 | - 新增导入私钥接口 117 | 118 | **Fix** 119 | - 增加私钥签名Credential缓存机制,优化签名性能 120 | 121 | **兼容性** 122 | - WeBASE-Front v1.3.0+ 123 | - WeBASE-Transaction v1.3.0+ 124 | 125 | 详细了解,请阅读[**技术文档**](https://webasedoc.readthedocs.io/zh_CN/latest/)。 126 | 127 | 128 | ### v1.3.0 129 | 130 | (2020-04-29) 131 | 132 | **Add** 133 | - 同时支持ECDSA与国密私钥与签名与私钥创建(移除yaml配置文件中的`encryptType`),可通过`encryptType`字段指定 134 | - 修改用户entity的`int userId`为`String signUserId`,新增`String appId` 135 | - 调用`/user/newUser`创建私钥时,需要传入`signUserId&appId`作为业务流水号;所有私钥与签名接口通过`signUserId`进行调用 136 | - 新增停用私钥用户接口`DELETE /user/{signUseriId}` 137 | - 新增根据appId获取用户分页列表接口`/user/list/{appId}/{pageNumber}/{pageSize}` 138 | 139 | **Fix** 140 | - 优化签名服务的性能 141 | - 升级fastjson, jackson, log4j 142 | 143 | **兼容性** 144 | - WeBASE-Front v1.3.0+ 145 | - WeBASE-Transaction v1.3.0+ 146 | 147 | 详细了解,请阅读[**技术文档**](https://webasedoc.readthedocs.io/zh_CN/latest/)。 148 | 149 | ### v1.2.2 150 | 151 | (2020-01-02) 152 | 153 | **Add** 154 | 155 | - 支持国密 156 | - 新增`/encrypt`接口判断是否国密 157 | 158 | **Fix** 159 | 160 | - bugfix:CommonUtils的`SignatureData`序列化支持国密 161 | - bugifx: 修复start.sh启动时间过长的问题 162 | - 优化:web3sdk升级至v2.2.0 163 | 164 | **兼容性** 165 | 166 | - WeBASE-Front v1.2.2 167 | - WeBASE-Transaction v1.2.2 168 | 169 | 详细了解,请阅读[**技术文档**](https://webasedoc.readthedocs.io/zh_CN/latest/)。 170 | 171 | 172 | ### v1.1.0 173 | 174 | (2019-09-12) 175 | 176 | **Add** 177 | 178 | - 查询用户列表 179 | 180 | **Fix** 181 | 182 | - bugfix:签名用户地址不一致 183 | - 优化:通过用户编号查询公私钥信息 184 | - 优化:启停脚本通过程序名和端口校验进程 185 | 186 | **兼容性** 187 | 188 | - WeBASE-Front v1.1.0 189 | - WeBASE-Transaction v1.1.0 190 | 191 | 详细了解,请阅读[**技术文档**](https://webasedoc.readthedocs.io/zh_CN/latest/)。 192 | 193 | 194 | 195 | ### v1.0.0 196 | 197 | (2019-06-27) 198 | 199 | WeBASE-Sign(微众区块链中间件平台-签名子系统),主要提供公私钥管理及数据签名功能。 200 | 201 | **Add** 202 | 203 | - 适配FISCO-BCOS 2.0.0版本 204 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 签名服务 2 | [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://webasedoc.readthedocs.io/zh_CN/latest/docs/WeBASE/CONTRIBUTING.html) 3 | [![CodeFactor](https://www.codefactor.io/repository/github/webankblockchain/webase-sign/badge)](https://www.codefactor.io/repository/github/webankblockchain/webase-sign) 4 | [![Code Lines](https://tokei.rs/b1/github/WeBankBlockchain/WeBASE-Sign?category=code)](https://github.com/WeBankBlockchain/WeBASE-Sign) 5 | [![license](http://img.shields.io/badge/license-Apache%20v2-blue.svg)](http://www.apache.org/licenses/) 6 | [![GitHub (pre-)release](https://img.shields.io/github/release/WeBankBlockchain/WeBASE-Sign/all.svg)](https://github.com/WeBankBlockchain/WeBASE-Sign/releases) 7 | 8 | ## 简介 9 | 本工程为签名服务子系统。功能:管理公私钥、对数据进行签名。 详细介绍请查看[WeBASE-Sign在线文档](https://webasedoc.readthedocs.io/zh_CN/latest/docs/WeBASE-Sign/index.html) 10 | 11 | ## 贡献说明 12 | 请阅读我们的贡献文档,了解如何贡献代码,并提交你的贡献。 13 | 14 | 希望在您的参与下,WeBASE会越来越好! 15 | 16 | ## 社区 17 | 联系我们:webase@webank.com 18 | -------------------------------------------------------------------------------- /bin/.gitignore: -------------------------------------------------------------------------------- 1 | /main/ 2 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | version '1.0' 2 | 3 | println "======Gradle version:" + gradle.gradleVersion 4 | if (gradle.gradleVersion.startsWith("7")) { 5 | println "Gradle 7.x not support yet!\n ====== please use Gradle version from 4.6.x to 6.9.x " 6 | } else if (gradle.gradleVersion.startsWith("6") 7 | || gradle.gradleVersion.startsWith("5") 8 | || gradle.gradleVersion.startsWith("4.10") 9 | || gradle.gradleVersion.startsWith("4.9") 10 | || gradle.gradleVersion.startsWith("4.8") 11 | || gradle.gradleVersion.startsWith("4.7") 12 | ) { 13 | println "Gradle with version >= 4.6 detected" 14 | } else { 15 | println "Gradle with version < 4.6 detected" 16 | } 17 | 18 | 19 | apply plugin: 'maven' 20 | apply plugin: 'java' 21 | apply plugin: 'idea' 22 | apply plugin: 'eclipse' 23 | 24 | sourceCompatibility = 1.8 25 | targetCompatibility = 1.8 26 | 27 | [compileJava, compileTestJava, javadoc]*.options*.encoding = 'UTF-8' 28 | 29 | // In this section you declare where to find the dependencies of your project 30 | repositories { 31 | maven { url "http://maven.aliyun.com/nexus/content/groups/public/"} 32 | maven { url "https://oss.sonatype.org/content/repositories/snapshots" } 33 | 34 | maven { url 'https://dl.bintray.com/ethereum/maven/'} 35 | mavenLocal() 36 | mavenCentral() 37 | } 38 | 39 | def spring_boot_version="2.7.10" 40 | List springboot =[ 41 | "org.springframework.boot:spring-boot-starter-web:$spring_boot_version", 42 | "org.springframework.boot:spring-boot-autoconfigure:$spring_boot_version", 43 | "org.springframework.boot:spring-boot-configuration-processor:$spring_boot_version", 44 | "org.springframework.boot:spring-boot-starter-aop:$spring_boot_version", 45 | "org.springframework.boot:spring-boot-starter-cache:$spring_boot_version", 46 | "org.springframework.boot:spring-boot-starter-validation:$spring_boot_version" 47 | ] 48 | 49 | List swagger = [ 50 | 'io.springfox:springfox-swagger2:2.8.0', 51 | 'io.springfox:springfox-swagger-ui:2.8.0' 52 | ] 53 | 54 | List mysql = [ 55 | 'mysql:mysql-connector-java:8.0.22', 56 | 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.2' 57 | ] 58 | 59 | def log4j_version="2.18.0" 60 | List log4j = [ 61 | "org.apache.logging.log4j:log4j-api:$log4j_version", 62 | "org.apache.logging.log4j:log4j-core:$log4j_version", 63 | "org.apache.logging.log4j:log4j-slf4j-impl:$log4j_version", 64 | "org.apache.logging.log4j:log4j-web:$log4j_version" 65 | ] 66 | 67 | List jaxb = [ 68 | "javax.xml.bind:jaxb-api:2.3.0", 69 | "com.sun.xml.bind:jaxb-impl:2.3.0", 70 | "com.sun.xml.bind:jaxb-core:2.3.0", 71 | "javax.activation:activation:1.1.1" 72 | ] 73 | 74 | def jackson_version = "2.14.2" 75 | List jackson = [ 76 | "com.fasterxml.jackson.core:jackson-databind:$jackson_version", 77 | "com.fasterxml.jackson.core:jackson-annotations:$jackson_version", 78 | "com.fasterxml.jackson.core:jackson-core:$jackson_version", 79 | "com.fasterxml.jackson.module:jackson-module-parameter-names:$jackson_version", 80 | "com.fasterxml.jackson.datatype:jackson-datatype-jdk8:$jackson_version", 81 | "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version", 82 | ] 83 | 84 | dependencies { 85 | compile springboot,swagger,mysql,log4j,jaxb,jackson 86 | compile ('org.fisco-bcos.java-sdk:fisco-bcos-java-sdk:2.9.2') { 87 | // 不需要连接节点,因此去除 88 | exclude group: "org.fisco-bcos", module: 'netty-sm-ssl-context' 89 | } 90 | compile 'org.slf4j:jcl-over-slf4j:1.7.30' 91 | compile 'org.apache.commons:commons-lang3:3.6' 92 | compile "org.bouncycastle:bcprov-jdk15on:1.69" 93 | compile 'org.yaml:snakeyaml:2.0' 94 | 95 | compile 'org.projectlombok:lombok:1.18.6' 96 | annotationProcessor 'org.projectlombok:lombok:1.18.6' 97 | } 98 | 99 | configurations { 100 | all*.exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging' 101 | all*.exclude group: 'org.slf4j', module: 'slf4j-log4j12' 102 | all*.exclude group: 'log4j', module: 'log4j' 103 | all*.exclude group: 'com.mchange', module: '*' 104 | } 105 | 106 | sourceSets { 107 | main { 108 | java { 109 | srcDir 'src/main/java' 110 | } 111 | resources { 112 | srcDir 'src/main/resources' 113 | } 114 | } 115 | } 116 | 117 | clean { 118 | delete 'dist' 119 | delete 'build' 120 | delete 'log' 121 | } 122 | 123 | jar { 124 | destinationDir file('dist/apps') 125 | archiveName project.name + '.jar' 126 | exclude '**/*.xml' 127 | exclude '**/*.properties' 128 | 129 | doLast { 130 | copy { 131 | from file('src/main/resources/') 132 | into 'dist/conf_template' 133 | } 134 | copy { 135 | from configurations.runtime 136 | into 'dist/lib' 137 | } 138 | copy { 139 | from file('.').listFiles().findAll{File f -> (f.name.endsWith('.sh') || f.name.endsWith('.env'))} 140 | into 'dist' 141 | } 142 | copy { 143 | from file('release_note.txt') 144 | into 'dist' 145 | } 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /docker/build/Dockerfile: -------------------------------------------------------------------------------- 1 | #FROM openjdk:8-jdk-alpine as prod 2 | FROM ubuntu:18.04 as prod 3 | 4 | #RUN apk --no-cache add bash curl wget 5 | RUN apt-get update \ 6 | && apt-get -y install openjdk-8-jre \ 7 | && apt-get -y install mysql-client \ 8 | && rm -rf /var/lib/apt/lists/* 9 | 10 | COPY lib /dist/lib 11 | COPY conf_template /dist/conf 12 | COPY apps /dist/apps 13 | 14 | WORKDIR /dist 15 | EXPOSE 5004 16 | 17 | ENV CLASSPATH "/dist/conf/:/dist/apps/*:/dist/lib/*" 18 | 19 | ENV JAVA_OPTS " -server -Dfile.encoding=UTF-8 -Xmx512m -Xms512m -Xmn256m -Xss512k -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/log/heap_error.log -XX:+UseG1GC -XX:MaxGCPauseMillis=200 " 20 | ENV APP_MAIN "com.webank.webase.sign.Application" 21 | 22 | # start commond 23 | ENTRYPOINT java ${JAVA_OPTS} -Djdk.tls.namedGroups="secp256k1", -Duser.timezone="Asia/Shanghai" -Djava.security.egd=file:/dev/./urandom, -Djava.library.path=/dist/conf -cp ${CLASSPATH} ${APP_MAIN} 24 | -------------------------------------------------------------------------------- /docker/build/build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | LOG_WARN() { 4 | local content=${1} 5 | echo -e "\033[31m[WARN] ${content}\033[0m" 6 | } 7 | 8 | LOG_INFO() { 9 | local content=${1} 10 | echo -e "\033[32m[INFO] ${content}\033[0m" 11 | } 12 | 13 | # 命令返回非 0 时,就退出 14 | set -o errexit 15 | # 管道命令中任何一个失败,就退出 16 | set -o pipefail 17 | # 遇到不存在的变量就会报错,并停止执行 18 | set -o nounset 19 | # 在执行每一个命令之前把经过变量展开之后的命令打印出来,调试时很有用 20 | #set -o xtrace 21 | 22 | # 退出时,执行的命令,做一些收尾工作 23 | trap 'echo -e "Aborted, error $? in command: $BASH_COMMAND"; trap ERR; exit 1' ERR 24 | 25 | # Set magic variables for current file & dir 26 | # 脚本所在的目录 27 | __dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" 28 | # 脚本的全路径,包含脚本文件名 29 | __file="${__dir}/$(basename "${BASH_SOURCE[0]}")" 30 | # 脚本的名称,不包含扩展名 31 | __base="$(basename ${__file} .sh)" 32 | # 脚本所在的目录的父目录,一般脚本都会在父项目中的子目录, 33 | # 比如: bin, script 等,需要根据场景修改 34 | __root="$(cd "$(dirname "${__dir}")" && pwd)"/../ # <-- change this as it depends on your app 35 | __root=$(realpath -s "${__root}") 36 | 37 | 38 | ########################### properties config ########################## 39 | image_organization=webasepro 40 | image_name="webase-sign" 41 | docker_push="no" 42 | latest_tag=latest 43 | new_tag= 44 | 45 | 46 | ########################### parse param ########################## 47 | __cmd="$(basename $0)" 48 | # 解析参数 49 | # usage help doc. 50 | usage() { 51 | cat << USAGE >&2 52 | Usage: 53 | ${__cmd} [-h] [-t new_tag] [-p] [-i fiscoorg] 54 | -t New tag for image, required. 55 | 56 | -p Push image to docker hub, default no. 57 | -i Default organization, default webasepro. 58 | -h Show help info. 59 | USAGE 60 | exit 1 61 | } 62 | while getopts t:i:ph OPT;do 63 | case $OPT in 64 | t) 65 | new_tag=$OPTARG 66 | ;; 67 | p) 68 | docker_push=yes 69 | ;; 70 | i) 71 | image_organization=${OPTARG} 72 | ;; 73 | h) 74 | usage 75 | exit 3 76 | ;; 77 | \?) 78 | usage 79 | exit 4 80 | ;; 81 | esac 82 | done 83 | 84 | 85 | # 必须设置新镜像的版本 86 | if [[ "${new_tag}"x == "x" ]] ; then 87 | LOG_WARN "Need a new_tag for new docker image!! " 88 | usage 89 | exit 1 90 | fi 91 | 92 | ########################### build docker image ########################## 93 | image_repository="${image_organization}/${image_name}" 94 | 95 | ## compile project 96 | cd "${__root}" && chmod +x ./gradlew && ./gradlew clean build -x test 97 | 98 | ## docker build 99 | cd "${__root}"/dist 100 | 101 | docker build -t ${image_repository}:${new_tag} -f "${__root}"/docker/build/Dockerfile . 102 | docker tag "${image_repository}:${new_tag}" "${image_repository}:${latest_tag}" 103 | 104 | 105 | ########################### push docker image ########################## 106 | if [[ "${docker_push}"x == "yesx" ]] ; then 107 | docker push "${image_repository}:${new_tag}" 108 | docker push "${image_repository}:${latest_tag}" 109 | fi 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeBASE-Sign/e98ab0cced21391fc2951e97e19fb84a701a7f98/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /release_note.txt: -------------------------------------------------------------------------------- 1 | v1.5.5 2 | -------------------------------------------------------------------------------- /sider.yml: -------------------------------------------------------------------------------- 1 | linter: 2 | pmd_java: 3 | dir: src 4 | encoding: Shift_JIS 5 | min_priority: 2 6 | checkstyle: 7 | dir: src 8 | ignore: 9 | - warning 10 | - info 11 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/Application.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign; 17 | 18 | import lombok.extern.slf4j.Slf4j; 19 | import org.mybatis.spring.annotation.MapperScan; 20 | import org.springframework.boot.SpringApplication; 21 | import org.springframework.boot.autoconfigure.SpringBootApplication; 22 | import org.springframework.cache.annotation.EnableCaching; 23 | import org.springframework.scheduling.annotation.EnableScheduling; 24 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 25 | 26 | /** 27 | * Startup class. 28 | */ 29 | @Slf4j 30 | @EnableSwagger2 31 | @EnableCaching 32 | @EnableScheduling 33 | @SpringBootApplication 34 | @MapperScan("com.webank.webase.sign") 35 | public class Application { 36 | 37 | public static void main(String[] args) { 38 | SpringApplication.run(Application.class, args); 39 | log.info("main run success..."); 40 | } 41 | } -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/api/controller/SignController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.api.controller; 17 | 18 | import com.webank.webase.sign.api.service.SignService; 19 | import com.webank.webase.sign.api.service.UserService; 20 | import com.webank.webase.sign.exception.BaseException; 21 | import com.webank.webase.sign.pojo.vo.BaseRspVo; 22 | import com.webank.webase.sign.pojo.vo.ReqEncodeInfoVo; 23 | import com.webank.webase.sign.pojo.vo.ReqSignMessageHashVo; 24 | import com.webank.webase.sign.pojo.vo.RspSignVo; 25 | import com.webank.webase.sign.util.CommonUtils; 26 | import io.swagger.annotations.Api; 27 | import io.swagger.annotations.ApiImplicitParam; 28 | import io.swagger.annotations.ApiOperation; 29 | import org.springframework.beans.factory.annotation.Autowired; 30 | import org.springframework.validation.BindingResult; 31 | import org.springframework.web.bind.annotation.PostMapping; 32 | import org.springframework.web.bind.annotation.RequestBody; 33 | import org.springframework.web.bind.annotation.RequestMapping; 34 | import org.springframework.web.bind.annotation.RestController; 35 | 36 | import javax.validation.Valid; 37 | 38 | import static com.webank.webase.sign.enums.CodeMessageEnums.PARAM_SIGN_USER_ID_IS_INVALID; 39 | 40 | 41 | /** 42 | * Controller. 43 | */ 44 | @Api(value = "sign", tags = "sign interface") 45 | @RestController 46 | @RequestMapping("sign") 47 | public class SignController { 48 | 49 | @Autowired 50 | SignService signService; 51 | @Autowired 52 | UserService userService; 53 | 54 | /** 55 | * add sign by ecdsa or guomi encryption 56 | * 57 | * @param req parameter 58 | * @param result checkResult 59 | */ 60 | @ApiOperation(value = "add sign by ecdsa(default) or guomi", 61 | notes = "获取ECDSA或国密SM2签名数据,默认ECDSA") 62 | @ApiImplicitParam(name = "req", value = "encode info", required = true, 63 | dataType = "ReqEncodeInfoVo") 64 | @PostMapping("") 65 | public BaseRspVo signStandard(@Valid @RequestBody ReqEncodeInfoVo req, BindingResult result) 66 | throws BaseException { 67 | CommonUtils.checkParamBindResult(result); 68 | String signUserId = req.getSignUserId(); 69 | if (!CommonUtils.checkLengthWithin_64(signUserId)) { 70 | throw new BaseException(PARAM_SIGN_USER_ID_IS_INVALID); 71 | } 72 | String signResult = signService.sign(req); 73 | // return 74 | RspSignVo rspSignVo = new RspSignVo(); 75 | rspSignVo.setSignDataStr(signResult); 76 | return CommonUtils.buildSuccessRspVo(rspSignVo); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/api/controller/UserController.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.webank.webase.sign.api.controller; 15 | 16 | import static com.webank.webase.sign.enums.CodeMessageEnums.PARAM_APP_ID_IS_BLANK; 17 | import static com.webank.webase.sign.enums.CodeMessageEnums.PARAM_APP_ID_IS_INVALID; 18 | import static com.webank.webase.sign.enums.CodeMessageEnums.PARAM_ENCRYPT_TYPE_IS_INVALID; 19 | import static com.webank.webase.sign.enums.CodeMessageEnums.PARAM_SIGN_USER_ID_IS_BLANK; 20 | import static com.webank.webase.sign.enums.CodeMessageEnums.PARAM_SIGN_USER_ID_IS_INVALID; 21 | import static com.webank.webase.sign.enums.CodeMessageEnums.PRIVATEKEY_NOT_SUPPORT_TRANSFER; 22 | import com.webank.webase.sign.api.service.UserService; 23 | import com.webank.webase.sign.constant.ConstantProperties; 24 | import com.webank.webase.sign.enums.EncryptTypes; 25 | import com.webank.webase.sign.exception.BaseException; 26 | import com.webank.webase.sign.pojo.bo.UserParam; 27 | import com.webank.webase.sign.pojo.po.UserInfoPo; 28 | import com.webank.webase.sign.pojo.vo.BaseRspVo; 29 | import com.webank.webase.sign.pojo.vo.ReqNewUserVo; 30 | import com.webank.webase.sign.pojo.vo.ReqUserInfoVo; 31 | import com.webank.webase.sign.pojo.vo.RspUserInfoVo; 32 | import com.webank.webase.sign.util.AesUtils; 33 | import com.webank.webase.sign.util.CommonUtils; 34 | import io.swagger.annotations.Api; 35 | import io.swagger.annotations.ApiImplicitParam; 36 | import io.swagger.annotations.ApiImplicitParams; 37 | import io.swagger.annotations.ApiOperation; 38 | import java.util.ArrayList; 39 | import java.util.List; 40 | import java.util.Optional; 41 | import javax.validation.Valid; 42 | import lombok.extern.slf4j.Slf4j; 43 | import org.apache.commons.lang3.StringUtils; 44 | import org.springframework.beans.BeanUtils; 45 | import org.springframework.beans.factory.annotation.Autowired; 46 | import org.springframework.validation.BindingResult; 47 | import org.springframework.web.bind.annotation.DeleteMapping; 48 | import org.springframework.web.bind.annotation.GetMapping; 49 | import org.springframework.web.bind.annotation.PathVariable; 50 | import org.springframework.web.bind.annotation.PostMapping; 51 | import org.springframework.web.bind.annotation.RequestBody; 52 | import org.springframework.web.bind.annotation.RequestMapping; 53 | import org.springframework.web.bind.annotation.RequestParam; 54 | import org.springframework.web.bind.annotation.RestController; 55 | 56 | /** 57 | * Controller. 58 | */ 59 | @Slf4j 60 | @Api(value = "user", tags = "user interface") 61 | @RestController 62 | @RequestMapping("user") 63 | public class UserController { 64 | 65 | @Autowired 66 | private UserService userService; 67 | @Autowired 68 | private AesUtils aesUtils; 69 | @Autowired 70 | ConstantProperties properties; 71 | 72 | /** 73 | * new user from ecdsa or guomi 74 | */ 75 | @ApiOperation(value = "new user from ecdsa/guomi, default ecdsa", 76 | notes = "新建公私钥用户(ecdsa或国密),默认ecdas") 77 | @GetMapping("/newUser") 78 | public BaseRspVo newUser(@RequestParam String signUserId, @RequestParam String appId, 79 | @RequestParam(required = false, defaultValue = "0") Integer encryptType, 80 | @RequestParam(required = false, defaultValue = "false") boolean returnPrivateKey) 81 | throws BaseException { 82 | // validate signUserId 83 | if (StringUtils.isBlank(signUserId)) { 84 | throw new BaseException(PARAM_SIGN_USER_ID_IS_BLANK); 85 | } 86 | if (!CommonUtils.isLetterDigit(signUserId) 87 | || !CommonUtils.checkLengthWithin_64(signUserId)) { 88 | throw new BaseException(PARAM_SIGN_USER_ID_IS_INVALID); 89 | } 90 | if (StringUtils.isBlank(appId)) { 91 | throw new BaseException(PARAM_APP_ID_IS_BLANK); 92 | } 93 | if (!CommonUtils.isLetterDigit(appId) || !CommonUtils.checkLengthWithin_64(appId)) { 94 | throw new BaseException(PARAM_APP_ID_IS_INVALID); 95 | } 96 | if (encryptType != EncryptTypes.STANDARD.getValue() 97 | && encryptType != EncryptTypes.GUOMI.getValue()) { 98 | throw new BaseException(PARAM_ENCRYPT_TYPE_IS_INVALID); 99 | } 100 | if (returnPrivateKey == true && !properties.isSupportPrivateKeyTransfer()) { 101 | throw new BaseException(PRIVATEKEY_NOT_SUPPORT_TRANSFER); 102 | } 103 | // new user 104 | RspUserInfoVo userInfo = userService.newUser(signUserId, appId, encryptType, null); 105 | if (returnPrivateKey == false) { 106 | userInfo.setPrivateKey(""); 107 | } 108 | return CommonUtils.buildSuccessRspVo(userInfo); 109 | } 110 | 111 | @ApiOperation(value = "import new user by private key", notes = "导入私钥用户(ecdsa或国密),默认ecdas") 112 | @ApiImplicitParam(name = "reqNewUser", value = "private key info", required = true, 113 | dataType = "ReqNewUserVo") 114 | @PostMapping("/newUser") 115 | public BaseRspVo newUserByImportPrivateKey(@Valid @RequestBody ReqNewUserVo reqNewUser, 116 | BindingResult result) throws BaseException { 117 | CommonUtils.checkParamBindResult(result); 118 | // validate signUserId 119 | String signUserId = reqNewUser.getSignUserId(); 120 | String appId = reqNewUser.getAppId(); 121 | Integer encryptType = reqNewUser.getEncryptType(); 122 | String privateKeyEncoded = reqNewUser.getPrivateKey(); 123 | if (StringUtils.isBlank(signUserId)) { 124 | throw new BaseException(PARAM_SIGN_USER_ID_IS_BLANK); 125 | } 126 | if (!CommonUtils.isLetterDigit(signUserId) 127 | || !CommonUtils.checkLengthWithin_64(signUserId)) { 128 | throw new BaseException(PARAM_SIGN_USER_ID_IS_INVALID); 129 | } 130 | if (StringUtils.isBlank(appId)) { 131 | throw new BaseException(PARAM_APP_ID_IS_BLANK); 132 | } 133 | if (!CommonUtils.isLetterDigit(appId) || !CommonUtils.checkLengthWithin_64(appId)) { 134 | throw new BaseException(PARAM_APP_ID_IS_INVALID); 135 | } 136 | if (encryptType != EncryptTypes.STANDARD.getValue() 137 | && encryptType != EncryptTypes.GUOMI.getValue()) { 138 | throw new BaseException(PARAM_ENCRYPT_TYPE_IS_INVALID); 139 | } 140 | // new user 141 | RspUserInfoVo userInfo = 142 | userService.newUser(signUserId, appId, encryptType, privateKeyEncoded); 143 | userInfo.setPrivateKey(""); 144 | return CommonUtils.buildSuccessRspVo(userInfo); 145 | } 146 | 147 | /** 148 | * get user. 149 | */ 150 | @ApiOperation(value = "check user info exist", notes = "check user info exist") 151 | @ApiImplicitParams({@ApiImplicitParam(name = "signUserId", 152 | value = "business id of user in system", required = true, dataType = "String"),}) 153 | @GetMapping("/{signUserId}/userInfo") 154 | public BaseRspVo getUserInfo(@PathVariable("signUserId") String signUserId, 155 | @RequestParam(required = false, defaultValue = "false") boolean returnPrivateKey) 156 | throws BaseException { 157 | if (!CommonUtils.checkLengthWithin_64(signUserId)) { 158 | throw new BaseException(PARAM_SIGN_USER_ID_IS_INVALID); 159 | } 160 | if (returnPrivateKey == true && !properties.isSupportPrivateKeyTransfer()) { 161 | throw new BaseException(PRIVATEKEY_NOT_SUPPORT_TRANSFER); 162 | } 163 | // find user 164 | UserInfoPo userInfo = userService.findBySignUserId(signUserId); 165 | RspUserInfoVo rspUserInfoVo = new RspUserInfoVo(); 166 | Optional.ofNullable(userInfo).ifPresent(u -> BeanUtils.copyProperties(u, rspUserInfoVo)); 167 | if (returnPrivateKey == false) { 168 | rspUserInfoVo.setPrivateKey(""); 169 | } else { 170 | rspUserInfoVo.setPrivateKey(aesUtils.aesEncrypt(userInfo.getPrivateKey())); 171 | } 172 | return CommonUtils.buildSuccessRspVo(rspUserInfoVo); 173 | } 174 | 175 | /** 176 | * get user list by app id 177 | */ 178 | @ApiOperation(value = "get user list by app id", notes = "根据appId获取user列表") 179 | @ApiImplicitParams({@ApiImplicitParam(name = "appId", value = "app id that users belong to", 180 | required = true, dataType = "String"),}) 181 | @GetMapping("/list/{appId}/{pageNumber}/{pageSize}") 182 | public BaseRspVo getUserListByAppId(@PathVariable("appId") String appId, 183 | @PathVariable("pageNumber") Integer pageNumber, 184 | @PathVariable("pageSize") Integer pageSize, 185 | @RequestParam(required = false, defaultValue = "false") boolean returnPrivateKey) 186 | throws BaseException { 187 | if (!CommonUtils.checkLengthWithin_64(appId)) { 188 | throw new BaseException(PARAM_APP_ID_IS_INVALID); 189 | } 190 | if (returnPrivateKey == true && !properties.isSupportPrivateKeyTransfer()) { 191 | throw new BaseException(PRIVATEKEY_NOT_SUPPORT_TRANSFER); 192 | } 193 | UserParam param = new UserParam(); 194 | param.setAppId(appId); 195 | int count = userService.countOfUser(param); 196 | List userList = new ArrayList<>(); 197 | if (count > 0) { 198 | Integer start = 199 | Optional.ofNullable(pageNumber).map(page -> (page - 1) * pageSize).orElse(null); 200 | param.setStart(start); 201 | param.setPageSize(pageSize); 202 | // find user 203 | userList = userService.findUserListByAppId(param); 204 | if (!userList.isEmpty() && returnPrivateKey == false) { 205 | userList.forEach(user -> user.setPrivateKey("")); 206 | } 207 | } 208 | return CommonUtils.buildSuccessPageRspVo(userList, count); 209 | } 210 | 211 | @ApiOperation(value = "delete user by address", notes = "通过地址删除私钥") 212 | @DeleteMapping("") 213 | public BaseRspVo deleteUser(@RequestBody ReqUserInfoVo req) throws BaseException { 214 | String signUserId = req.getSignUserId(); 215 | if (!CommonUtils.checkLengthWithin_64(signUserId)) { 216 | throw new BaseException(PARAM_SIGN_USER_ID_IS_INVALID); 217 | } 218 | // set as 0: SUSPENDED 219 | userService.deleteBySignUserId(signUserId); 220 | return CommonUtils.buildSuccessRspVo(null); 221 | } 222 | 223 | 224 | @ApiOperation(value = "delete all user cache", notes = "删除所有用户缓存信息") 225 | @DeleteMapping("/all") 226 | public BaseRspVo deleteAllUserCache() { 227 | 228 | userService.deleteAllUserCache(); 229 | return CommonUtils.buildSuccessRspVo(null); 230 | } 231 | 232 | @ApiOperation(value = "delete all Credential cache", notes = "删除所有私钥缓存信息") 233 | @DeleteMapping("/all-credential") 234 | public BaseRspVo deleteCredentialCache() { 235 | 236 | userService.deleteAllCredentialCache(); 237 | return CommonUtils.buildSuccessRspVo(null); 238 | } 239 | 240 | } 241 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/api/controller/VersionController.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | *

7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | *

9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | 15 | package com.webank.webase.sign.api.controller; 16 | 17 | import com.webank.webase.sign.constant.VersionProperties; 18 | import lombok.extern.slf4j.Slf4j; 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | import org.springframework.web.bind.annotation.GetMapping; 21 | import org.springframework.web.bind.annotation.RequestMapping; 22 | import org.springframework.web.bind.annotation.RestController; 23 | 24 | /** 25 | * return version of local server 26 | */ 27 | @Slf4j 28 | @RestController 29 | @RequestMapping("version") 30 | public class VersionController { 31 | 32 | @Autowired 33 | private VersionProperties versionProperties; 34 | 35 | @GetMapping() 36 | public String getServerVersion() { 37 | return versionProperties.getVersion(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/api/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.webank.webase.sign.api.dao; 15 | 16 | 17 | import com.webank.webase.sign.pojo.bo.UserParam; 18 | import com.webank.webase.sign.pojo.po.UserInfoPo; 19 | import org.apache.ibatis.annotations.Param; 20 | import org.springframework.stereotype.Repository; 21 | 22 | import java.time.LocalDateTime; 23 | import java.util.List; 24 | 25 | /** 26 | * user repository. 27 | */ 28 | @Repository 29 | public interface UserDao { 30 | /** 31 | * create table tb_user 32 | */ 33 | void createTbUser(); 34 | 35 | void insertUserInfo(UserInfoPo userInfoPo); 36 | 37 | UserInfoPo findUserBySignUserId(@Param("signUserId") String signUserId); 38 | 39 | UserInfoPo findUserByAddress(@Param("address") String address); 40 | 41 | UserInfoPo findLatestUpdateUser(); 42 | 43 | Integer countOfUser(UserParam userParam); 44 | 45 | /** 46 | * select by encryptType 47 | */ 48 | List findUserList(UserParam userParam); 49 | 50 | /** 51 | * select by appId 52 | */ 53 | List findUserListByAppId(UserParam userParam); 54 | 55 | /** 56 | * delete user by address 57 | */ 58 | int deleteUserBySignUserId(@Param("signUserId") String signUserId); 59 | 60 | List findUserListByTime(@Param("beginTime")LocalDateTime beginTime, @Param("endTime")LocalDateTime endTime); 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/api/service/KeyStoreService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.api.service; 17 | 18 | import com.webank.webase.sign.enums.CodeMessageEnums; 19 | import com.webank.webase.sign.exception.BaseException; 20 | import com.webank.webase.sign.pojo.bo.KeyStoreInfo; 21 | import com.webank.webase.sign.util.AesUtils; 22 | import lombok.extern.slf4j.Slf4j; 23 | import org.apache.commons.lang3.StringUtils; 24 | import org.fisco.bcos.sdk.crypto.CryptoSuite; 25 | import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair; 26 | import org.fisco.bcos.sdk.model.CryptoType; 27 | import org.springframework.beans.factory.annotation.Autowired; 28 | import org.springframework.cache.annotation.Cacheable; 29 | import org.springframework.stereotype.Service; 30 | 31 | /** 32 | * KeyStoreService. 33 | */ 34 | @Slf4j 35 | @Service 36 | public class KeyStoreService { 37 | @Autowired 38 | private AesUtils aesUtils; 39 | 40 | /** 41 | * get KeyStoreInfo by privateKey. 42 | * @param privateKeyRaw hex format 43 | * @param encryptType 1: guomi, 0: standard 44 | */ 45 | @Cacheable(cacheNames = "getCredentials") 46 | public KeyStoreInfo getKeyStoreFromPrivateKey(String privateKeyRaw, int encryptType) throws BaseException { 47 | if (StringUtils.isBlank(privateKeyRaw)) { 48 | log.error("fail getKeyStoreFromPrivateKey. private key is null"); 49 | throw new BaseException(CodeMessageEnums.PRIVATEKEY_IS_NULL); 50 | } 51 | 52 | // support guomi. v1.3.0+: create by type 53 | CryptoKeyPair cryptoKeyPair = getKeyPairByType(privateKeyRaw, encryptType); 54 | return keyPair2KeyStoreInfo(cryptoKeyPair); 55 | } 56 | 57 | /** 58 | * get Key by encrypt type 59 | * @param encryptType 1: guomi, 0: standard 60 | */ 61 | public KeyStoreInfo newKeyByType(int encryptType) throws BaseException { 62 | try { 63 | // support guomi 64 | CryptoKeyPair keyPair = getKeyPairRandom(encryptType); 65 | return keyPair2KeyStoreInfo(keyPair); 66 | } catch (Exception e) { 67 | log.error("createEcKeyPair fail.", e); 68 | throw new BaseException(CodeMessageEnums.SYSTEM_ERROR); 69 | } 70 | } 71 | 72 | 73 | /** 74 | * keyPair to keyStoreInfo. 75 | */ 76 | private KeyStoreInfo keyPair2KeyStoreInfo(CryptoKeyPair cryptoKeyPair) { 77 | String publicKey = cryptoKeyPair.getHexPublicKey(); 78 | String privateKey = cryptoKeyPair.getHexPrivateKey(); 79 | String address = cryptoKeyPair.getAddress(); 80 | log.debug("publicKey:{} privateKey:{} address:{}", publicKey, privateKey, address); 81 | KeyStoreInfo keyStoreInfo = new KeyStoreInfo(); 82 | keyStoreInfo.setPublicKey(publicKey); 83 | keyStoreInfo.setPrivateKey(aesUtils.aesEncrypt(privateKey)); 84 | keyStoreInfo.setAddress(address); 85 | return keyStoreInfo; 86 | } 87 | 88 | public CryptoKeyPair getKeyPairByType(String privateKeyRaw, int encryptType) { 89 | if (encryptType == CryptoType.SM_TYPE) { 90 | return new CryptoSuite(CryptoType.SM_TYPE).createKeyPair(privateKeyRaw); 91 | } else { 92 | return new CryptoSuite(CryptoType.ECDSA_TYPE).createKeyPair(privateKeyRaw); 93 | } 94 | } 95 | 96 | public CryptoKeyPair getKeyPairRandom(int encryptType) { 97 | if (encryptType == CryptoType.SM_TYPE) { 98 | return new CryptoSuite(CryptoType.SM_TYPE).getKeyPairFactory().generateKeyPair(); 99 | } else { 100 | return new CryptoSuite(CryptoType.ECDSA_TYPE).getKeyPairFactory().generateKeyPair(); 101 | } 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/api/service/SignService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.api.service; 17 | 18 | 19 | import com.webank.webase.sign.constant.ConstantProperties; 20 | import com.webank.webase.sign.enums.CodeMessageEnums; 21 | import com.webank.webase.sign.exception.BaseException; 22 | import com.webank.webase.sign.pojo.po.UserInfoPo; 23 | import com.webank.webase.sign.pojo.vo.ReqEncodeInfoVo; 24 | import com.webank.webase.sign.pojo.vo.ReqSignMessageHashVo; 25 | import com.webank.webase.sign.util.CommonUtils; 26 | import java.time.Duration; 27 | import java.time.Instant; 28 | import java.util.Objects; 29 | import lombok.extern.slf4j.Slf4j; 30 | import org.fisco.bcos.sdk.crypto.CryptoSuite; 31 | import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair; 32 | import org.fisco.bcos.sdk.crypto.signature.SignatureResult; 33 | import org.fisco.bcos.sdk.model.CryptoType; 34 | import org.fisco.bcos.sdk.utils.ByteUtils; 35 | import org.fisco.bcos.sdk.utils.Hex; 36 | import org.fisco.bcos.sdk.utils.exceptions.DecoderException; 37 | import org.springframework.beans.factory.annotation.Autowired; 38 | import org.springframework.stereotype.Service; 39 | 40 | /** 41 | * SignService. 42 | */ 43 | @Slf4j 44 | @Service 45 | public class SignService { 46 | 47 | @Autowired 48 | private UserService userService; 49 | @Autowired 50 | ConstantProperties properties; 51 | @Autowired 52 | private KeyStoreService keyStoreService; 53 | 54 | /** 55 | * add sign. 56 | * @param req parameter 57 | */ 58 | public String sign(ReqEncodeInfoVo req) throws BaseException { 59 | String signUserId = req.getSignUserId(); 60 | log.info("start sign. signUserId:{}", signUserId); 61 | Instant startTimeDB = Instant.now(); 62 | // check exist 63 | UserInfoPo userRow = userService.findBySignUserId(signUserId); 64 | log.debug("end query db time: {}", Duration.between(startTimeDB, Instant.now()).toMillis()); 65 | // check user name not exist. 66 | if (Objects.isNull(userRow)) { 67 | log.warn("fail sign, user not exists. signUserId:{}", signUserId); 68 | throw new BaseException(CodeMessageEnums.USER_NOT_EXISTS); 69 | } 70 | int encryptType = userRow.getEncryptType(); 71 | // signature 72 | CryptoKeyPair cryptoKeyPair = keyStoreService.getKeyPairByType(userRow.getPrivateKey(), encryptType); 73 | // make sure hex 74 | byte[] encodedData; 75 | try { 76 | encodedData = ByteUtils.hexStringToBytes(req.getEncodedDataStr()); 77 | } catch (DecoderException e) { 78 | log.error("hexStringToBytes error: ", e); 79 | throw new BaseException(CodeMessageEnums.PARAM_ENCODED_DATA_INVALID); 80 | 81 | } 82 | Instant startTime = Instant.now(); 83 | log.info("start sign. startTime:{}", startTime.toEpochMilli()); 84 | // sign message by type 85 | SignatureResult signatureResult = signMessageByType( 86 | encodedData, cryptoKeyPair, encryptType); 87 | log.info("end sign duration:{}", Duration.between(startTime, Instant.now()).toMillis()); 88 | String signDataStr = CommonUtils.signatureResultToStringByType(signatureResult, encryptType); 89 | log.info("end sign. signUserId:{}", signUserId); 90 | return signDataStr; 91 | } 92 | 93 | public SignatureResult signMessageByType(byte[] message, CryptoKeyPair cryptoKeyPair, 94 | int encryptType) { 95 | if (encryptType == CryptoType.SM_TYPE) { 96 | byte[] messageHash = new CryptoSuite(CryptoType.SM_TYPE).hash(message); 97 | log.debug("userRow.messageHash:{},hex:{}", messageHash, Hex.toHexString(messageHash)); 98 | return new CryptoSuite(CryptoType.SM_TYPE).sign(Hex.toHexString(messageHash), cryptoKeyPair); 99 | } else { 100 | byte[] messageHash = new CryptoSuite(CryptoType.ECDSA_TYPE).hash(message); 101 | log.debug("userRow.messageHash:{},hex:{}", messageHash, Hex.toHexString(messageHash)); 102 | return new CryptoSuite(CryptoType.ECDSA_TYPE).sign(Hex.toHexString(messageHash), cryptoKeyPair); 103 | } 104 | } 105 | 106 | /** 107 | * add signHash. 108 | * @param req parameter 109 | */ 110 | public String signMessageHash(ReqSignMessageHashVo req) throws BaseException { 111 | String signUserId = req.getSignUserId(); 112 | log.info("start sign. signUserId:{}", signUserId); 113 | Instant startTimeDB = Instant.now(); 114 | // check exist 115 | UserInfoPo userRow = userService.findBySignUserId(signUserId); 116 | log.debug("end query db time: {}", Duration.between(startTimeDB, Instant.now()).toMillis()); 117 | // check user name not exist. 118 | if (Objects.isNull(userRow)) { 119 | log.warn("fail sign, user not exists. signUserId:{}", signUserId); 120 | throw new BaseException(CodeMessageEnums.USER_NOT_EXISTS); 121 | } 122 | int encryptType = userRow.getEncryptType(); 123 | // signature 124 | CryptoKeyPair cryptoKeyPair = keyStoreService.getKeyPairByType(userRow.getPrivateKey(), encryptType); 125 | 126 | Instant startTime = Instant.now(); 127 | log.info("start sign. startTime:{}", startTime.toEpochMilli()); 128 | SignatureResult signatureResult = signMessageHashByType( 129 | req.getMessageHash(), cryptoKeyPair, encryptType); 130 | log.info("end sign duration:{}", Duration.between(startTime, Instant.now()).toMillis()); 131 | String signDataStr = CommonUtils.signatureResultToStringByType(signatureResult, encryptType); 132 | log.info("end sign. signUserId:{}", signUserId); 133 | return signDataStr; 134 | } 135 | 136 | public SignatureResult signMessageHashByType(String messageHash, CryptoKeyPair cryptoKeyPair, 137 | int encryptType) { 138 | if (encryptType == CryptoType.SM_TYPE) { 139 | return new CryptoSuite(CryptoType.SM_TYPE).sign(messageHash, cryptoKeyPair); 140 | } else { 141 | return new CryptoSuite(CryptoType.ECDSA_TYPE).sign(messageHash, cryptoKeyPair); 142 | } 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/api/service/UserService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.webank.webase.sign.api.service; 15 | 16 | import java.time.LocalDateTime; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | import java.util.Objects; 20 | import java.util.Optional; 21 | import com.webank.webase.sign.enums.KeyStatus; 22 | import com.webank.webase.sign.pojo.bo.UserParam; 23 | import com.webank.webase.sign.util.CommonUtils; 24 | import org.apache.commons.lang3.StringUtils; 25 | import org.springframework.beans.BeanUtils; 26 | import org.springframework.beans.factory.annotation.Autowired; 27 | import org.springframework.cache.Cache; 28 | import org.springframework.cache.CacheManager; 29 | import org.springframework.cache.annotation.CacheEvict; 30 | import org.springframework.cache.annotation.Cacheable; 31 | import org.springframework.stereotype.Service; 32 | import com.webank.webase.sign.api.dao.UserDao; 33 | import com.webank.webase.sign.enums.CodeMessageEnums; 34 | import com.webank.webase.sign.exception.BaseException; 35 | import com.webank.webase.sign.pojo.bo.KeyStoreInfo; 36 | import com.webank.webase.sign.pojo.po.UserInfoPo; 37 | import com.webank.webase.sign.pojo.vo.RspUserInfoVo; 38 | import com.webank.webase.sign.util.AesUtils; 39 | import lombok.extern.slf4j.Slf4j; 40 | 41 | @Slf4j 42 | @Service 43 | public class UserService { 44 | 45 | @Autowired 46 | private UserDao userDao; 47 | @Autowired 48 | private AesUtils aesUtils; 49 | @Autowired 50 | private KeyStoreService keyStoreService; 51 | @Autowired 52 | private CacheManager cacheManager; 53 | 54 | /** 55 | * add user by encrypt type 56 | */ 57 | public RspUserInfoVo newUser(String signUserId, String appId, int encryptType, 58 | String privateKeyEncoded) throws BaseException { 59 | log.info("start addUser signUserId:{},appId:{},encryptType:{}", signUserId, appId, 60 | encryptType); 61 | // check user uuid exist 62 | UserInfoPo checkSignUserIdExists = userDao.findUserBySignUserId(signUserId); 63 | if (Objects.nonNull(checkSignUserIdExists)) { 64 | if (checkSignUserIdExists.getStatus().equals(KeyStatus.NORMAL.getValue())) { 65 | throw new BaseException(CodeMessageEnums.USER_EXISTS); 66 | } else { 67 | throw new BaseException(CodeMessageEnums.USER_DISABLE); 68 | } 69 | } 70 | 71 | // get keyStoreInfo 72 | KeyStoreInfo keyStoreInfo; 73 | if (StringUtils.isNotBlank(privateKeyEncoded)) { 74 | String privateKey; 75 | // decode base64 as raw private key 76 | try { 77 | privateKey = new String(CommonUtils.base64Decode(privateKeyEncoded)); 78 | keyStoreInfo = keyStoreService.getKeyStoreFromPrivateKey(privateKey, encryptType); 79 | } catch (Exception ex) { 80 | log.error("newUser privatekey encoded format error:{}", privateKeyEncoded); 81 | throw new BaseException(CodeMessageEnums.PRIVATE_KEY_DECODE_FAIL); 82 | } 83 | } else { 84 | keyStoreInfo = keyStoreService.newKeyByType(encryptType); 85 | } 86 | 87 | // save user. 88 | UserInfoPo userInfoPo = new UserInfoPo(); 89 | BeanUtils.copyProperties(keyStoreInfo, userInfoPo); 90 | userInfoPo.setEncryptType(encryptType); 91 | userInfoPo.setSignUserId(signUserId); 92 | userInfoPo.setAppId(appId); 93 | RspUserInfoVo rspUserInfoVo = saveUser(userInfoPo); 94 | log.info("end addUser"); 95 | return rspUserInfoVo; 96 | } 97 | 98 | 99 | /** 100 | * save user. 101 | */ 102 | private RspUserInfoVo saveUser(UserInfoPo userInfoPo) { 103 | // save user 104 | userDao.insertUserInfo(userInfoPo); 105 | 106 | // return 107 | RspUserInfoVo rspUserInfoVo = new RspUserInfoVo(); 108 | BeanUtils.copyProperties(userInfoPo, rspUserInfoVo); 109 | 110 | return rspUserInfoVo; 111 | } 112 | 113 | /** 114 | * query user by userId. 115 | */ 116 | @Cacheable(cacheNames = "user") 117 | public UserInfoPo findBySignUserId(String signUserId) throws BaseException { 118 | log.info("start findBySignUserId. signUserId:{}", signUserId); 119 | UserInfoPo user = userDao.findUserBySignUserId(signUserId); 120 | if (Objects.isNull(user) || user.getStatus().equals(KeyStatus.SUSPENDED.getValue())) { 121 | log.warn("fail findBySignUserId, user not exists. userId:{}", signUserId); 122 | throw new BaseException(CodeMessageEnums.USER_NOT_EXISTS); 123 | } 124 | Optional.ofNullable(user) 125 | .ifPresent(u -> u.setPrivateKey(aesUtils.aesDecrypt(u.getPrivateKey()))); 126 | log.info("end findBySignUserId. userId:{}", signUserId); 127 | return user; 128 | } 129 | 130 | public UserInfoPo findByAddress(String address) throws BaseException { 131 | log.info("start findUserByAddress. address:{}", address); 132 | UserInfoPo user = userDao.findUserByAddress(address); 133 | if (Objects.isNull(user)) { 134 | log.warn("fail findUserByAddress, user not exists. address:{}", address); 135 | throw new BaseException(CodeMessageEnums.USER_NOT_EXISTS); 136 | } 137 | Optional.ofNullable(user) 138 | .ifPresent(u -> u.setPrivateKey(aesUtils.aesDecrypt(u.getPrivateKey()))); 139 | log.info("end findUserByAddress. address:{}", address); 140 | return user; 141 | } 142 | 143 | /** 144 | * count of user. 145 | */ 146 | public int countOfUser(UserParam param) { 147 | Integer count = userDao.countOfUser(param); 148 | return count == null ? 0 : count; 149 | } 150 | 151 | /** 152 | * query user list. 153 | * 154 | * @param param encryptType 1: guomi, 0: standard 155 | */ 156 | public List findUserList(UserParam param) { 157 | log.info("start findUserList."); 158 | List users = userDao.findUserList(param); 159 | List rspUserInfoVos = new ArrayList<>(); 160 | for (UserInfoPo user : users) { 161 | RspUserInfoVo rspUserInfoVo = new RspUserInfoVo(); 162 | BeanUtils.copyProperties(user, rspUserInfoVo); 163 | rspUserInfoVo.setPrivateKey(aesUtils.aesDecrypt(user.getPrivateKey())); 164 | rspUserInfoVos.add(rspUserInfoVo); 165 | } 166 | return rspUserInfoVos; 167 | } 168 | 169 | public List findUserListByAppId(UserParam param) { 170 | log.info("start findUserListByAppId."); 171 | List users = userDao.findUserListByAppId(param); 172 | List rspUserInfoVos = new ArrayList<>(); 173 | for (UserInfoPo user : users) { 174 | RspUserInfoVo rspUserInfoVo = new RspUserInfoVo(); 175 | BeanUtils.copyProperties(user, rspUserInfoVo); 176 | rspUserInfoVos.add(rspUserInfoVo); 177 | } 178 | return rspUserInfoVos; 179 | } 180 | 181 | public List findUserListByTime(LocalDateTime begin, LocalDateTime end) { 182 | log.info("start findUserListByTime."); 183 | List users = userDao.findUserListByTime(begin, end); 184 | 185 | return users; 186 | } 187 | 188 | 189 | /** 190 | * delete user by signUserId 191 | */ 192 | @CacheEvict(cacheNames = "user", beforeInvocation = true) 193 | public void deleteBySignUserId(String signUserId) throws BaseException { 194 | log.info("start deleteByUuid signUserId:{}", signUserId); 195 | UserInfoPo user = userDao.findUserBySignUserId(signUserId); 196 | if (Objects.isNull(user) || user.getStatus().equals(KeyStatus.SUSPENDED.getValue())) { 197 | log.warn("fail deleteByUuid, user not exists. signUserId:{}", signUserId); 198 | throw new BaseException(CodeMessageEnums.USER_NOT_EXISTS); 199 | } 200 | userDao.deleteUserBySignUserId(signUserId); 201 | log.info("end deleteByUuid."); 202 | } 203 | 204 | 205 | public Boolean deleteAllUserCache() { 206 | log.info("delete all user cache"); 207 | 208 | Cache cache = cacheManager.getCache("user"); 209 | if (cache != null) { 210 | cache.clear(); 211 | } 212 | return true; 213 | } 214 | 215 | public Boolean deleteAllCredentialCache() { 216 | log.info("delete all Credential cache"); 217 | 218 | Cache cache = cacheManager.getCache("getCredentials"); 219 | if (cache != null) { 220 | cache.clear(); 221 | } 222 | return true; 223 | } 224 | 225 | public UserInfoPo findLatestUpdatedUser() { 226 | UserInfoPo user = userDao.findLatestUpdateUser(); 227 | return user; 228 | } 229 | } 230 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/aspect/LogAspect.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.webank.webase.sign.aspect; 15 | 16 | import java.time.Duration; 17 | import java.time.Instant; 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | import java.util.Optional; 21 | import org.aspectj.lang.ProceedingJoinPoint; 22 | import org.aspectj.lang.annotation.Around; 23 | import org.aspectj.lang.annotation.Aspect; 24 | import org.aspectj.lang.annotation.Pointcut; 25 | import org.aspectj.lang.reflect.MethodSignature; 26 | import org.slf4j.Logger; 27 | import com.webank.webase.sign.util.JsonUtils; 28 | import org.springframework.stereotype.Component; 29 | import com.webank.webase.sign.manager.LoggerManager; 30 | import org.springframework.validation.BindingResult; 31 | 32 | @Aspect 33 | @Component 34 | public class LogAspect { 35 | 36 | private final String POINT_CUT = "execution(public * com.webank.webase.sign.api.controller.*.*(..))"; 37 | 38 | @Pointcut(POINT_CUT) 39 | public void logPointCut() { 40 | } 41 | 42 | 43 | @Around("logPointCut()") 44 | public Object methodAround(ProceedingJoinPoint point) throws Throwable { 45 | Instant startTime = Instant.now(); 46 | Class targetClass = point.getTarget().getClass(); 47 | MethodSignature methodSignature = (MethodSignature) point.getSignature(); 48 | String methodName = methodSignature.getName(); 49 | Object[] args = point.getArgs(); 50 | Logger logger = LoggerManager.getLogger(targetClass); 51 | // log args of param in controller 52 | // if args contains BindingResult(recursive of request entity and itself), stack over flow 53 | logger.debug("startTime:{} methodName:{} args:{}", startTime, methodName, 54 | JsonUtils.toJSONString(this.excludeBindingResult(args))); 55 | Object result = null; 56 | try { 57 | result = point.proceed(); 58 | } catch (Throwable throwable) { 59 | logger.warn("fail request. methodName:{} ", methodName, throwable); 60 | throw throwable; 61 | } 62 | 63 | String resultStr = Optional.ofNullable(result).map(JsonUtils::toJSONString).orElse(null); 64 | logger.debug("methodName:{} usedTime:{} result:{}", methodName, 65 | Duration.between(startTime, Instant.now()), resultStr); 66 | return result; 67 | } 68 | 69 | private List excludeBindingResult(Object[] params) { 70 | List retainParams = new ArrayList<>(); 71 | for (int index = 0; index < params.length; index++) { 72 | if (!(params[index] instanceof BindingResult)) { 73 | retainParams.add(params[index]); 74 | } 75 | } 76 | return retainParams; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/config/BeanConfig.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.config; 18 | 19 | import org.fisco.bcos.sdk.crypto.CryptoSuite; 20 | import org.fisco.bcos.sdk.model.CryptoType; 21 | import org.springframework.context.annotation.Bean; 22 | import org.springframework.context.annotation.Configuration; 23 | 24 | /** 25 | * init bean in utils 26 | * @author marsli 27 | */ 28 | @Configuration 29 | public class BeanConfig { 30 | 31 | @Bean(name = "ecdsa") 32 | public CryptoSuite getECDSASuite() { 33 | return new CryptoSuite(CryptoType.ECDSA_TYPE); 34 | } 35 | 36 | @Bean(name = "sm") 37 | public CryptoSuite getGuomiSuite() { 38 | return new CryptoSuite(CryptoType.SM_TYPE); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/config/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.config; 17 | 18 | import com.google.common.collect.Lists; 19 | import java.util.HashSet; 20 | import org.springframework.context.annotation.Bean; 21 | import org.springframework.context.annotation.Configuration; 22 | import org.springframework.web.servlet.config.annotation.EnableWebMvc; 23 | import springfox.documentation.builders.ApiInfoBuilder; 24 | import springfox.documentation.builders.RequestHandlerSelectors; 25 | import springfox.documentation.service.ApiInfo; 26 | import springfox.documentation.spi.DocumentationType; 27 | import springfox.documentation.spring.web.plugins.Docket; 28 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 29 | 30 | @Configuration 31 | @EnableSwagger2 32 | public class SwaggerConfig { 33 | /** 34 | * documentation. 35 | * 36 | * @return 37 | */ 38 | @Bean 39 | public Docket documentation() { 40 | return new Docket(DocumentationType.SWAGGER_2).select() 41 | .apis(RequestHandlerSelectors.basePackage("com.webank.webase.sign")).build() 42 | .protocols(new HashSet(Lists.newArrayList("http"))).pathMapping("/") 43 | .apiInfo(apiInfo()).enable(true); 44 | } 45 | 46 | private ApiInfo apiInfo() { 47 | return new ApiInfoBuilder().title("API document").description("sign api") 48 | .version("1.0").build(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/config/TableInitConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | 15 | package com.webank.webase.sign.config; 16 | 17 | import com.webank.webase.sign.api.dao.UserDao; 18 | import org.springframework.beans.factory.InitializingBean; 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | import org.springframework.context.annotation.Configuration; 21 | import lombok.Data; 22 | 23 | @Data 24 | @Configuration 25 | public class TableInitConfig implements InitializingBean { 26 | 27 | @Autowired 28 | private UserDao userDao; 29 | 30 | @Override 31 | public void afterPropertiesSet() { 32 | userDao.createTbUser(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/config/TomcatConfig.java: -------------------------------------------------------------------------------- 1 | //package com.webank.webase.sign.config; 2 | // 3 | //import com.webank.webase.sign.constant.ConstantProperties; 4 | //import org.apache.coyote.http11.Http11NioProtocol; 5 | //import org.springframework.beans.factory.annotation.Autowired; 6 | //import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; 7 | //import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; 8 | //import org.springframework.context.annotation.Bean; 9 | //import org.springframework.context.annotation.Configuration; 10 | // 11 | //@Configuration 12 | //public class TomcatConfig { 13 | // 14 | // 15 | // @Autowired 16 | // private ConstantProperties constantProperties; 17 | // @Bean 18 | // public EmbeddedServletContainerFactory createEmbeddedServletContainerFactory() { 19 | // TomcatEmbeddedServletContainerFactory tomcatFactory = new TomcatEmbeddedServletContainerFactory(); 20 | // tomcatFactory.addConnectorCustomizers(connector -> { 21 | // Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler(); 22 | // protocol.setKeepAliveTimeout(10 * 1000); 23 | // protocol.setMaxKeepAliveRequests(constantProperties.getKeepAliveRequests()); 24 | // }); 25 | // return tomcatFactory; 26 | // } 27 | //} 28 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/constant/ConstantProperties.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.constant; 17 | 18 | import org.springframework.boot.context.properties.ConfigurationProperties; 19 | import org.springframework.context.annotation.Configuration; 20 | 21 | import lombok.Data; 22 | 23 | /** 24 | * constant configuration from file 25 | */ 26 | @Data 27 | @Configuration 28 | @ConfigurationProperties(prefix = ConstantProperties.CONSTANT_PREFIX) 29 | public class ConstantProperties { 30 | public static final String CONSTANT_PREFIX = "constant"; 31 | private String aesKey = "EfdsW23D23d3df43"; 32 | private String aesPattern = "CBC"; 33 | private int keepAliveRequests = 100; 34 | private int syncUsrCacheTaskFixedDelay = 10000; 35 | private boolean supportPrivateKeyTransfer = true; 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/constant/VersionProperties.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | *

7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | *

9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | 15 | package com.webank.webase.sign.constant; 16 | 17 | import lombok.Data; 18 | import org.springframework.beans.factory.annotation.Value; 19 | import org.springframework.stereotype.Component; 20 | 21 | /** 22 | * load 'version' in .yml 23 | */ 24 | @Data 25 | @Component 26 | public class VersionProperties { 27 | 28 | @Value("${version}") 29 | private String version; 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/enums/CodeMessageEnums.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.webank.webase.sign.enums; 15 | 16 | import lombok.AllArgsConstructor; 17 | import lombok.Getter; 18 | import lombok.Setter; 19 | import lombok.ToString; 20 | 21 | /** 22 | * A-BB-CCC A:error level.
23 | * 1:system exception
24 | * 2:business exception
25 | * B:project number
26 | * WeBASE-Sign:03
27 | * C: error code
28 | */ 29 | @Getter 30 | @ToString 31 | @AllArgsConstructor 32 | public enum CodeMessageEnums { 33 | //success 34 | SUCCEED(0, "success"), 35 | 36 | //param 37 | PARAM_EXCEPTION(203003, "param exception"), 38 | PARAM_SIGN_USER_ID_IS_BLANK(203004, "sign user id cannot be blank"), 39 | PARAM_SIGN_USER_ID_IS_INVALID(203005, "invalid sign user id (max length of 64, only support letter and digit)"), 40 | PARAM_APP_ID_IS_BLANK(203006, "app id cannot be blank"), 41 | PARAM_APP_ID_IS_INVALID(203007, "app id invalid, only support letter and digit"), 42 | PARAM_ENCRYPT_TYPE_IS_INVALID(203008, "encrypt type should be 0 (ecdsa) or 1 (guomi)"), 43 | PARAM_ENCODED_DATA_INVALID(203009, "encoded data string must be hex string"), 44 | 45 | //business exception 46 | USER_EXISTS(303001, "user of this sign user id is already exists "), 47 | USER_DISABLE(303006, "user of this sign user id is already been disable"), 48 | USER_NOT_EXISTS(303002, "user does not exist or already been disable"), 49 | PRIVATEKEY_IS_NULL(303003, "privateKey is null"), 50 | PRIVATE_KEY_DECODE_FAIL(303004, "privateKey decode fail"), 51 | PRIVATEKEY_FORMAT_ERROR(303005, "privateKey format error"), 52 | PRIVATEKEY_NOT_SUPPORT_TRANSFER(303006, "privateKey not support transfer"), 53 | 54 | //system error 55 | SYSTEM_ERROR(103001, "system error"), 56 | PARAM_VAILD_FAIL(103002, "param valid fail"); 57 | 58 | int code; 59 | @Setter 60 | String message; 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/enums/EncryptTypes.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.enums; 18 | 19 | /** 20 | * encrypt type status: 21 | * 1: guomi, 0: standard 22 | */ 23 | public enum EncryptTypes { 24 | /** 25 | * not guomi status 26 | */ 27 | STANDARD(0), 28 | /** 29 | * guomi status 30 | */ 31 | GUOMI(1); 32 | 33 | private int value; 34 | 35 | EncryptTypes(Integer gmStatus) { 36 | this.value = gmStatus; 37 | } 38 | 39 | public int getValue() { 40 | return this.value; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/enums/KeyStatus.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.enums; 18 | 19 | /** 20 | * @author marsli 21 | */ 22 | 23 | public enum KeyStatus { 24 | /** 25 | * normal private key 26 | */ 27 | SUSPENDED("0"), 28 | /** 29 | * suspended private key 30 | */ 31 | NORMAL("1"); 32 | 33 | private String status; 34 | 35 | KeyStatus(String keyStatus) { 36 | this.status = keyStatus; 37 | } 38 | 39 | public String getValue() { 40 | return this.status; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/exception/BaseException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.exception; 17 | 18 | import com.webank.webase.sign.enums.CodeMessageEnums; 19 | 20 | /** 21 | * BaseException. 22 | * 23 | */ 24 | public class BaseException extends Exception { 25 | 26 | private static final long serialVersionUID = 1L; 27 | private CodeMessageEnums cme; 28 | 29 | public BaseException(CodeMessageEnums cme) { 30 | super(cme.getMessage()); 31 | this.cme = cme; 32 | } 33 | 34 | public BaseException(String msg) { 35 | super(msg); 36 | this.cme.setMessage(msg); 37 | } 38 | 39 | public CodeMessageEnums getCodeMessageEnums() { 40 | return cme; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/exception/ExceptionsHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.exception; 17 | 18 | import com.fasterxml.jackson.databind.ObjectMapper; 19 | import com.webank.webase.sign.enums.CodeMessageEnums; 20 | import com.webank.webase.sign.pojo.vo.BaseRspVo; 21 | import com.webank.webase.sign.util.JsonUtils; 22 | import java.util.Optional; 23 | import lombok.extern.slf4j.Slf4j; 24 | import org.springframework.beans.TypeMismatchException; 25 | import org.springframework.beans.factory.annotation.Autowired; 26 | import org.springframework.http.HttpStatus; 27 | import org.springframework.web.bind.annotation.ControllerAdvice; 28 | import org.springframework.web.bind.annotation.ExceptionHandler; 29 | import org.springframework.web.bind.annotation.ResponseBody; 30 | import org.springframework.web.bind.annotation.ResponseStatus; 31 | 32 | /** 33 | * ExceptionsHandler. 34 | */ 35 | @ControllerAdvice 36 | @Slf4j 37 | public class ExceptionsHandler { 38 | 39 | @Autowired 40 | ObjectMapper mapper; 41 | 42 | /** 43 | * myExceptionHandler. 44 | * 45 | * @param baseException e 46 | */ 47 | @ResponseBody 48 | @ExceptionHandler(value = BaseException.class) 49 | public BaseRspVo baseExceptionHandler(BaseException baseException) { 50 | log.warn("catch baseException", baseException); 51 | CodeMessageEnums cme = Optional.ofNullable(baseException) 52 | .map(BaseException::getCodeMessageEnums).orElse(CodeMessageEnums.SYSTEM_ERROR); 53 | 54 | BaseRspVo rep = new BaseRspVo(cme); 55 | log.warn("baseException return:{}", JsonUtils.toJSONString(rep)); 56 | return rep; 57 | } 58 | 59 | 60 | /** 61 | * catch:paramException 62 | */ 63 | @ResponseBody 64 | @ExceptionHandler(value = ParamException.class) 65 | @ResponseStatus(value = HttpStatus.BAD_REQUEST) 66 | public BaseRspVo paramExceptionHandler(ParamException paramException) { 67 | log.warn("catch param exception", paramException); 68 | CodeMessageEnums cme = Optional.ofNullable(paramException) 69 | .map(ParamException::getCodeMessageEnums).orElse(CodeMessageEnums.SYSTEM_ERROR); 70 | 71 | BaseRspVo bre = new BaseRspVo(cme); 72 | log.warn("param exception return:{}", JsonUtils.toJSONString(bre)); 73 | return bre; 74 | } 75 | 76 | /** 77 | * parameter exception:TypeMismatchException 78 | */ 79 | @ResponseBody 80 | @ExceptionHandler(value = TypeMismatchException.class) 81 | @ResponseStatus(value = HttpStatus.BAD_REQUEST) 82 | public BaseRspVo typeMismatchExceptionHandler(TypeMismatchException ex) { 83 | log.warn("catch typeMismatchException", ex); 84 | 85 | CodeMessageEnums cme = CodeMessageEnums.PARAM_EXCEPTION; 86 | cme.setMessage(ex.getMessage()); 87 | BaseRspVo bre = new BaseRspVo(cme); 88 | log.warn("typeMismatchException return:{}", JsonUtils.toJSONString(bre)); 89 | return bre; 90 | } 91 | 92 | 93 | /** 94 | * exceptionHandler. 95 | * 96 | * @param exc e 97 | */ 98 | @ResponseBody 99 | @ExceptionHandler(value = Exception.class) 100 | public BaseRspVo exceptionHandler(Exception exc) { 101 | log.info("catch exception", exc); 102 | BaseRspVo rep = new BaseRspVo(CodeMessageEnums.SYSTEM_ERROR); 103 | log.warn("exception return:{}", JsonUtils.toJSONString(rep)); 104 | return rep; 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/exception/ParamException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.exception; 17 | 18 | 19 | import com.webank.webase.sign.enums.CodeMessageEnums; 20 | 21 | /** 22 | * param Exception 23 | */ 24 | public class ParamException extends RuntimeException { 25 | 26 | private static final long serialVersionUID = 1L; 27 | private CodeMessageEnums cme; 28 | 29 | 30 | public ParamException(CodeMessageEnums cme) { 31 | super(cme.getMessage()); 32 | this.cme = cme; 33 | } 34 | 35 | public void setMessage(String msg) { 36 | this.cme.setMessage(msg); 37 | } 38 | public ParamException(String msg) { 39 | super(msg); 40 | this.cme.setMessage(msg); 41 | } 42 | 43 | public CodeMessageEnums getCodeMessageEnums() { 44 | return cme; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/manager/LoggerManager.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package com.webank.webase.sign.manager; 15 | 16 | 17 | import java.util.HashMap; 18 | import java.util.Map; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | /** 23 | * log manager. 24 | */ 25 | public class LoggerManager { 26 | 27 | private static final Map logMap = new HashMap<>(); 28 | 29 | /** 30 | * get logger. 31 | */ 32 | public static Logger getLogger(Class clazz) { 33 | if (!logMap.containsKey(clazz)) { 34 | Logger log = LoggerFactory.getLogger(clazz); 35 | logMap.put(clazz, log); 36 | } 37 | return logMap.get(clazz); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/pojo/bo/BaseQueryParam.java: -------------------------------------------------------------------------------- 1 | package com.webank.webase.sign.pojo.bo; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | @Data 8 | @NoArgsConstructor 9 | @AllArgsConstructor 10 | public class BaseQueryParam { 11 | private Integer start; 12 | private Integer pageSize; 13 | } -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/pojo/bo/KeyStoreInfo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.pojo.bo; 17 | 18 | import lombok.Data; 19 | 20 | @Data 21 | public class KeyStoreInfo { 22 | private String publicKey; 23 | private String privateKey; 24 | private String address; 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/pojo/bo/UserParam.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.pojo.bo; 18 | 19 | import lombok.Data; 20 | import lombok.EqualsAndHashCode; 21 | import lombok.NoArgsConstructor; 22 | import lombok.ToString; 23 | 24 | @Data 25 | @NoArgsConstructor 26 | @ToString(callSuper = true) 27 | @EqualsAndHashCode(callSuper = true) 28 | public class UserParam extends BaseQueryParam{ 29 | 30 | private String appId; 31 | private String encryptType; 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/pojo/po/UserInfoPo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.pojo.po; 17 | 18 | import lombok.Data; 19 | 20 | import java.time.LocalDateTime; 21 | 22 | /** 23 | * UserInfo Plain Object of tb_user table 24 | */ 25 | @Data 26 | public class UserInfoPo { 27 | /** 28 | * id of table tb_user 29 | */ 30 | private Integer userId; 31 | /** 32 | * business user id 33 | */ 34 | private String signUserId; 35 | /** 36 | * app that user belong to 37 | */ 38 | private String appId; 39 | private String address; 40 | private String publicKey; 41 | private String privateKey; 42 | private String description; 43 | /** 44 | * 0 is standard, 1 is guomi 45 | */ 46 | private Integer encryptType; 47 | 48 | private String status; 49 | 50 | private LocalDateTime gmtModify; 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/pojo/vo/BasePageRspVo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.pojo.vo; 18 | 19 | import com.webank.webase.sign.enums.CodeMessageEnums; 20 | import lombok.Data; 21 | import lombok.EqualsAndHashCode; 22 | 23 | /** 24 | * @author marsli 25 | */ 26 | @Data 27 | @EqualsAndHashCode(callSuper = true) 28 | public class BasePageRspVo extends BaseRspVo { 29 | 30 | private long totalCount; 31 | 32 | public BasePageRspVo(CodeMessageEnums cme) { 33 | super(cme); 34 | } 35 | public BasePageRspVo(CodeMessageEnums cme, Object obj, long totalCount) { 36 | super(cme.getCode(), cme.getMessage(), obj); 37 | this.totalCount = totalCount; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/pojo/vo/BaseRspVo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.pojo.vo; 17 | 18 | import com.webank.webase.sign.enums.CodeMessageEnums; 19 | import lombok.Data; 20 | 21 | @Data 22 | public class BaseRspVo { 23 | 24 | private int code; 25 | private String message; 26 | private Object data; 27 | 28 | public BaseRspVo() { 29 | } 30 | 31 | public BaseRspVo(int code) { 32 | this.code = code; 33 | } 34 | 35 | public BaseRspVo(CodeMessageEnums cme) { 36 | this.code = cme.getCode(); 37 | this.message = cme.getMessage(); 38 | } 39 | 40 | /** 41 | * constructor. 42 | * 43 | * @param cme not null 44 | * @param obj result 45 | */ 46 | public BaseRspVo(CodeMessageEnums cme, Object obj) { 47 | this.code = cme.getCode(); 48 | this.message = cme.getMessage(); 49 | this.data = obj; 50 | } 51 | 52 | /** 53 | * constructor. 54 | * 55 | * @param code not null 56 | * @param message not null 57 | * @param obj result 58 | */ 59 | public BaseRspVo(int code, String message, Object obj) { 60 | this.code = code; 61 | this.message = message; 62 | this.data = obj; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/pojo/vo/ReqEncodeInfoVo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.pojo.vo; 17 | 18 | import javax.validation.constraints.NotBlank; 19 | import lombok.Data; 20 | 21 | /** 22 | * ReqEncodeInfoVo. 23 | */ 24 | @Data 25 | public class ReqEncodeInfoVo { 26 | @NotBlank(message = "signUserId cannot be empty") 27 | private String signUserId; 28 | @NotBlank(message = "encodedDataStr cannot be empty") 29 | private String encodedDataStr; 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/pojo/vo/ReqNewUserVo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.pojo.vo; 18 | 19 | import javax.validation.constraints.NotBlank; 20 | import lombok.Data; 21 | 22 | /** 23 | * import private key entity 24 | * @author marsli 25 | */ 26 | @Data 27 | public class ReqNewUserVo { 28 | @NotBlank 29 | private String signUserId; 30 | @NotBlank 31 | private String appId; 32 | private Integer encryptType; 33 | /** 34 | * encoded by base64 35 | */ 36 | private String privateKey; 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/pojo/vo/ReqSignMessageHashVo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.pojo.vo; 17 | 18 | import javax.validation.constraints.NotBlank; 19 | import lombok.Data; 20 | 21 | /** 22 | * ReqHashSignVo. 23 | */ 24 | @Data 25 | public class ReqSignMessageHashVo { 26 | @NotBlank(message = "signUserId cannot be empty") 27 | private String signUserId; 28 | @NotBlank(message = "hashStr cannot be empty") 29 | private String messageHash; 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/pojo/vo/ReqUserInfoVo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.pojo.vo; 18 | 19 | import lombok.Data; 20 | 21 | @Data 22 | public class ReqUserInfoVo { 23 | private String signUserId; 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/pojo/vo/RspSignVo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.pojo.vo; 17 | 18 | import lombok.Data; 19 | 20 | /** 21 | * SignInfo. 22 | * 23 | */ 24 | @Data 25 | public class RspSignVo { 26 | private String signDataStr; 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/pojo/vo/RspUserInfoVo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.pojo.vo; 17 | 18 | import lombok.Data; 19 | 20 | /** 21 | * RspUserInfoVo. 22 | * 23 | */ 24 | @Data 25 | public class RspUserInfoVo { 26 | private String signUserId; 27 | private String appId; 28 | private String address; 29 | private String publicKey; 30 | // not return privateKey 31 | private String privateKey; 32 | private String description; 33 | private Integer encryptType; 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/task/SynUsrTask.java: -------------------------------------------------------------------------------- 1 | package com.webank.webase.sign.task; 2 | 3 | 4 | import com.webank.webase.sign.api.service.UserService; 5 | import com.webank.webase.sign.pojo.po.UserInfoPo; 6 | import java.time.LocalDateTime; 7 | import java.util.List; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.cache.Cache; 11 | import org.springframework.cache.CacheManager; 12 | import org.springframework.scheduling.annotation.Scheduled; 13 | import org.springframework.stereotype.Component; 14 | 15 | @Slf4j 16 | @Component 17 | public class SynUsrTask { 18 | 19 | 20 | @Autowired 21 | private CacheManager cacheManager; 22 | @Autowired 23 | private UserService userService; 24 | 25 | public static LocalDateTime synTime; 26 | 27 | @Scheduled(fixedDelayString = "${constant.syncUsrCacheTaskFixedDelay}") 28 | public void taskStart() { 29 | syncUsrCacheTask(); 30 | } 31 | 32 | public synchronized void syncUsrCacheTask() { 33 | log.debug("start syncUsrCacheTask task"); 34 | 35 | UserInfoPo user = userService.findLatestUpdatedUser(); 36 | if (user == null) { 37 | return; 38 | } 39 | 40 | log.debug("latest delete userId :" + user.getSignUserId()); 41 | LocalDateTime dbLatestUpdateTime = user.getGmtModify(); 42 | 43 | log.debug("***" + synTime + "****db : " + dbLatestUpdateTime); 44 | if (synTime != null && synTime.isBefore(dbLatestUpdateTime)) { 45 | 46 | List userInfoPoList = 47 | userService.findUserListByTime(synTime, dbLatestUpdateTime); 48 | Cache cache = cacheManager.getCache("user"); 49 | for (int i = 0; i < userInfoPoList.size(); i++) { 50 | UserInfoPo userInfoPo = userInfoPoList.get(i); 51 | if (cache.get(userInfoPo.getSignUserId()) != null) { 52 | cache.evict(userInfoPo.getSignUserId()); 53 | log.debug("evict : {}", userInfoPo.getSignUserId()); 54 | } 55 | } 56 | } 57 | synTime = dbLatestUpdateTime; 58 | 59 | 60 | log.debug("end syncUsrCacheTask task"); 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/util/AesUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014-2021 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | 15 | package com.webank.webase.sign.util; 16 | 17 | import java.nio.charset.StandardCharsets; 18 | import java.util.Base64; 19 | import javax.crypto.Cipher; 20 | import javax.crypto.spec.IvParameterSpec; 21 | import javax.crypto.spec.SecretKeySpec; 22 | import lombok.extern.slf4j.Slf4j; 23 | import org.apache.commons.lang3.StringUtils; 24 | import org.springframework.beans.factory.annotation.Autowired; 25 | import org.springframework.stereotype.Component; 26 | import com.webank.webase.sign.constant.ConstantProperties; 27 | 28 | @Slf4j 29 | @Component 30 | public class AesUtils { 31 | 32 | @Autowired 33 | private ConstantProperties constants; 34 | 35 | 36 | private static final String KEY_ALGORITHM = "AES"; 37 | private static final String DEFAULT_IV = "abcdefgh12345678"; 38 | private static final String CBC_PATTERN = "CBC"; 39 | 40 | /** 41 | * AES 加密操作 42 | * 43 | * @param content 待加密内容 44 | * @return 加密数据 45 | */ 46 | public String aesEncrypt(String content) { 47 | return aesEncrypt( content, constants.getAesKey(),null); 48 | } 49 | 50 | /** 51 | * AES 加密操作 52 | * 53 | * @param content 待加密内容 54 | * @param password 加密密码 55 | * @param iv 使用CBC模式,需要一个向量iv,可增加加密算法的强度 56 | * @return 加密数据 57 | */ 58 | public String aesEncrypt(String content, String password, String iv) { 59 | if(StringUtils.isBlank(iv)) { 60 | iv = DEFAULT_IV; 61 | } 62 | try { 63 | //创建密码器 64 | Cipher cipher = Cipher.getInstance(this.getDefaultAesCipherPattern()); 65 | 66 | //密码key(超过16字节即128bit的key,需要替换jre中的local_policy.jar和US_export_policy.jar,否则报错:Illegal key size) 67 | SecretKeySpec keySpec = new SecretKeySpec(password.getBytes("utf-8"), KEY_ALGORITHM); 68 | 69 | //向量iv 70 | IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8")); 71 | 72 | //初始化为加密模式的密码器 73 | if (CBC_PATTERN.equals(constants.getAesPattern())) { 74 | cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec); 75 | } else { 76 | cipher.init(Cipher.ENCRYPT_MODE, keySpec); 77 | } 78 | 79 | //加密 80 | byte[] byteContent = content.getBytes("utf-8"); 81 | byte[] result = cipher.doFinal(byteContent); 82 | 83 | return Base64.getEncoder().encodeToString(result); 84 | } catch (Exception ex) { 85 | log.error(ex.getMessage(),ex); 86 | return null; 87 | } 88 | } 89 | 90 | 91 | /** 92 | * AES 解密操作 93 | * 94 | * @param content 密文 95 | * @return 明文 96 | */ 97 | public String aesDecrypt(String content) { 98 | return aesDecrypt(content, constants.getAesKey(),null); 99 | } 100 | 101 | 102 | /** 103 | * AES 解密操作 104 | * 105 | * @param content 密文 106 | * @param password 密码 107 | * @param iv 使用CBC模式,需要一个向量iv,可增加加密算法的强度 108 | * @return 明文 109 | */ 110 | public String aesDecrypt(String content, String password,String iv) { 111 | if(StringUtils.isBlank(iv)) { 112 | iv = DEFAULT_IV; 113 | } 114 | 115 | try { 116 | //创建密码器 117 | Cipher cipher = Cipher.getInstance(this.getDefaultAesCipherPattern()); 118 | 119 | //密码key 120 | SecretKeySpec keySpec = new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8),KEY_ALGORITHM); 121 | 122 | //向量iv 123 | IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes( 124 | StandardCharsets.UTF_8)); 125 | 126 | //初始化为解密模式的密码器 127 | if (CBC_PATTERN.equals(constants.getAesPattern())) { 128 | cipher.init(Cipher.DECRYPT_MODE,keySpec,ivParameterSpec); 129 | } else { 130 | cipher.init(Cipher.DECRYPT_MODE, keySpec); 131 | } 132 | //执行操作 133 | byte[] encrypted1 = Base64.getDecoder().decode(content); 134 | byte[] result = cipher.doFinal(encrypted1); 135 | 136 | return new String(result, StandardCharsets.UTF_8); 137 | } catch (Exception ex) { 138 | log.error(ex.getMessage(),ex); 139 | } 140 | 141 | return null; 142 | } 143 | 144 | /** 145 | * before v1.4.0, pattern default "ECB", after v1.4.0 use "CBC" as default 146 | * @return 147 | */ 148 | private String getDefaultAesCipherPattern() { 149 | // CBC as default 150 | String aesPattern = constants.getAesPattern(); 151 | String cipherPattern = "AES/" + aesPattern + "/PKCS5Padding"; 152 | log.info("getDefaultAesCipherPattern aes cipher pattern: {}", cipherPattern); 153 | return cipherPattern; 154 | } 155 | 156 | 157 | 158 | } 159 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/util/CommonUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2021 the original author or authors. 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.webank.webase.sign.util; 17 | 18 | import com.webank.webase.sign.enums.CodeMessageEnums; 19 | import com.webank.webase.sign.exception.ParamException; 20 | import com.webank.webase.sign.pojo.vo.BasePageRspVo; 21 | import com.webank.webase.sign.pojo.vo.BaseRspVo; 22 | import java.util.Base64; 23 | import java.util.List; 24 | import java.util.stream.Collectors; 25 | import lombok.extern.slf4j.Slf4j; 26 | import org.apache.commons.lang3.StringUtils; 27 | import org.fisco.bcos.sdk.crypto.signature.ECDSASignatureResult; 28 | import org.fisco.bcos.sdk.crypto.signature.SM2SignatureResult; 29 | import org.fisco.bcos.sdk.crypto.signature.SignatureResult; 30 | import org.fisco.bcos.sdk.model.CryptoType; 31 | import org.fisco.bcos.sdk.rlp.RlpString; 32 | import org.fisco.bcos.sdk.rlp.RlpType; 33 | import org.fisco.bcos.sdk.utils.Numeric; 34 | import org.springframework.validation.BindingResult; 35 | 36 | /** 37 | * CommonUtils. 38 | */ 39 | @Slf4j 40 | public class CommonUtils { 41 | 42 | public static final int publicKeyLength_64 = 64; 43 | /** 44 | * in sm2, v is not used, so used meaningless zero 45 | */ 46 | private static final byte SM_DEFAULT_V_VALUE = 0; 47 | 48 | /** 49 | * byte array: [v + r + s + pub] 50 | * @param signatureResult 51 | * @param encryptType 52 | * @return 53 | */ 54 | public static String signatureResultToStringByType(SignatureResult signatureResult, int encryptType) { 55 | byte[] byteArr; 56 | if (encryptType == CryptoType.SM_TYPE) { 57 | byteArr = sigResult2ByteArrGuomi((SM2SignatureResult) signatureResult); 58 | } else { 59 | byteArr = sigResult2ByteArrECDSA((ECDSASignatureResult) signatureResult); 60 | } 61 | return Numeric.toHexString(byteArr, 0, byteArr.length, false); 62 | } 63 | 64 | private static byte[] sigResult2ByteArrGuomi(SM2SignatureResult signatureResult) { 65 | byte[] targetByteArr; 66 | targetByteArr = new byte[1 + signatureResult.getR().length + signatureResult.getS().length + publicKeyLength_64]; 67 | // set V as default 00 68 | targetByteArr[0] = SM_DEFAULT_V_VALUE; 69 | System.arraycopy(signatureResult.getR(), 0, targetByteArr, 1, signatureResult.getR().length); 70 | System.arraycopy(signatureResult.getS(), 0, targetByteArr, signatureResult.getR().length + 1, 71 | signatureResult.getS().length); 72 | System.arraycopy(signatureResult.getPub(), 0, targetByteArr, 73 | signatureResult.getS().length + signatureResult.getR().length + 1, 74 | signatureResult.getPub().length); 75 | return targetByteArr; 76 | } 77 | 78 | private static byte[] sigResult2ByteArrECDSA(ECDSASignatureResult signatureResult) { 79 | byte[] targetByteArr; 80 | targetByteArr = new byte[1 + signatureResult.getR().length + signatureResult.getS().length]; 81 | targetByteArr[0] = signatureResult.getV(); 82 | System.arraycopy(signatureResult.getR(), 0, targetByteArr, 1, signatureResult.getR().length); 83 | System.arraycopy(signatureResult.getS(), 0, targetByteArr, signatureResult.getR().length + 1, 84 | signatureResult.getS().length); 85 | return targetByteArr; 86 | } 87 | 88 | /** 89 | * check param valid result. 90 | */ 91 | public static void checkParamBindResult(BindingResult result) { 92 | if (result.hasErrors()) { 93 | log.error("param exception. error:{}", JsonUtils.toJSONString(result.getAllErrors())); 94 | String errFieldStr = result.getAllErrors().stream() 95 | .map(obj -> JsonUtils.stringToJsonNode(JsonUtils.toJSONString(obj))) 96 | .map(err -> err.get("field").asText()) 97 | .collect(Collectors.joining(",")); 98 | StringUtils.removeEnd(errFieldStr, ","); 99 | String message = "These fields do not match:" + errFieldStr; 100 | 101 | ParamException paramException = new ParamException(CodeMessageEnums.PARAM_EXCEPTION); 102 | paramException.setMessage(message); 103 | throw paramException; 104 | } 105 | } 106 | 107 | /** 108 | * base response 109 | */ 110 | public static BaseRspVo buildSuccessRspVo(Object data) { 111 | BaseRspVo baseRspVo = new BaseRspVo(CodeMessageEnums.SUCCEED); 112 | baseRspVo.setData(data); 113 | return baseRspVo; 114 | } 115 | 116 | /** 117 | * base page response 118 | */ 119 | public static BaseRspVo buildSuccessPageRspVo(Object data, long totalCount) { 120 | BasePageRspVo basePageRspVo = new BasePageRspVo(CodeMessageEnums.SUCCEED); 121 | basePageRspVo.setData(data); 122 | basePageRspVo.setTotalCount(totalCount); 123 | return basePageRspVo; 124 | } 125 | 126 | /** 127 | * signUserId支持数字,字母与下划线"_" 128 | * @param str 129 | * @return 130 | */ 131 | public static boolean isLetterDigit(String str) { 132 | String regex = "^[a-z0-9A-Z_]+$"; 133 | return str.matches(regex); 134 | } 135 | 136 | /** 137 | * 0 < signUserId <= 64 138 | * @param input 139 | */ 140 | public static boolean checkLengthWithin_64(String input) { 141 | if (input.isEmpty() || input.length() > publicKeyLength_64) { 142 | return false; 143 | } 144 | return true; 145 | } 146 | 147 | /** 148 | * base64Decode. 149 | * 150 | * @param str String 151 | * @return byte[] 152 | */ 153 | public static byte[] base64Decode(String str) { 154 | if (str == null) { 155 | return new byte[0]; 156 | } 157 | return Base64.getDecoder().decode(str); 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/main/java/com/webank/webase/sign/util/JsonUtils.java: -------------------------------------------------------------------------------- 1 | package com.webank.webase.sign.util; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 4 | import com.fasterxml.jackson.core.JsonParser.Feature; 5 | import com.fasterxml.jackson.core.JsonProcessingException; 6 | import com.fasterxml.jackson.core.type.TypeReference; 7 | import com.fasterxml.jackson.databind.DeserializationFeature; 8 | import com.fasterxml.jackson.databind.JavaType; 9 | import com.fasterxml.jackson.databind.JsonNode; 10 | import com.fasterxml.jackson.databind.ObjectMapper; 11 | import com.fasterxml.jackson.databind.SerializationFeature; 12 | import java.io.IOException; 13 | import java.text.SimpleDateFormat; 14 | import lombok.extern.slf4j.Slf4j; 15 | import org.apache.commons.lang3.StringUtils; 16 | 17 | import java.util.LinkedHashMap; 18 | import java.util.List; 19 | import java.util.Map; 20 | import java.util.function.Supplier; 21 | 22 | /** 23 | * Jackson Util 24 | * edit by marsli from hujkay 25 | */ 26 | @Slf4j 27 | public class JsonUtils { 28 | private static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss"; 29 | /** 30 | * 设置一些通用的属性 31 | */ 32 | private static final ThreadLocal OBJECT_MAPPER = ThreadLocal.withInitial(() -> { 33 | ObjectMapper objectMapper = new ObjectMapper(); 34 | // 如果存在未知属性,则忽略不报错 35 | objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 36 | objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); 37 | // 允许key没有双引号 38 | objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); 39 | // 允许key有单引号 40 | objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true); 41 | // 属性值为null的不参与序列化 42 | // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); 43 | objectMapper.setSerializationInclusion(Include.ALWAYS); 44 | // timestamp 45 | objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); 46 | // date format 47 | objectMapper.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT)); 48 | return objectMapper; 49 | }); 50 | 51 | public static String toJSONString(Object obj) { 52 | return obj != null ? toJSONString(obj, () -> "") : ""; 53 | } 54 | 55 | public static String toJSONString(Object obj, Supplier defaultSupplier) { 56 | try { 57 | return obj != null ? OBJECT_MAPPER.get().writeValueAsString(obj) : defaultSupplier.get(); 58 | } catch (Throwable e) { 59 | log.error(String.format("toJSONString %s", obj != null ? obj.toString() : "null"), e); 60 | } 61 | return defaultSupplier.get(); 62 | } 63 | 64 | public static T toJavaObject(String value, Class tClass) { 65 | return StringUtils.isNotBlank(value) ? toJavaObject(value, tClass, () -> null) : null; 66 | } 67 | 68 | public static T toJavaObject(Object obj, Class tClass) { 69 | return obj != null ? toJavaObject(toJSONString(obj), tClass, () -> null) : null; 70 | } 71 | 72 | public static T toJavaObject(String value, Class tClass, Supplier defaultSupplier) { 73 | try { 74 | if (StringUtils.isBlank(value)) { 75 | return defaultSupplier.get(); 76 | } 77 | return OBJECT_MAPPER.get().readValue(value, tClass); 78 | } catch (Throwable e) { 79 | log.error(String.format("toJavaObject exception: \n %s\n %s", value, tClass), e); 80 | } 81 | return defaultSupplier.get(); 82 | } 83 | 84 | public static List toJavaObjectList(String value, Class tClass) { 85 | return StringUtils.isNotBlank(value) ? toJavaObjectList(value, tClass, () -> null) : null; 86 | } 87 | 88 | public static List toJavaObjectList(Object obj, Class tClass) { 89 | return obj != null ? toJavaObjectList(toJSONString(obj), tClass, () -> null) : null; 90 | } 91 | 92 | public static List toJavaObjectList(String value, Class tClass, Supplier> defaultSupplier) { 93 | try { 94 | if (StringUtils.isBlank(value)) { 95 | return defaultSupplier.get(); 96 | } 97 | JavaType javaType = OBJECT_MAPPER.get().getTypeFactory().constructParametricType(List.class, tClass); 98 | return OBJECT_MAPPER.get().readValue(value, javaType); 99 | } catch (Throwable e) { 100 | log.error(String.format("toJavaObjectList exception \n%s\n%s", value, tClass), e); 101 | } 102 | return defaultSupplier.get(); 103 | } 104 | 105 | // 简单地直接用json复制或者转换(Cloneable) 106 | public static T jsonCopy(Object obj, Class tClass) { 107 | return obj != null ? toJavaObject(toJSONString(obj), tClass) : null; 108 | } 109 | 110 | public static Map toMap(String value) { 111 | return StringUtils.isNotBlank(value) ? toMap(value, () -> null) : null; 112 | } 113 | 114 | public static Map toMap(Object value) { 115 | return value != null ? toMap(value, () -> null) : null; 116 | } 117 | 118 | public static Map toMap(Object value, Supplier> defaultSupplier) { 119 | if (value == null) { 120 | return defaultSupplier.get(); 121 | } 122 | try { 123 | if (value instanceof Map) { 124 | return (Map) value; 125 | } 126 | } catch (Exception e) { 127 | log.error("fail to convert" + toJSONString(value), e); 128 | } 129 | return toMap(toJSONString(value), defaultSupplier); 130 | } 131 | 132 | public static Map toMap(String value, Supplier> defaultSupplier) { 133 | if (StringUtils.isBlank(value)) { 134 | return defaultSupplier.get(); 135 | } 136 | try { 137 | return toJavaObject(value, LinkedHashMap.class); 138 | } catch (Exception e) { 139 | log.error(String.format("toMap exception\n%s", value), e); 140 | } 141 | return defaultSupplier.get(); 142 | } 143 | 144 | 145 | public static List toList(String value) { 146 | return StringUtils.isNotBlank(value) ? toList(value, () -> null) : null; 147 | } 148 | 149 | public static List toList(Object value) { 150 | return value != null ? toList(value, () -> null) : null; 151 | } 152 | 153 | public static List toList(String value, Supplier> defaultSuppler) { 154 | if (StringUtils.isBlank(value)) { 155 | return defaultSuppler.get(); 156 | } 157 | try { 158 | return toJavaObject(value, List.class); 159 | } catch (Exception e) { 160 | log.error("toList exception\n" + value, e); 161 | } 162 | return defaultSuppler.get(); 163 | } 164 | 165 | public static List toList(Object value, Supplier> defaultSuppler) { 166 | if (value == null) { 167 | return defaultSuppler.get(); 168 | } 169 | if (value instanceof List) { 170 | return (List) value; 171 | } 172 | return toList(toJSONString(value), defaultSuppler); 173 | } 174 | 175 | /* author: clk */ 176 | 177 | public static boolean isJson(String str) { 178 | try { 179 | OBJECT_MAPPER.get().readTree(str); 180 | return true; 181 | } catch (IOException e) { 182 | return false; 183 | } 184 | } 185 | 186 | public static JsonNode stringToJsonNode(String str) { 187 | try { 188 | return OBJECT_MAPPER.get().readTree(str); 189 | } catch (IOException e) { 190 | log.error("Parse String to JsonNode error : {}", e.getMessage()); 191 | return null; 192 | } 193 | } 194 | 195 | public static String objToString(T obj) { 196 | if (obj == null) { 197 | return null; 198 | } 199 | try { 200 | return obj instanceof String ? (String) obj 201 | : OBJECT_MAPPER.get().writerWithDefaultPrettyPrinter().writeValueAsString(obj); 202 | } catch (JsonProcessingException e) { 203 | log.error("Parse Object to String error : {}", e.getMessage()); 204 | return null; 205 | } 206 | } 207 | 208 | @SuppressWarnings("unchecked") 209 | public static T stringToObj(String str, Class clazz) { 210 | if (StringUtils.isEmpty(str) || clazz == null) { 211 | return null; 212 | } 213 | try { 214 | return clazz.equals(String.class) ? (T) str : OBJECT_MAPPER.get().readValue(str, clazz); 215 | } catch (Exception e) { 216 | log.error("Parse String to Object error : {}", e.getMessage()); 217 | return null; 218 | } 219 | } 220 | 221 | @SuppressWarnings("unchecked") 222 | public static T stringToObj(String str, TypeReference typeReference) { 223 | if (StringUtils.isEmpty(str) || typeReference == null) { 224 | return null; 225 | } 226 | try { 227 | return (T) (typeReference.getType().equals(String.class) ? str 228 | : OBJECT_MAPPER.get().readValue(str, typeReference)); 229 | } catch (IOException e) { 230 | log.error("Parse String to Object error", e); 231 | return null; 232 | } 233 | } 234 | 235 | public static T stringToObj(String str, Class collectionClazz, 236 | Class... elementClazzes) { 237 | JavaType javaType = OBJECT_MAPPER.get().getTypeFactory() 238 | .constructParametricType(collectionClazz, elementClazzes); 239 | try { 240 | return OBJECT_MAPPER.get().readValue(str, javaType); 241 | } catch (IOException e) { 242 | log.error("Parse String to Object error : {}" + e.getMessage()); 243 | return null; 244 | } 245 | } 246 | 247 | public void unload() { 248 | OBJECT_MAPPER.remove(); 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /src/main/resources/application-docker.yml: -------------------------------------------------------------------------------- 1 | # server version 2 | version: v1.5.3 3 | 4 | server: 5 | # 本工程服务端口,端口被占用则修改 6 | port: ${SERVER_PORT:5004} 7 | servlet: 8 | context-path: /WeBASE-Sign 9 | tomcat: 10 | max-threads: 200 #default 200 11 | max-connections: 10000 #default 10000 12 | 13 | spring: 14 | cache: 15 | type: simple 16 | datasource: 17 | # 数据库连接信息 18 | url: jdbc:mysql://${WEBASE_DB_IP:127.0.0.1}:${WEBASE_DB_PORT:3306}/${WEBASE_DB_NAME:webasesign}?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8 19 | # 数据库用户名 20 | username: ${WEBASE_DB_UNAME:defaultAccount} 21 | # 数据库密码 22 | password: ${WEBASE_DB_PWD:defaultPassword} 23 | driver-class-name: com.mysql.cj.jdbc.Driver 24 | hikari: 25 | connection-test-query: SELECT 1 FROM DUAL 26 | connection-timeout: 30000 27 | maximum-pool-size: 20 28 | max-lifetime: 1800000 29 | minimum-idle: 5 30 | # fix swagger 31 | mvc: 32 | pathmatch: 33 | matching-strategy: ant_path_matcher 34 | 35 | constant: 36 | # aes加密key(16位) 37 | aesKey: EfdsW23D23d3df43 38 | # aes加密模式 v1.4.0+ 默认CBC(v1.4.0前默认为ECB) 39 | aesPattern: CBC 40 | keepAliveRequests: 100 41 | syncUsrCacheTaskFixedDelay: 10000 42 | # 返回值是否支持私钥传输 43 | supportPrivateKeyTransfer: true 44 | 45 | mybatis: 46 | mapper-locations: classpath:mapper/*.xml 47 | 48 | logging: 49 | config: classpath:log4j2.xml 50 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | # server version 2 | version: v1.5.3 3 | 4 | server: 5 | # 本工程服务端口,端口被占用则修改 6 | port: 5004 7 | servlet: 8 | context-path: /WeBASE-Sign 9 | tomcat: 10 | max-threads: 200 #default 200 11 | max-connections: 10000 #default 10000 12 | 13 | spring: 14 | cache: 15 | type: simple 16 | datasource: 17 | # 数据库连接信息 18 | url: jdbc:mysql://127.0.0.1:3306/webasesign?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8 19 | # 数据库用户名 20 | username: "dbUsername" 21 | # 数据库密码 22 | password: "dbPassword" 23 | driver-class-name: com.mysql.cj.jdbc.Driver 24 | hikari: 25 | connection-test-query: SELECT 1 FROM DUAL 26 | connection-timeout: 30000 27 | maximum-pool-size: 20 28 | max-lifetime: 1800000 29 | minimum-idle: 5 30 | # fix swagger 31 | mvc: 32 | pathmatch: 33 | matching-strategy: ant_path_matcher 34 | 35 | constant: 36 | # aes加密key(16位) 37 | aesKey: EfdsW23D23d3df43 38 | # aes加密模式 v1.4.0+ 默认CBC(v1.4.0前默认为ECB) 39 | aesPattern: CBC 40 | keepAliveRequests: 100 41 | syncUsrCacheTaskFixedDelay: 10000 42 | # 返回值是否支持私钥传输 43 | supportPrivateKeyTransfer: true 44 | 45 | mybatis: 46 | mapper-locations: classpath:mapper/*.xml 47 | 48 | logging: 49 | config: classpath:log4j2.xml 50 | -------------------------------------------------------------------------------- /src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ./log 5 | 6 | 7 | 8 | 10 | 11 | 12 | 14 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/main/resources/mapper/UserDao.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | CREATE TABLE IF NOT EXISTS tb_user ( 7 | user_id int(11) NOT NULL AUTO_INCREMENT COMMENT '用户编号', 8 | sign_user_id varchar(64) NOT NULL COMMENT '用户唯一的业务编号', 9 | app_id varchar(64) NOT NULL COMMENT '用户对应的应用编号', 10 | address varchar(64) NOT NULL COMMENT '用户地址', 11 | public_key varchar(256) NOT NULL COMMENT '公钥', 12 | private_key varchar(256) NOT NULL COMMENT '私钥', 13 | description varchar(128) DEFAULT NULL COMMENT '描述', 14 | encrypt_type int NOT NULL COMMENT '加密类型,1:国密;0:ECDSA', 15 | gmt_create datetime DEFAULT NULL COMMENT '创建时间', 16 | gmt_modify datetime DEFAULT NULL COMMENT '修改时间', 17 | status char(1) NOT NULL DEFAULT '1' COMMENT '状态: 1 有效 0 无效', 18 | PRIMARY KEY (user_id), 19 | UNIQUE KEY unique_uuid (sign_user_id) 20 | ) ENGINE=InnoDB AUTO_INCREMENT=100001 DEFAULT CHARSET=utf8 COMMENT='用户信息表'; 21 | 22 | 23 | 24 | user_id as userId, 25 | sign_user_id as signUserId, 26 | app_id as appId, 27 | address, 28 | public_key as publicKey, 29 | private_key as privateKey, 30 | description, 31 | status, 32 | encrypt_type as encryptType, 33 | gmt_modify as gmtModify 34 | 35 | 36 | 37 | 38 | select LAST_INSERT_ID() 39 | 40 | insert into tb_user( 41 | `sign_user_id`, 42 | `app_id`, 43 | `address`, 44 | `public_key`, 45 | `private_key`, 46 | `description`, 47 | `encrypt_type`, 48 | `gmt_create`, 49 | `gmt_modify` 50 | ) values ( 51 | #{signUserId}, 52 | #{appId}, 53 | #{address}, 54 | #{publicKey}, 55 | #{privateKey}, 56 | #{description}, 57 | #{encryptType}, 58 | NOW(), 59 | NOW() 60 | ) 61 | 62 | 63 | 68 | 69 | 74 | 75 | 81 | 82 | 92 | 93 | 94 | 102 | 103 | 113 | 114 | 115 | 122 | 123 | 124 | 125 | 126 | UPDATE 127 | tb_user 128 | SET 129 | status = '0', 130 | gmt_modify = NOW() 131 | where sign_user_id = #{signUserId} 132 | 133 | 134 | 135 | 136 | -------------------------------------------------------------------------------- /src/main/resources/swagger/favicon-16x16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeBASE-Sign/e98ab0cced21391fc2951e97e19fb84a701a7f98/src/main/resources/swagger/favicon-16x16.png -------------------------------------------------------------------------------- /src/main/resources/swagger/favicon-32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeBASE-Sign/e98ab0cced21391fc2951e97e19fb84a701a7f98/src/main/resources/swagger/favicon-32x32.png -------------------------------------------------------------------------------- /src/main/resources/swagger/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Swagger UI 7 | 8 | 9 | 10 | 31 | 32 | 33 | 34 |
35 | 36 | 37 | 38 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /src/main/resources/swagger/swagger-ui.css.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sources":[],"names":[],"mappings":"","file":"swagger-ui.css","sourceRoot":""} -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | APP_MAIN=com.webank.webase.sign.Application 4 | CLASSPATH='conf/:apps/*:lib/*' 5 | CURRENT_DIR=$(pwd)/ 6 | LOG_DIR=${CURRENT_DIR}log 7 | CONF_DIR=${CURRENT_DIR}conf 8 | 9 | SERVER_PORT=$(cat $CONF_DIR/application.yml | grep "server:" -A 3 | grep "port" | awk '{print $2}'| sed 's/\r//') 10 | if [ ${SERVER_PORT}"" = "" ];then 11 | echo "$CONF_DIR/application.yml server port has not been configured" 12 | exit -1 13 | fi 14 | 15 | if [ ${JAVA_HOME}"" = "" ];then 16 | echo "JAVA_HOME has not been configured" 17 | exit -1 18 | fi 19 | 20 | mkdir -p log 21 | 22 | startWaitTime=30 23 | processPid=0 24 | processStatus=0 25 | checkProcess(){ 26 | server_pid=$(ps aux | grep java | grep $CURRENT_DIR | grep $APP_MAIN | awk '{print $2}') 27 | if [ -n "$server_pid" ]; then 28 | processPid=$server_pid 29 | processStatus=1 30 | else 31 | processPid=0 32 | processStatus=0 33 | fi 34 | } 35 | 36 | JAVA_OPTS=" -Dfile.encoding=UTF-8" 37 | JAVA_OPTS+=" -Xmx256m -Xms256m -Xmn128m -Xss512k -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=256m" 38 | JAVA_OPTS+=" -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${LOG_DIR}/heap_error.log" 39 | 40 | start(){ 41 | checkProcess 42 | echo "===============================================================================================" 43 | if [ $processStatus == 1 ]; then 44 | echo "Server $APP_MAIN Port $SERVER_PORT is running PID($processPid)" 45 | echo "===============================================================================================" 46 | else 47 | echo -n "Starting Server $APP_MAIN Port $SERVER_PORT ..." 48 | nohup $JAVA_HOME/bin/java $JAVA_OPTS -cp $CLASSPATH $APP_MAIN >> $LOG_DIR/sign.out 2>&1 & 49 | 50 | count=1 51 | result=0 52 | while [ $count -lt 20 ] ; do 53 | checkProcess 54 | if [ $processPid -ne 0 ]; then 55 | result=1 56 | break 57 | fi 58 | let count++ 59 | echo -n "." 60 | sleep 1 61 | done 62 | 63 | if [ $result -ne 0 ]; then 64 | echo "PID($processPid) [Starting]. Please check message through the log file (default path:./log/)." 65 | echo "===============================================================================================" 66 | else 67 | echo "[Failed]. Please check message through the log file (default path:./log/)." 68 | echo "===============================================================================================" 69 | fi 70 | fi 71 | } 72 | 73 | start 74 | -------------------------------------------------------------------------------- /status.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | APP_MAIN=com.webank.webase.sign.Application 4 | CURRENT_DIR=$(pwd)/ 5 | CONF_DIR=${CURRENT_DIR}conf 6 | 7 | SERVER_PORT=$(cat $CONF_DIR/application.yml | grep "server:" -A 3 | grep "port" | awk '{print $2}'| sed 's/\r//') 8 | if [ ${SERVER_PORT}"" = "" ];then 9 | echo "$CONF_DIR/application.yml server port has not been configured" 10 | exit -1 11 | fi 12 | 13 | processPid=0 14 | checkProcess(){ 15 | server_pid=$(ps aux | grep java | grep $CURRENT_DIR | grep $APP_MAIN | awk '{print $2}') 16 | if [ -n "$server_pid" ]; then 17 | processPid=$server_pid 18 | else 19 | processPid=0 20 | fi 21 | } 22 | 23 | status(){ 24 | checkProcess 25 | echo "===============================================================================================" 26 | if [ $processPid -ne 0 ]; then 27 | echo "Server $APP_MAIN Port $SERVER_PORT is running PID($processPid)" 28 | echo "===============================================================================================" 29 | else 30 | echo "Server $APP_MAIN Port $SERVER_PORT is not running" 31 | echo "===============================================================================================" 32 | fi 33 | } 34 | 35 | status 36 | -------------------------------------------------------------------------------- /stop.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | APP_MAIN=com.webank.webase.sign.Application 4 | CURRENT_DIR=$(pwd)/ 5 | CONF_DIR=${CURRENT_DIR}conf 6 | 7 | SERVER_PORT=$(cat $CONF_DIR/application.yml | grep "server:" -A 3 | grep "port" | awk '{print $2}'| sed 's/\r//') 8 | if [ ${SERVER_PORT}"" = "" ];then 9 | echo "$CONF_DIR/application.yml server port has not been configured" 10 | exit -1 11 | fi 12 | 13 | processPid=0 14 | checkProcess(){ 15 | server_pid=$(ps aux | grep java | grep $CURRENT_DIR | grep $APP_MAIN | awk '{print $2}') 16 | if [ -n "$server_pid" ]; then 17 | processPid=$server_pid 18 | else 19 | processPid=0 20 | fi 21 | } 22 | 23 | stop(){ 24 | checkProcess 25 | echo "===============================================================================================" 26 | if [ $processPid -ne 0 ]; then 27 | echo -n "Stopping Server $APP_MAIN Port $SERVER_PORT PID($processPid)..." 28 | kill -9 $processPid 29 | if [ $? -eq 0 ]; then 30 | echo "[Success]" 31 | echo "===============================================================================================" 32 | else 33 | echo "[Failed]" 34 | echo "===============================================================================================" 35 | fi 36 | else 37 | echo "Server $APP_MAIN Port $SERVER_PORT is not running" 38 | echo "===============================================================================================" 39 | fi 40 | } 41 | 42 | stop --------------------------------------------------------------------------------