├── .gitignore ├── .travis.yml ├── Changelog.md ├── Future.md ├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── github │ │ └── trang │ │ └── typehandlers │ │ ├── alias │ │ └── Encrypt.java │ │ ├── crypt │ │ ├── Crypt.java │ │ └── SimpleCrypt.java │ │ ├── type │ │ └── EncryptTypeHandler.java │ │ └── util │ │ ├── ConfigUtil.java │ │ ├── Constants.java │ │ ├── EncryptUtil.java │ │ ├── ReflectionUtil.java │ │ └── StringUtil.java └── resources │ └── default-encrypt.properties └── test ├── java └── com │ └── github │ └── trang │ └── typehandlers │ └── test │ └── converalls │ ├── EncryptTest.java │ └── TestCrypt.java └── resources └── test.properties /.gitignore: -------------------------------------------------------------------------------- 1 | ### Extra 2 | rebel*.xml 3 | 4 | ### Maven template 5 | target/ 6 | pom.xml.tag 7 | pom.xml.releaseBackup 8 | pom.xml.versionsBackup 9 | pom.xml.next 10 | release.properties 11 | dependency-reduced-pom.xml 12 | buildNumber.properties 13 | .mvn/timing.properties 14 | 15 | # Exclude maven wrapper 16 | !/.mvn/wrapper/maven-wrapper.jar 17 | ### macOS template 18 | *.DS_Store 19 | .AppleDouble 20 | .LSOverride 21 | 22 | # Icon must end with two \r 23 | Icon 24 | 25 | 26 | # Thumbnails 27 | ._* 28 | 29 | # Files that might appear in the root of a volume 30 | .DocumentRevisions-V100 31 | .fseventsd 32 | .Spotlight-V100 33 | .TemporaryItems 34 | .Trashes 35 | .VolumeIcon.icns 36 | .com.apple.timemachine.donotpresent 37 | 38 | # Directories potentially created on remote AFP share 39 | .AppleDB 40 | .AppleDesktop 41 | Network Trash Folder 42 | Temporary Items 43 | .apdisk 44 | ### Example user template template 45 | ### Example user template 46 | 47 | # IntelliJ project files 48 | .idea 49 | *.iml 50 | out 51 | gen### Java template 52 | *.class 53 | 54 | # BlueJ files 55 | *.ctxt 56 | 57 | # Mobile Tools for Java (J2ME) 58 | .mtj.tmp/ 59 | 60 | # Package Files # 61 | *.jar 62 | *.war 63 | *.ear 64 | 65 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 66 | hs_err_pid* 67 | ### JDeveloper template 68 | # default application storage directory used by the IDE Performance Cache feature 69 | .data/ 70 | 71 | # used for ADF styles caching 72 | temp/ 73 | 74 | # default output directories 75 | classes/ 76 | deploy/ 77 | javadoc/ 78 | 79 | # lock file, a part of Oracle Credential Store Framework 80 | cwallet.sso.lck### Eclipse template 81 | 82 | .metadata 83 | bin/ 84 | tmp/ 85 | *.tmp 86 | *.bak 87 | *.swp 88 | *~.nib 89 | local.properties 90 | .settings/ 91 | .loadpath 92 | .recommenders 93 | 94 | # Eclipse Core 95 | .project 96 | 97 | # External tool builders 98 | .externalToolBuilders/ 99 | 100 | # Locally stored "Eclipse launch configurations" 101 | *.launch 102 | 103 | # PyDev specific (Python IDE for Eclipse) 104 | *.pydevproject 105 | 106 | # CDT-specific (C/C++ Development Tooling) 107 | .cproject 108 | 109 | # JDT-specific (Eclipse Java Development Tools) 110 | .classpath 111 | 112 | # Java annotation processor (APT) 113 | .factorypath 114 | 115 | # PDT-specific (PHP Development Tools) 116 | .buildpath 117 | 118 | # sbteclipse plugin 119 | .target 120 | 121 | # Tern plugin 122 | .tern-project 123 | 124 | # TeXlipse plugin 125 | .texlipse 126 | 127 | # STS (Spring Tool Suite) 128 | .springBeans 129 | 130 | # Code Recommenders 131 | .recommenders/ 132 | ### JetBrains template 133 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 134 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 135 | 136 | # User-specific stuff: 137 | .idea/workspace.xml 138 | .idea/tasks.xml 139 | 140 | # Sensitive or high-churn files: 141 | .idea/dataSources/ 142 | .idea/dataSources.ids 143 | .idea/dataSources.xml 144 | .idea/dataSources.local.xml 145 | .idea/sqlDataSources.xml 146 | .idea/dynamic.xml 147 | .idea/uiDesigner.xml 148 | 149 | # Gradle: 150 | .idea/gradle.xml 151 | .idea/libraries 152 | 153 | # Mongo Explorer plugin: 154 | .idea/mongoSettings.xml 155 | 156 | ## File-based project format: 157 | *.iws 158 | 159 | ## Plugin-specific files: 160 | 161 | # IntelliJ 162 | /out/ 163 | 164 | # mpeltonen/sbt-idea plugin 165 | .idea_modules/ 166 | 167 | # JIRA plugin 168 | atlassian-ide-plugin.xml 169 | 170 | # Crashlytics plugin (for Android Studio and IntelliJ) 171 | com_crashlytics_export_strings.xml 172 | crashlytics.properties 173 | crashlytics-build.properties 174 | fabric.properties 175 | ### Windows template 176 | # Windows image file caches 177 | Thumbs.db 178 | ehthumbs.db 179 | 180 | # Folder config file 181 | Desktop.ini 182 | 183 | # Recycle Bin used on file shares 184 | $RECYCLE.BIN/ 185 | 186 | # Windows Installer files 187 | *.cab 188 | *.msi 189 | *.msm 190 | *.msp 191 | 192 | # Windows shortcuts 193 | *.lnk -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - openjdk7 4 | sudo: false 5 | install: false 6 | cache: 7 | directories: 8 | - $HOME/.m2/repository 9 | after_success: 10 | - mvn clean test -Pcoveralls jacoco:report coveralls:report -------------------------------------------------------------------------------- /Changelog.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 1.1.1 2017-10-14 4 | 1. FIX ISSUE #1 5 | 2. MyBatis 版本 3.4.4 -> 3.4.5 6 | 3. Maven 插件常规升级 7 | 8 | ## 1.1.0 2017-06-30 9 | 1. 更改包名为 `com.github.trang.typehandlers` 10 | 2. 发布到 Maven 中央仓库 11 | 12 | ## 1.0.2 2017-05-23 13 | 1. 新增自定义加密算法功能 14 | 15 | ## 1.0.1 207-04-27 16 | 1. 兼容老数据 17 | 18 | ## 1.0.0 2017-04-26 19 | 1. 正式发布 -------------------------------------------------------------------------------- /Future.md: -------------------------------------------------------------------------------- 1 | # Future 2 | 3 | 1. 加密算法改为 SPI 模式 4 | ~~2. 完善 ReadMe~~ -------------------------------------------------------------------------------- /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 | # MyBatis Type Handlers for Encrypt 2 | 3 | [![Build Status](https://www.travis-ci.org/drtrang/typehandlers-encrypt.svg?branch=master)](https://www.travis-ci.org/drtrang/typehandlers-encrypt) 4 | [![Coverage Status](https://coveralls.io/repos/github/drtrang/typehandlers-encrypt/badge.svg?branch=master)](https://coveralls.io/github/drtrang/typehandlers-encrypt?branch=master) 5 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.drtrang/typehandlers-encrypt/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.github.drtrang/typehandlers-encrypt) 6 | [![License](http://img.shields.io/badge/license-apache%202-brightgreen.svg)](https://github.com/drtrang/typehandlers-encrypt/blob/master/LICENSE) 7 | 8 | ## 介绍 9 | 应公司安全部门要求,需要对数据库中的敏感信息做加密处理。由于此次需求涉及的字段较多,手动加解密颇为不便且改动较大,一个更加简单、通用的解决方案势在必行。 10 | 11 | `typehandlers-encrypt` 项目在这种背景下诞生,用户使用时无需更改业务代码,仅需少量配置即可实现数据库指定字段的加解密操作,大大减小了对用户的影响。 12 | 13 | 14 | ## 实现原理 15 | 16 | `typehandlers-encrypt` 基于 MyBatis 的 TypeHandler 开发,通过 TypeHandler 可以在 JavaType 和 JdbcType 中互相转换的特性,拦截 JavaType 为 `com.github.trang.typehandlers.alias.Encrypt` 的 SQL,在预处理语句(PreparedStatement)中设置参数时自动加密,并在结果集(ResultSet)中取值时自动解密。 17 | 18 | 注:由于依赖 MyBatis,使用时需要将 `EncryptTypeHandler` 和 `Encrypt` 注册到 MyBatis,否则无法生效,注册方式见 **声明 EncryptTypeHandler**。 19 | 20 | 21 | ## 应用 22 | ### 依赖 23 | ```xml 24 | 25 | com.github.drtrang 26 | typehandlers-encrypt 27 | 1.1.1 28 | 29 | ``` 30 | 31 | ### 声明 EncryptTypeHandler 32 | #### 1. 单独使用 MyBatis 33 | ```xml 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | ``` 43 | 44 | #### 2. 与 Spring 结合 45 | ```java 46 | @Bean 47 | public SqlSessionFactory sqlSessionFactory(Configuration config) { 48 | SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); 49 | factory.setTypeAliasesPackage("com.github.trang.typehandlers.alias"); 50 | factory.setTypeHandlersPackage("com.github.trang.typehandlers.type"); 51 | return factory.getObject(); 52 | } 53 | ``` 54 | 55 | #### 3. 与 SpringBoot 结合 56 | ```yaml 57 | ##application.yml 58 | mybatis: 59 | type-aliases-package: com.github.trang.typehandlers.alias 60 | type-handlers-package: com.github.trang.typehandlers.type 61 | ``` 62 | 63 | 注:以上配置方式**任选其一**即可,请根据实际情况选择。 64 | 65 | ### 使用 EncryptTypeHandler 66 | ```xml 67 | 68 | 69 | 70 | 71 |     72 | 73 | 74 | 75 | 76 | insert into user (id, username, password) 77 | values (#{id,jdbcType=BIGINT}, #{username,jdbcType=VARCHAR}, #{password, javaType=encrypt, jdbcType=VARCHAR}) 78 | 79 | 80 | 81 | 82 | update user set password=#{password, javaType=encrypt, jdbcType=VARCHAR} where id=#{id} 83 | 84 | ``` 85 | 86 | 87 | ## 进阶 88 | `typehandlers-encrypt` 内置了 AES 加密算法与默认的 16 位密钥,支持**开箱即用**,但用户也可以自定义加密算法和密钥,只需要在配置文件中声明对应的配置即可。需要注意,**两者同时配置时,要声明在同一文件里**。 89 | 90 | 配置示例: 91 | ```properties 92 | encrypt.private.key=xxx 93 | encrypt.class.name=com.github.trang.typehandlers.crypt.SimpleEncrypt 94 | ``` 95 | 96 | ### 配置文件查找 97 | 方式一:项目启动时,会在项目的 Classpath 中依次查找名称为 `encrypt`、`properties/config-common`、`properties/config`、`config`、`application` 的 Properties 文件,直到文件存在且文件中包含名称为 `encrypt.private.key` 的属性时停止。 98 | 99 | 方式二:如果项目中不存在以上文件,且不想单独新增,也可以在项目启动时调用 `ConfigUtil.bundleNames("xxx")` 来指定要读取的文件,这时只会从用户给定的文件中查找。 100 | 101 | **当没有查找到相应配置时,项目会使用内置的默认配置。** 102 | 103 | ### 自定义密钥 104 | `typehandlers-encrypt` 支持自定义密钥,只需在配置文件中声明即可。 105 | ```properties 106 | encrypt.private.key=xxx 107 | ``` 108 | 109 | ### 自定义加密算法 110 | `typehandlers-encrypt` 默认的加密算法是 **AES 对称加密**,如果默认算法不满足实际需求,用户可以自己实现 `com.github.trang.typehandlers.crypt.Crypt` 接口,并在配置文件中声明实现类的全路径。 111 | ```properties 112 | encrypt.class.name=com.github.trang.typehandlers.crypt.SimpleEncrypt 113 | ``` 114 | 115 | 116 | ## 硬广 117 | 目前项目已开源,并上传到 [Github](https://github.com/drtrang/typehandlers-encrypt),大家感兴趣的话可以阅读源码。[Github](https://github.com/drtrang/typehandlers-encrypt) 中有配套的 Demo 演示 [`typehandlers-encrypt-demo`](https://github.com/drtrang/typehandlers-encrypt-demo),其中包括 `typehandlers-encrypt` 完整的使用方式,可以作为参考。 118 | 119 | 如果有问题,可以在 Github 上提 ISSUE,或者 QQ 交流,以下是联系方式:
120 | 我的 Github 主页:https://github.com/drtrang
121 | 该项目的 Github 地址:https://github.com/drtrang/typehandlers-encrypt
122 | 配套 Demo 的 Github 地址:https://github.com/drtrang/typehandlers-encrypt-demo
123 | BeanCopier 工具:https://github.com/drtrang/Copiers
124 | QQ:349096849 125 | 126 | 127 | > **注意:** 128 | > 1. 目前 `EncryptTypeHandler` 只支持 JavaType 为 **String** 的情形,如有其它需求,请及时联系我。 129 | > 2. 加密时字段只过滤 **null 值**,非 null 的字段不做任何处理直接加密。 130 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | com.github.drtrang 9 | parent 10 | 1.0.6 11 | 12 | 13 | typehandlers-encrypt 14 | 1.1.2 15 | 16 | type-handlers-encrypt 17 | MyBatis Type Handlers for Encrypt. 18 | https://github.com/drtrang/typehandlers-encrypt 19 | 20 | 21 | 22 | The Apache Software License, Version 2.0 23 | https://github.com/drtrang/typehandlers-encrypt/blob/master/LICENSE 24 | 25 | 26 | 27 | 28 | 29 | trang 30 | donghao.l@hotmail.com 31 | 32 | 33 | 34 | 35 | https://github.com/drtrang/typehandlers-encrypt.git 36 | scm:git:https://github.com/drtrang/typehandlers-encrypt.git 37 | scm:git:https://github.com/drtrang 38 | HEAD 39 | 40 | 41 | 42 | 43 | UTF-8 44 | UTF-8 45 | 1.7 46 | 47 | 48 | 49 | 50 | org.slf4j 51 | slf4j-api 52 | 53 | 54 | org.mybatis 55 | mybatis 56 | true 57 | 58 | 59 | junit 60 | junit 61 | test 62 | 63 | 64 | 65 | 66 | 67 | 68 | maven-enforcer-plugin 69 | 70 | 71 | maven-compiler-plugin 72 | 73 | ${project.build.sourceEncoding} 74 | ${java.version} 75 | ${java.version} 76 | -Xlint:unchecked 77 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /src/main/java/com/github/trang/typehandlers/alias/Encrypt.java: -------------------------------------------------------------------------------- 1 | package com.github.trang.typehandlers.alias; 2 | 3 | import org.apache.ibatis.type.Alias; 4 | 5 | /** 6 | * MyBatis JavaType 别名 7 | * 8 | * @author trang 9 | */ 10 | @Alias("encrypt") 11 | public class Encrypt { 12 | 13 | } -------------------------------------------------------------------------------- /src/main/java/com/github/trang/typehandlers/crypt/Crypt.java: -------------------------------------------------------------------------------- 1 | package com.github.trang.typehandlers.crypt; 2 | 3 | /** 4 | * 加密接口,自定义算法必须实现此接口 5 | * 6 | * @author trang 7 | */ 8 | public interface Crypt { 9 | 10 | /** 11 | * 加密数据 12 | * 13 | * @param content 明文 14 | * @return 密文 15 | */ 16 | String encrypt(String content); 17 | 18 | /** 19 | * 加密数据 20 | * 21 | * @param content 密文 22 | * @return 明文 23 | */ 24 | String decrypt(String content); 25 | 26 | } -------------------------------------------------------------------------------- /src/main/java/com/github/trang/typehandlers/crypt/SimpleCrypt.java: -------------------------------------------------------------------------------- 1 | package com.github.trang.typehandlers.crypt; 2 | 3 | import com.github.trang.typehandlers.util.ConfigUtil; 4 | 5 | import javax.crypto.Cipher; 6 | import javax.crypto.spec.SecretKeySpec; 7 | import java.nio.charset.Charset; 8 | import java.nio.charset.StandardCharsets; 9 | import java.security.GeneralSecurityException; 10 | import java.security.SecureRandom; 11 | 12 | /** 13 | * 默认的 AES 加密算法 14 | * 15 | * @author trang 16 | */ 17 | public enum SimpleCrypt implements Crypt { 18 | INSTANCE; 19 | 20 | private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; 21 | 22 | /** 23 | * 加密数据 24 | * 25 | * @param content 待加密数据 26 | * @return 加密后的 16 进制字符串 27 | */ 28 | @Override 29 | public String encrypt(String content) { 30 | return encrypt(content, DEFAULT_CHARSET); 31 | } 32 | 33 | /** 34 | * 加密数据 35 | * 36 | * @param content 待加密数据 37 | * @param charset 字符集 38 | * @return 加密后的 16 进制字符串 39 | */ 40 | public String encrypt(String content, Charset charset) { 41 | return encrypt(content, ConfigUtil.getPrivateKey(), charset); 42 | } 43 | 44 | /** 45 | * 加密数据 46 | * 47 | * @param content 待加密数据 48 | * @param key 密钥 49 | * @param charset 字符集 50 | * @return 加密后的 16 进制字符串 51 | */ 52 | public String encrypt(String content, String key, Charset charset) { 53 | return byte2Hex(encrypt(content.getBytes(charset), key.getBytes(charset))); 54 | } 55 | 56 | /** 57 | * 执行加密的方法 58 | * 59 | * @param content 待加密数据 60 | * @param key 密钥 61 | */ 62 | public byte[] encrypt(byte[] content, byte[] key) { 63 | return aesCrypt(Cipher.ENCRYPT_MODE, content, key); 64 | } 65 | 66 | /** 67 | * 解密 16 进制字符串 68 | * 69 | * @param content 加密后的 16 进制字符串 70 | * @return 解密后的明文字符串(UTF-8编码) 71 | */ 72 | @Override 73 | public String decrypt(String content) { 74 | return decrypt(content, DEFAULT_CHARSET); 75 | } 76 | 77 | /** 78 | * 解密 16 进制字符串 79 | * 80 | * @param content 加密后的 16 进制字符串 81 | * @param charset 字符集 82 | * @return 解密后的明文字符串(UTF-8编码) 83 | */ 84 | public String decrypt(String content, Charset charset) { 85 | return decrypt(content, ConfigUtil.getPrivateKey(), charset); 86 | } 87 | 88 | /** 89 | * 解密 16 进制字符串 90 | * 91 | * @param content 加密后的 16 进制字符串 92 | * @param key 密钥 93 | * @param charset 字符集 94 | * @return 解密后的明文字符串(UTF-8编码) 95 | */ 96 | public String decrypt(String content, String key, Charset charset) { 97 | byte[] buffer = decrypt(hex2Byte(content), key.getBytes(charset)); 98 | return new String(buffer, charset); 99 | } 100 | 101 | /** 102 | * 实际执行解密的方法 103 | * 104 | * @param content 待解密内容 105 | * @param key 密钥 106 | */ 107 | public byte[] decrypt(byte[] content, byte[] key) { 108 | return aesCrypt(Cipher.DECRYPT_MODE, content, key); 109 | } 110 | 111 | /** 112 | * AES 加密/解密 113 | * 114 | * @param content 需要 加密/解密 的内容 115 | * @param key 加密/解密 密钥 116 | */ 117 | private byte[] aesCrypt(int mode, byte[] content, byte[] key) { 118 | try { 119 | SecureRandom sRandom = SecureRandom.getInstance("SHA1PRNG"); 120 | sRandom.setSeed(key); 121 | byte[] randomBytes = key.clone(); 122 | sRandom.nextBytes(randomBytes); 123 | SecretKeySpec keySpec = new SecretKeySpec(randomBytes, "AES"); 124 | 125 | Cipher cipher = Cipher.getInstance("AES"); 126 | cipher.init(mode, keySpec); 127 | 128 | return cipher.doFinal(content); 129 | } catch (GeneralSecurityException e) { 130 | throw new SecurityException(e); 131 | } 132 | } 133 | 134 | /** 135 | * 将 2 进制转换成 16 进制字符串 136 | */ 137 | private String byte2Hex(byte[] buf) { 138 | StringBuilder sb = new StringBuilder(); 139 | for (byte aBuf : buf) { 140 | String hex = Integer.toHexString(aBuf & 0xFF); 141 | if (hex.length() == 1) { 142 | hex = '0' + hex; 143 | } 144 | sb.append(hex.toUpperCase()); 145 | } 146 | return sb.toString(); 147 | } 148 | 149 | /** 150 | * 将 16 进制字符串转换为 2 进制 151 | */ 152 | private byte[] hex2Byte(String hexStr) { 153 | if (hexStr.length() < 1) { 154 | return null; 155 | } 156 | byte[] result = new byte[hexStr.length() / 2]; 157 | for (int i = 0; i < hexStr.length() / 2; i++) { 158 | int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); 159 | int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); 160 | result[i] = (byte) (high * 16 + low); 161 | } 162 | return result; 163 | } 164 | 165 | } 166 | -------------------------------------------------------------------------------- /src/main/java/com/github/trang/typehandlers/type/EncryptTypeHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.trang.typehandlers.type; 2 | 3 | import com.github.trang.typehandlers.alias.Encrypt; 4 | import com.github.trang.typehandlers.util.EncryptUtil; 5 | import org.apache.ibatis.type.BaseTypeHandler; 6 | import org.apache.ibatis.type.JdbcType; 7 | import org.apache.ibatis.type.MappedTypes; 8 | 9 | import java.sql.CallableStatement; 10 | import java.sql.PreparedStatement; 11 | import java.sql.ResultSet; 12 | import java.sql.SQLException; 13 | 14 | /** 15 | * 拦截 JavaType 为 #{@link Encrypt} 的 SQL 16 | * 注意: 17 | * 1. 加密时字段只过滤 `null` 值,明文不做任何处理直接加密 18 | * 2. 解密时会判断字段是否是加密数据,如果是才会解密否则直接返回原始数据 19 | * 3. fail fast 模式,当加/解密失败时,立即抛出异常 20 | * 21 | * @author trang 22 | */ 23 | @MappedTypes(Encrypt.class) 24 | public class EncryptTypeHandler extends BaseTypeHandler { 25 | 26 | @Override 27 | public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) 28 | throws SQLException { 29 | // 只要 parameter 非空都进行加密 30 | ps.setString(i, EncryptUtil.encrypt(parameter)); 31 | } 32 | 33 | @Override 34 | public String getNullableResult(ResultSet rs, String columnName) throws SQLException { 35 | String r = rs.getString(columnName); 36 | // 兼容待修复的数据 37 | return r == null ? null : (EncryptUtil.isEncrypted(r) ? EncryptUtil.decrypt(r) : r); 38 | } 39 | 40 | @Override 41 | public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { 42 | String r = rs.getString(columnIndex); 43 | // 兼容待修复的数据 44 | return r == null ? null : (EncryptUtil.isEncrypted(r) ? EncryptUtil.decrypt(r) : r); 45 | } 46 | 47 | @Override 48 | public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { 49 | String r = cs.getString(columnIndex); 50 | // 兼容待修复的数据 51 | return r == null ? null : (EncryptUtil.isEncrypted(r) ? EncryptUtil.decrypt(r) : r); 52 | } 53 | 54 | } -------------------------------------------------------------------------------- /src/main/java/com/github/trang/typehandlers/util/ConfigUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.trang.typehandlers.util; 2 | 3 | import com.github.trang.typehandlers.crypt.Crypt; 4 | import com.github.trang.typehandlers.crypt.SimpleCrypt; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | import java.util.*; 9 | 10 | import static com.github.trang.typehandlers.util.Constants.*; 11 | 12 | /** 13 | * 配置文件工具类 14 | * 15 | * 说明: 16 | * 1. 默认加载以下文件:encrypt.properties、properties/config-common.properties、properties/config.properties、 17 | * config.properties、application.properties,当文件存在且包含 encrypt.private.key 属性时认为是配置文件,会以该 18 | * 配置文件中的值为准,如果不存在以上文件则使用默认值,用户也可以通过 ConfigUtil.bundleNames() 方法来指定配置文件 19 | * 的名称,这种情况以指定的为准,若文件不存在则使用默认值 20 | * 2. 自定义私钥:在以上文件中新增属性 encrypt.private.key=私钥 21 | * 自定义算法:在以上文件中新增属性 encrypt.class.name=类的全路径 22 | * 23 | * @author trang 24 | */ 25 | public final class ConfigUtil { 26 | 27 | private static final Logger log = LoggerFactory.getLogger(ConfigUtil.class); 28 | 29 | private ConfigUtil() { 30 | throw new UnsupportedOperationException(); 31 | } 32 | 33 | private static final List INTERNAL_BUNDLE_NAMES = new ArrayList<>(); 34 | private static final List EXTRA_BUNDLE_NAMES = new ArrayList<>(); 35 | private static ResourceBundle DEFAULT_BUNDLE = ResourceBundle.getBundle(DEFAULT_BUNDLE_NAME); 36 | private static ResourceBundle BUNDLE; 37 | private static Crypt CRYPT; 38 | 39 | static { 40 | init(); 41 | } 42 | 43 | private static String findProperty(String name) { 44 | try { 45 | return BUNDLE.getString(name); 46 | } catch (MissingResourceException e) { 47 | return DEFAULT_BUNDLE.getString(name); 48 | } 49 | } 50 | 51 | public static String getPrivateKey() { 52 | return findProperty(PRIVATE_KEY_NAME); 53 | } 54 | 55 | public static Crypt getCrypt() { 56 | return ConfigUtil.CRYPT; 57 | } 58 | 59 | /** 60 | * 检查是否需要兼容历史数据 61 | * TODO 62 | * @return 63 | */ 64 | public static boolean isChecked() { 65 | return false; 66 | } 67 | 68 | private static void init() { 69 | initBundleNames(); 70 | initBundle(); 71 | initCrypt(); 72 | } 73 | 74 | private static void initBundleNames() { 75 | log.debug("init default bundle name"); 76 | INTERNAL_BUNDLE_NAMES.add("encrypt"); 77 | INTERNAL_BUNDLE_NAMES.add("properties/config-common"); 78 | INTERNAL_BUNDLE_NAMES.add("properties/config"); 79 | INTERNAL_BUNDLE_NAMES.add("config"); 80 | INTERNAL_BUNDLE_NAMES.add("application"); 81 | log.debug("init default bundle name completed: {}", INTERNAL_BUNDLE_NAMES); 82 | } 83 | 84 | private static void initBundle() { 85 | log.debug("init default bundle"); 86 | ConfigUtil.BUNDLE = findBundle(0, INTERNAL_BUNDLE_NAMES); 87 | log.debug("init default bundle completed: {}", ConfigUtil.BUNDLE); 88 | } 89 | 90 | private static void initCrypt() { 91 | log.debug("init default crypt"); 92 | ConfigUtil.CRYPT = findCrypt(findProperty(CRYPT_CLASS_NAME)); 93 | log.debug("init default crypt completed: {}", ConfigUtil.CRYPT.getClass().getName()); 94 | } 95 | 96 | public static void bundleNames(String... names) { 97 | if (names != null && names.length > 0) { 98 | Collections.addAll(EXTRA_BUNDLE_NAMES, names); 99 | refreshBundle(); 100 | refreshCrypt(); 101 | } 102 | } 103 | 104 | private static void refreshBundle() { 105 | log.debug("refresh bundle"); 106 | ConfigUtil.BUNDLE = findBundle(0, EXTRA_BUNDLE_NAMES); 107 | log.debug("refresh bundle completed: {}", ConfigUtil.BUNDLE); 108 | } 109 | 110 | private static void refreshCrypt() { 111 | log.debug("refresh crypt"); 112 | String className = findProperty(CRYPT_CLASS_NAME); 113 | if (!className.equalsIgnoreCase(CRYPT.getClass().getName())) { 114 | ConfigUtil.CRYPT = findCrypt(className); 115 | } 116 | log.debug("refresh crypt completed: {}", ConfigUtil.CRYPT.getClass().getName()); 117 | } 118 | 119 | private static ResourceBundle findBundle(int index, List names) { 120 | int size = names.size(); 121 | if (index >= size) { 122 | return DEFAULT_BUNDLE; 123 | } 124 | try { 125 | ResourceBundle bundle = ResourceBundle.getBundle(names.get(index)); 126 | if (bundle.containsKey(PRIVATE_KEY_NAME)) { 127 | return bundle; 128 | } 129 | return findBundle(++index, names); 130 | } catch (MissingResourceException e) { 131 | return findBundle(++index, names); 132 | } 133 | } 134 | 135 | @SuppressWarnings("unchecked") 136 | private static Crypt findCrypt(String className) { 137 | try { 138 | if (StringUtil.isBlank(className)) { 139 | throw new IllegalArgumentException("Property '" + CRYPT_CLASS_NAME + "' can't be null"); 140 | } 141 | Class cryptClass = Class.forName(className); 142 | if (!Crypt.class.isAssignableFrom(cryptClass)) { 143 | throw new IllegalArgumentException("Class '" + cryptClass.getSimpleName() + "' must implements 'Crypt'"); 144 | } 145 | if (SimpleCrypt.class.getName().equals(className)) { 146 | return SimpleCrypt.INSTANCE; 147 | } 148 | Class clazz = (Class) cryptClass; 149 | if (clazz.isEnum()) { 150 | Crypt[] constants = clazz.getEnumConstants(); 151 | if (constants == null || constants.length == 0) { 152 | throw new IllegalArgumentException("Class '" + clazz.getSimpleName() + "' doesn't have any constants"); 153 | } 154 | return constants[0]; 155 | } else { 156 | return ReflectionUtil.newInstance(clazz); 157 | } 158 | } catch (Exception e) { 159 | log.error("init default crypt failed", e); 160 | throw new IllegalArgumentException(e); 161 | } 162 | } 163 | 164 | } -------------------------------------------------------------------------------- /src/main/java/com/github/trang/typehandlers/util/Constants.java: -------------------------------------------------------------------------------- 1 | package com.github.trang.typehandlers.util; 2 | 3 | /** 4 | * 常量池 5 | * 6 | * @author trang 7 | */ 8 | class Constants { 9 | 10 | static final String PRIVATE_KEY_NAME = "encrypt.private.key"; 11 | static final String CRYPT_CLASS_NAME = "encrypt.class.name"; 12 | static final String DEFAULT_BUNDLE_NAME = "default-encrypt"; 13 | 14 | } -------------------------------------------------------------------------------- /src/main/java/com/github/trang/typehandlers/util/EncryptUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.trang.typehandlers.util; 2 | 3 | /** 4 | * 加密工具类 5 | * 6 | * @author trang 7 | */ 8 | public final class EncryptUtil { 9 | 10 | private EncryptUtil() { 11 | throw new UnsupportedOperationException(); 12 | } 13 | 14 | /** 加密后的最短密文长度,用于兼容尚未刷完的数据 */ 15 | private static final int LENGTH = 32; 16 | 17 | public static boolean isEncrypted(String content) { 18 | // FIX #1 19 | return !ConfigUtil.isChecked() || 20 | (StringUtil.isNotBlank(content) && !StringUtil.isNumeric(content) && content.length() >= LENGTH); 21 | } 22 | 23 | public static String encrypt(String content) { 24 | return ConfigUtil.getCrypt().encrypt(content); 25 | } 26 | 27 | public static String decrypt(String content) { 28 | return ConfigUtil.getCrypt().decrypt(content); 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /src/main/java/com/github/trang/typehandlers/util/ReflectionUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.trang.typehandlers.util; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import java.lang.reflect.AccessibleObject; 7 | import java.lang.reflect.Constructor; 8 | 9 | /** 10 | * 反射工具类 11 | * 12 | * @author trang 13 | */ 14 | class ReflectionUtil { 15 | 16 | private static final Logger log = LoggerFactory.getLogger(ReflectionUtil.class); 17 | 18 | /** 19 | * 使用反射新建一个对象,尽全力去新建,如果没有默认构造方法也支持 20 | * 21 | * @param clazz 类型 22 | * @param T 23 | * @return 对象 24 | */ 25 | static T newInstance(final Class clazz) { 26 | Constructor[] constructors = getAllConstructorsOfClass(clazz, true); 27 | if (constructors == null || constructors.length == 0) { 28 | return null; 29 | } 30 | 31 | Object[] initParameters = getInitParameters(constructors[0].getParameterTypes()); 32 | 33 | try { 34 | @SuppressWarnings("unchecked") 35 | T instance = (T) constructors[0].newInstance(initParameters); 36 | return instance; 37 | } catch (Exception e) { 38 | log.error("newInstance", e); 39 | return null; 40 | } 41 | } 42 | 43 | /** 44 | * 获取某个类型的所有构造方法 45 | * 46 | * @param clazz 类型 47 | * @param accessible 是否可以访问 48 | * @return 构造方法数组 49 | */ 50 | private static Constructor[] getAllConstructorsOfClass(final Class clazz, boolean accessible) { 51 | if (clazz == null) { 52 | return null; 53 | } 54 | 55 | Constructor[] constructors = clazz.getDeclaredConstructors(); 56 | if (constructors != null && constructors.length > 0) { 57 | AccessibleObject.setAccessible(constructors, accessible); 58 | } 59 | 60 | return constructors; 61 | } 62 | 63 | /** 64 | * 获取默认参数 65 | * 66 | * @param parameterTypes 参数类型数组 67 | * @return 参数值数组 68 | */ 69 | private static Object[] getInitParameters(Class[] parameterTypes) { 70 | int length = parameterTypes.length; 71 | 72 | Object[] result = new Object[length]; 73 | for (int i = 0; i < length; i++) { 74 | if (parameterTypes[i].isPrimitive()) { 75 | Object init = getPrimitiveDefaultValue(parameterTypes[i]); 76 | result[i] = init; 77 | continue; 78 | } 79 | result[i] = null; 80 | } 81 | 82 | return result; 83 | } 84 | 85 | private static Object getPrimitiveDefaultValue(Class primitiveType) { 86 | if (boolean.class.equals(primitiveType)) { 87 | return false; 88 | } else if (byte.class.equals(primitiveType)) { 89 | return (byte) 0; 90 | } else if (char.class.equals(primitiveType)) { 91 | return '\0'; 92 | } else if (short.class.equals(primitiveType)) { 93 | return (short) 0; 94 | } else if (int.class.equals(primitiveType)) { 95 | return 0; 96 | } else if (long.class.equals(primitiveType)) { 97 | return 0L; 98 | } else if (float.class.equals(primitiveType)) { 99 | return 0F; 100 | } else if (double.class.equals(primitiveType)) { 101 | return 0D; 102 | } else { 103 | return null; 104 | } 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/com/github/trang/typehandlers/util/StringUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.trang.typehandlers.util; 2 | 3 | /** 4 | * 字符串工具类 5 | * 6 | * @author trang 7 | */ 8 | class StringUtil { 9 | 10 | static boolean isEmpty(final CharSequence cs) { 11 | return cs == null || cs.length() == 0; 12 | } 13 | 14 | static boolean isNotEmpty(final CharSequence cs) { 15 | return !isEmpty(cs); 16 | } 17 | 18 | static boolean isBlank(final CharSequence cs) { 19 | int strLen; 20 | if (cs == null || (strLen = cs.length()) == 0) { 21 | return true; 22 | } 23 | for (int i = 0; i < strLen; i++) { 24 | if (!Character.isWhitespace(cs.charAt(i))) { 25 | return false; 26 | } 27 | } 28 | return true; 29 | } 30 | 31 | static boolean isNotBlank(final CharSequence cs) { 32 | return !isBlank(cs); 33 | } 34 | 35 | static boolean isNumeric(final CharSequence cs) { 36 | if (isEmpty(cs)) { 37 | return false; 38 | } 39 | final int sz = cs.length(); 40 | for (int i = 0; i < sz; i++) { 41 | if (!Character.isDigit(cs.charAt(i))) { 42 | return false; 43 | } 44 | } 45 | return true; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/resources/default-encrypt.properties: -------------------------------------------------------------------------------- 1 | encrypt.private.key=1OJR04NMFG4JR6N8 2 | encrypt.class.name=com.github.trang.typehandlers.crypt.SimpleCrypt -------------------------------------------------------------------------------- /src/test/java/com/github/trang/typehandlers/test/converalls/EncryptTest.java: -------------------------------------------------------------------------------- 1 | package com.github.trang.typehandlers.test.converalls; 2 | 3 | import com.github.trang.typehandlers.util.ConfigUtil; 4 | import com.github.trang.typehandlers.util.EncryptUtil; 5 | import org.junit.Test; 6 | 7 | import java.util.concurrent.ExecutorService; 8 | import java.util.concurrent.Executors; 9 | import java.util.concurrent.atomic.AtomicInteger; 10 | 11 | /** 12 | * @author trang 13 | */ 14 | public class EncryptTest { 15 | 16 | @Test 17 | public void test() throws InterruptedException { 18 | final AtomicInteger atomic = new AtomicInteger(); 19 | Runnable task = new Runnable() { 20 | @Override 21 | public void run() { 22 | int i = atomic.getAndAdd(1); 23 | String encrypt = EncryptUtil.encrypt("" + i); 24 | System.out.println(EncryptUtil.decrypt(encrypt)); 25 | } 26 | }; 27 | ExecutorService executor = Executors.newFixedThreadPool(20); 28 | for (int i = 0; i < 20; i++) { 29 | executor.execute(task); 30 | } 31 | Thread.sleep(3000); 32 | } 33 | 34 | @Test 35 | public void e() throws InterruptedException { 36 | System.out.println(EncryptUtil.encrypt("A")); 37 | System.out.println(EncryptUtil.encrypt("A")); 38 | System.out.println(EncryptUtil.encrypt("A")); 39 | 40 | ConfigUtil.bundleNames("test"); 41 | System.out.println(EncryptUtil.encrypt("A")); 42 | System.out.println(EncryptUtil.encrypt("A")); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/com/github/trang/typehandlers/test/converalls/TestCrypt.java: -------------------------------------------------------------------------------- 1 | package com.github.trang.typehandlers.test.converalls; 2 | 3 | import com.github.trang.typehandlers.crypt.Crypt; 4 | 5 | /** 6 | * @author trang 7 | */ 8 | public class TestCrypt implements Crypt { 9 | 10 | @Override 11 | public String encrypt(String content) { 12 | return "1"; 13 | } 14 | 15 | @Override 16 | public String decrypt(String content) { 17 | return "3"; 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /src/test/resources/test.properties: -------------------------------------------------------------------------------- 1 | encrypt.private.key=1OJR04NMFG4JR6N1 --------------------------------------------------------------------------------