├── .gitignore ├── LICENSE ├── README.md ├── deploy.sh ├── mybatis-encrypt-spring-boot-starter ├── pom.xml └── src │ ├── main │ └── java │ │ └── io │ │ └── github │ │ └── weasleyj │ │ └── mybatis │ │ └── encrypt │ │ ├── annotation │ │ ├── EnableMybatisEncryption.java │ │ └── Encryption.java │ │ ├── config │ │ ├── MybatisEncryptConfigurer.java │ │ └── MybatisEncryptProperties.java │ │ ├── constant │ │ ├── EncryptConstant.java │ │ └── EncryptType.java │ │ ├── core │ │ ├── DefaultAesEncryptStrategyImpl.java │ │ ├── DefaultBase64EncryptStrategyImpl.java │ │ └── EncryptStrategy.java │ │ ├── exception │ │ └── MybatisEncryptException.java │ │ └── interceptor │ │ └── DefaultMybatisEncryptInterceptor.java │ └── test │ └── java │ └── io │ └── github │ └── weasleyj │ └── mybatis │ └── encrypt │ └── core │ ├── DefaultAesEncryptStrategyImplTest.java │ └── DefaultBase64EncryptStrategyImplTest.java ├── mybatis-encrypt-spring-boot-tests ├── h2.mv.db ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ ├── MybatisEncryptTestsApp.java │ │ │ ├── common │ │ │ ├── config │ │ │ │ └── Jackson2ObjectMapperConfig.java │ │ │ └── page │ │ │ │ ├── PageHandler.java │ │ │ │ └── PageWrapper.java │ │ │ ├── controller │ │ │ └── MemberController.java │ │ │ ├── demain │ │ │ └── DttMember.java │ │ │ ├── mapper │ │ │ └── MemberMapper.java │ │ │ └── service │ │ │ ├── MemberService.java │ │ │ └── impl │ │ │ └── MemberServiceImpl.java │ └── resources │ │ ├── application-h2.yml │ │ ├── application-mysql.yml │ │ ├── application-oracle.yml │ │ ├── application.yml │ │ ├── mapper │ │ └── example │ │ │ └── MemberMapper.xml │ │ └── member.json │ └── test │ └── java │ └── com │ └── example │ └── EncryptionTestsAppTests.java └── pom.xml /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | assets/ 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | mybatis-encrypt-spring-boot-starter Copyright (C) 2022 Weasley J 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mybatis-encrypt-spring-boot-parent 2 | 3 | **A spring-boot starter to encrypt and decrypt some column of database** 4 | 5 | ## [![Maven Central](https://img.shields.io/maven-central/v/io.github.weasley-j/mybatis-encrypt-spring-boot-starter)](https://search.maven.org/artifact/io.github.weasley-j/mybatis-encrypt-spring-boot-starter) 6 | 7 | Tips: For running test application I recommend you to set the correct path that you can get a cleanning project directory. 8 | 9 | - Set value of `spring.datasource.url` 10 | 11 | ```yaml 12 | spring: 13 | datasource: 14 | embedded-database-connection: h2 15 | driver-class-name: org.h2.Driver 16 | #url: jdbc:h2:mem:h2;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE 17 | url: jdbc:h2:/Users/weasley/Development/IdeaProjects/mybatis-encrypt-spring-boot-parent/mybatis-encrypt-spring-boot-tests/h2;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE 18 | username: "" 19 | password: "" 20 | ``` 21 | 22 | - Set value for `alphahub.dtt.all-in-one-table.filepath` and `alphahub.dtt.code-generator.module-path` 23 | 24 | ```yaml 25 | alphahub: 26 | dtt: 27 | show-sql: on 28 | all-in-one-table: 29 | enable: true 30 | filename: all_in_one.sql 31 | filepath: /Users/weasley/Downloads 32 | code-generator: 33 | is-enable: on 34 | include-controller: on 35 | include-interface: on 36 | override-exists: off 37 | remove-prefix: dtt 38 | base-classes: 39 | - com.example.demain.DttMember 40 | module-name: example 41 | module-package: com.example 42 | module-path: /Users/weasley/Development/IdeaProjects/mybatis-encrypt-spring-boot-parent/mybatis-encrypt-spring-boot-tests 43 | ``` 44 | 45 | 46 | 47 | # Quick start 48 | 49 | 50 | 51 | ## 1 Add dependences for your project pom.xml 52 | 53 | ```xml 54 | 55 | 56 | io.github.weasley-j 57 | mybatis-encrypt-spring-boot-starter 58 | 1.0.3 59 | 60 | ``` 61 | 62 | 63 | 64 | ## 2 Configure your configuration yaml file 65 | 66 | [`MyBatis` encryption configuration](https://github.com/Weasley-J/mybatis-encrypt-spring-boot-parent/blob/main/mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/config/MybatisEncryptProperties.java),2 algorithms embeded. you can choose one of them. Or you can implement you own algorithm. 67 | 68 | ### 2.1 Base64 algorithm 69 | 70 | ```yaml 71 | # mybatis encryption configuration 72 | mybatis: 73 | encrypt: 74 | enable: on 75 | encrypt-type: base64 76 | ``` 77 | 78 | ### 2.2 AES algorithm 79 | 80 | **Replace your own key and keyIv** 81 | 82 | ```yaml 83 | # mybatis encryption configuration 84 | mybatis: 85 | encrypt: 86 | enable: on 87 | encrypt-type: aes 88 | aes: 89 | key: Jidkdp1mWL1tRyK= 90 | key-iv: Poikdp1mWL1jijK= 91 | ``` 92 | 93 | ## 2.3 DIY algorithm 94 | 95 | As you choose `encrypt-type = diy`,you must implement [`io.github.weasleyj.mybatis.encrypt.core.EncryptStrategy`](https://github.com/Weasley-J/mybatis-encrypt-spring-boot-parent/blob/main/mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/core/EncryptStrategy.java) to define your own algorithms for encryption and decryption some column of database, 96 | 97 | ```yaml 98 | # mybatis encryption configuration 99 | mybatis: 100 | encrypt: 101 | enable: on 102 | encrypt-type: diy 103 | diy: 104 | encrypt-strategy: com.somepackage.YourEncryptStrategyImpl 105 | ``` 106 | 107 | 108 | 109 | 3 Use `@EnableMybatisEncryption` annotation to annotate a `Bean` of your application that `Spring AOC` can find it 110 | 111 | - Annotate on Java configuration class 112 | 113 | ```java 114 | import io.github.weasleyj.mybatis.encrypt.annotation.EnableMybatisEncryption; 115 | import org.springframework.context.annotation.Configuration; 116 | 117 | /** 118 | * Mybatis Encrypt Configuration class 119 | * 120 | * @author weasley 121 | * @version 1.0.0 122 | */ 123 | @Configuration 124 | @EnableMybatisEncryption 125 | public class MybatisEncryptConfig { 126 | 127 | } 128 | ``` 129 | 130 | - Annotate on your SpringBoot aplciation Main class 131 | 132 | ```java 133 | import io.github.weasleyj.mybatis.encrypt.annotation.EnableMybatisEncryption; 134 | import org.springframework.boot.SpringApplication; 135 | import org.springframework.boot.autoconfigure.SpringBootApplication; 136 | 137 | /** 138 | * Some application Main class 139 | */ 140 | @SpringBootApplication 141 | @EnableMybatisEncryption 142 | public class SomeApplication { 143 | public static void main(String[] args) { 144 | SomeApplication.run(SomeApplication.class, args); 145 | } 146 | } 147 | ``` 148 | 149 | 150 | 151 | ## 3 Wirte a Java bean that MyBatis can map with table column 152 | 153 | - Use `@Encryption` annotate on the field property which you need encryption and decryption,Here is an example to decrypt and encrypt `nickname`: 154 | 155 | [API link](https://github.com/Weasley-J/mybatis-encrypt-spring-boot-parent/blob/8500f7454d5ec150b5ece6549f4608b38183af19/mybatis-encrypt-spring-boot-tests/src/main/java/com/example/controller/MemberController.java#L112): http://localhost:8080/api/member/save/direct 156 | 157 | 158 | 159 | ```java 160 | import com.baomidou.mybatisplus.annotation.TableId; 161 | import io.github.weasleyj.mybatis.encrypt.annotation.Encryption; 162 | import lombok.AllArgsConstructor; 163 | import lombok.Builder; 164 | import lombok.Data; 165 | import lombok.NoArgsConstructor; 166 | import lombok.experimental.Accessors; 167 | 168 | import java.io.Serializable; 169 | import java.math.BigDecimal; 170 | import java.time.LocalDate; 171 | import java.time.LocalDateTime; 172 | import java.time.LocalTime; 173 | 174 | /** 175 | * 用户信息 176 | */ 177 | @Data 178 | @Builder 179 | @AllArgsConstructor 180 | @NoArgsConstructor 181 | @Accessors(chain = true) 182 | public class DttMember implements Serializable { 183 | /** 184 | * 主键id 185 | * 186 | * @primaryKey 187 | */ 188 | @TableId 189 | private Long memberId; 190 | /** 191 | * 用户openId 192 | * 193 | * @defaultValue e1be63305 194 | * @length 16 195 | */ 196 | private String openId; 197 | /** 198 | * 用户昵称 199 | * 200 | * @length 32 201 | */ 202 | @Encryption 203 | private String nickname; 204 | /** 205 | * 是否启用, 默认:1 206 | * 207 | * @defaultValue true 208 | */ 209 | private Boolean isEnable; 210 | /** 211 | * 用户积分余额, 默认:0.00 212 | * 213 | * @precision 10 214 | * @scale 4 215 | * @defaultValue 0.01 216 | */ 217 | private BigDecimal balance; 218 | /** 219 | * 出生日期,格式:yyyy-MM-dd HH:mm:ss 220 | */ 221 | private LocalDateTime birthday; 222 | /** 223 | * 用户状态;0 正常(默认),1 已冻结,2 账号已封,3 账号异常 224 | * 225 | * @defaultValue 3 226 | */ 227 | private Integer status; 228 | /** 229 | * 账户注销状态;0 未注销(默认),1 已销户 230 | * 231 | * @defaultValue 1 232 | * @dbDataType SMALLINT 233 | */ 234 | private Integer deleted; 235 | /** 236 | * 注册时间,格式: yyyy-MM-dd 237 | */ 238 | private LocalDate registrarDate; 239 | /** 240 | * 会员加速开始时间, 格式:HH:mm:ss 241 | */ 242 | private LocalTime accelerateBeginTime; 243 | /** 244 | * 会员加速结束时间, 格式:HH:mm:ss 245 | */ 246 | private LocalTime accelerateEndTime; 247 | /** 248 | * 修改时间 249 | */ 250 | private LocalDateTime updateTime; 251 | } 252 | ``` 253 | 254 | - When sql with type of ` INSERT`,`UPDATE` Executed by `MyBatis` Executor, `nickname` will be encrypted, i.e: 255 | 256 | ```log 257 | Creating a new SqlSession 258 | Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@69693f7a] 259 | JDBC Connection [HikariProxyConnection@1043294096 wrapping conn1: url=jdbc:h2:/Users/weasley/Development/IdeaProjects/mybatis-encrypt-spring-boot-parent/mybatis-encrypt-spring-boot-tests/h2 user=] will be managed by Spring 260 | ==> Preparing: SELECT MAX(member_id) memberId FROM dtt_member 261 | ==> Parameters: 262 | <== Columns: MEMBERID 263 | <== Row: 5 264 | <== Total: 1 265 | Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@69693f7a] 266 | 2022-12-20 17:30:27.737 INFO 15312 --- [nio-8080-exec-1] com.example.controller.MemberController : {"memberId":6,"openId":"fawezOE5sT","nickname":"蒋震南","isEnable":true,"balance":865,"birthday":"2022-12-20 17:30:27","status":0,"deleted":1,"registrarDate":"2022-12-20","accelerateBeginTime":"17:30:27","accelerateEndTime":"17:30:27","updateTime":"2022-12-20 17:30:27"} 267 | Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@69693f7a] from current transaction 268 | 2022-12-20 17:30:27.822 DEBUG 15312 --- [nio-8080-exec-1] w.m.e.i.DefaultMybatisEncryptInterceptor : Encrypt field for 'nickname', Plaintext: 蒋震南, Ciphertext: IgaLfu2eBut5jAKENLZd3A== 269 | ==> Preparing: INSERT INTO dtt_member ( member_id, open_id, nickname, is_enable, balance, birthday, status, deleted, registrar_date, accelerate_begin_time, accelerate_end_time, update_time ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) 270 | ==> Parameters: 6(Long), fawezOE5sT(String), IgaLfu2eBut5jAKENLZd3A==(String), true(Boolean), 865(BigDecimal), 2022-12-20T17:30:27.558(LocalDateTime), 0(Integer), 1(Integer), 2022-12-20(LocalDate), 17:30:27.558(LocalTime), 17:30:27.558(LocalTime), 2022-12-20T17:30:27.558(LocalDateTime) 271 | <== Updates: 1 272 | ``` 273 | 274 | Real SQL: 275 | 276 | ```sql 277 | INSERT INTO dtt_member ( member_id, open_id, nickname, is_enable, balance, birthday, status, deleted, registrar_date, accelerate_begin_time, accelerate_end_time, update_time ) VALUES ( 6, 'fawezOE5sT', 'IgaLfu2eBut5jAKENLZd3A==', true, 865, '2022-12-20T17:30:27.558', 0, 1, '2022-12-20', '17:30:27.558', '17:30:27.558', '2022-12-20T17:30:27.558' ); 278 | 279 | ``` 280 | 281 | 282 | 283 | - When sql with type of ` SELECT` Executed by `MyBatis` Executor, `nickname` will be decrypted, i.e: 284 | 285 | [API link](https://github.com/Weasley-J/mybatis-encrypt-spring-boot-parent/blob/8500f7454d5ec150b5ece6549f4608b38183af19/mybatis-encrypt-spring-boot-tests/src/main/java/com/example/controller/MemberController.java#L53): http://localhost:8080/api/member/page/pagehelper?pageNum=1&pageSize=10 286 | 287 | ```log 288 | JDBC Connection [HikariProxyConnection@670142194 wrapping conn1: url=jdbc:h2:/Users/weasley/Development/IdeaProjects/mybatis-encrypt-spring-boot-parent/mybatis-encrypt-spring-boot-tests/h2 user=] will not be managed by Spring 289 | ==> Preparing: SELECT count(0) FROM dtt_member 290 | ==> Parameters: 291 | <== Columns: COUNT(*) 292 | <== Row: 6 293 | <== Total: 1 294 | ==> Preparing: SELECT member_id,open_id,nickname,is_enable,balance,birthday,status,deleted,registrar_date,accelerate_begin_time,accelerate_end_time,update_time FROM dtt_member LIMIT ? 295 | ==> Parameters: 10(Integer) 296 | <== Columns: MEMBER_ID, OPEN_ID, NICKNAME, IS_ENABLE, BALANCE, BIRTHDAY, STATUS, DELETED, REGISTRAR_DATE, ACCELERATE_BEGIN_TIME, ACCELERATE_END_TIME, UPDATE_TIME 297 | <== Row: 1, fawezOE5sT, IgaLfu2eBut5jAKENLZd3A==, TRUE, 865.0000, 2022-12-20 13:33:46.547, 0, 1, 2022-12-20, 13:33:47, 13:33:47, 2022-12-20 13:33:46.547 298 | <== Row: 2, fawezOE5sT, IgaLfu2eBut5jAKENLZd3A==, TRUE, 865.0000, 2022-12-20 13:33:49.226, 0, 1, 2022-12-20, 13:33:49, 13:33:49, 2022-12-20 13:33:49.226 299 | <== Row: 3, fawezOE5sT, IgaLfu2eBut5jAKENLZd3A==, TRUE, 865.0000, 2022-12-20 13:33:50.398, 0, 1, 2022-12-20, 13:33:50, 13:33:50, 2022-12-20 13:33:50.398 300 | <== Row: 4, fawezOE5sT, IgaLfu2eBut5jAKENLZd3A==, TRUE, 865.0000, 2022-12-20 13:33:51.319, 0, 1, 2022-12-20, 13:33:51, 13:33:51, 2022-12-20 13:33:51.319 301 | <== Row: 5, fawezOE5sT, IgaLfu2eBut5jAKENLZd3A==, TRUE, 865.0000, 2022-12-20 13:33:52.31, 0, 1, 2022-12-20, 13:33:52, 13:33:52, 2022-12-20 13:33:52.31 302 | <== Row: 6, fawezOE5sT, IgaLfu2eBut5jAKENLZd3A==, TRUE, 865.0000, 2022-12-20 17:30:27.558, 0, 1, 2022-12-20, 17:30:28, 17:30:28, 2022-12-20 17:30:27.558 303 | <== Total: 6 304 | 2022-12-20 17:45:12.534 DEBUG 15634 --- [nio-8080-exec-1] w.m.e.i.DefaultMybatisEncryptInterceptor : Decrypt field for 'nickname', Ciphertext: IgaLfu2eBut5jAKENLZd3A==, Plaintext: 蒋震南 305 | 2022-12-20 17:45:12.534 DEBUG 15634 --- [nio-8080-exec-1] w.m.e.i.DefaultMybatisEncryptInterceptor : Decrypt field for 'nickname', Ciphertext: IgaLfu2eBut5jAKENLZd3A==, Plaintext: 蒋震南 306 | 2022-12-20 17:45:12.534 DEBUG 15634 --- [nio-8080-exec-1] w.m.e.i.DefaultMybatisEncryptInterceptor : Decrypt field for 'nickname', Ciphertext: IgaLfu2eBut5jAKENLZd3A==, Plaintext: 蒋震南 307 | 2022-12-20 17:45:12.535 DEBUG 15634 --- [nio-8080-exec-1] w.m.e.i.DefaultMybatisEncryptInterceptor : Decrypt field for 'nickname', Ciphertext: IgaLfu2eBut5jAKENLZd3A==, Plaintext: 蒋震南 308 | 2022-12-20 17:45:12.535 DEBUG 15634 --- [nio-8080-exec-1] w.m.e.i.DefaultMybatisEncryptInterceptor : Decrypt field for 'nickname', Ciphertext: IgaLfu2eBut5jAKENLZd3A==, Plaintext: 蒋震南 309 | 2022-12-20 17:45:12.535 DEBUG 15634 --- [nio-8080-exec-1] w.m.e.i.DefaultMybatisEncryptInterceptor : Decrypt field for 'nickname', Ciphertext: IgaLfu2eBut5jAKENLZd3A==, Plaintext: 蒋震南 310 | Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4b849667] 311 | ``` 312 | 313 | SQL 314 | 315 | ```sql 316 | SELECT member_id,open_id,nickname,is_enable,balance,birthday,status,deleted,registrar_date,accelerate_begin_time,accelerate_end_time,update_time FROM dtt_member LIMIT 10; 317 | ``` 318 | 319 | Finally, you can get some results like this: 320 | 321 | ```json 322 | { 323 | "pageNum": 1, 324 | "pageSize": 10, 325 | "total": 6, 326 | "pages": 1, 327 | "list": [ 328 | { 329 | "memberId": 1, 330 | "openId": "fawezOE5sT", 331 | "nickname": "蒋震南", 332 | "isEnable": true, 333 | "balance": 865.0000, 334 | "birthday": "2022-12-20T13:33:46.547", 335 | "status": 0, 336 | "deleted": 1, 337 | "registrarDate": "2022-12-20", 338 | "accelerateBeginTime": "13:33:47", 339 | "accelerateEndTime": "13:33:47", 340 | "updateTime": "2022-12-20T13:33:46.547" 341 | }, 342 | { 343 | "memberId": 2, 344 | "openId": "fawezOE5sT", 345 | "nickname": "蒋震南", 346 | "isEnable": true, 347 | "balance": 865.0000, 348 | "birthday": "2022-12-20T13:33:49.226", 349 | "status": 0, 350 | "deleted": 1, 351 | "registrarDate": "2022-12-20", 352 | "accelerateBeginTime": "13:33:49", 353 | "accelerateEndTime": "13:33:49", 354 | "updateTime": "2022-12-20T13:33:49.226" 355 | }, 356 | { 357 | "memberId": 3, 358 | "openId": "fawezOE5sT", 359 | "nickname": "蒋震南", 360 | "isEnable": true, 361 | "balance": 865.0000, 362 | "birthday": "2022-12-20T13:33:50.398", 363 | "status": 0, 364 | "deleted": 1, 365 | "registrarDate": "2022-12-20", 366 | "accelerateBeginTime": "13:33:50", 367 | "accelerateEndTime": "13:33:50", 368 | "updateTime": "2022-12-20T13:33:50.398" 369 | }, 370 | { 371 | "memberId": 4, 372 | "openId": "fawezOE5sT", 373 | "nickname": "蒋震南", 374 | "isEnable": true, 375 | "balance": 865.0000, 376 | "birthday": "2022-12-20T13:33:51.319", 377 | "status": 0, 378 | "deleted": 1, 379 | "registrarDate": "2022-12-20", 380 | "accelerateBeginTime": "13:33:51", 381 | "accelerateEndTime": "13:33:51", 382 | "updateTime": "2022-12-20T13:33:51.319" 383 | }, 384 | { 385 | "memberId": 5, 386 | "openId": "fawezOE5sT", 387 | "nickname": "蒋震南", 388 | "isEnable": true, 389 | "balance": 865.0000, 390 | "birthday": "2022-12-20T13:33:52.31", 391 | "status": 0, 392 | "deleted": 1, 393 | "registrarDate": "2022-12-20", 394 | "accelerateBeginTime": "13:33:52", 395 | "accelerateEndTime": "13:33:52", 396 | "updateTime": "2022-12-20T13:33:52.31" 397 | }, 398 | { 399 | "memberId": 6, 400 | "openId": "fawezOE5sT", 401 | "nickname": "蒋震南", 402 | "isEnable": true, 403 | "balance": 865.0000, 404 | "birthday": "2022-12-20T17:30:27.558", 405 | "status": 0, 406 | "deleted": 1, 407 | "registrarDate": "2022-12-20", 408 | "accelerateBeginTime": "17:30:28", 409 | "accelerateEndTime": "17:30:28", 410 | "updateTime": "2022-12-20T17:30:27.558" 411 | } 412 | ] 413 | } 414 | ``` 415 | 416 | 417 | 418 | # Q & A 419 | 420 | ## 1 How can I use some encrypted fields as query criteria? 421 | 422 | **Exclude `LIKE` SQL grammar** 423 | 424 | - You can use this `API` [`EncryptStrategy#convert`](https://github.com/Weasley-J/mybatis-encrypt-spring-boot-parent/blob/main/mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/core/EncryptStrategy.java#L29) to convert your plain bean as a cipher bean (Only converts the field annotated by annotation [`@Encryption`](https://github.com/Weasley-J/mybatis-encrypt-spring-boot-parent/blob/8500f7454d/mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/annotation/Encryption.java)), [Here is an Example that you can reference](https://github.com/Weasley-J/mybatis-encrypt-spring-boot-parent/blob/350b08c2b6/mybatis-encrypt-spring-boot-tests/src/test/java/com/example/EncryptionTestsAppTests.java#L101). 425 | 426 | -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | SETTINGS="/Users/weasley/Development/program/apache-maven/conf/settings-sonatype.xml" 4 | MODULE="mybatis-encrypt-spring-boot-starter" 5 | 6 | clear && 7 | mvn clean deploy -pl :$MODULE -am --settings $SETTINGS && 8 | mvn clean 9 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-starter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.7.6 9 | 10 | 11 | 12 | io.github.weasley-j 13 | mybatis-encrypt-spring-boot-starter 14 | 1.0.3 15 | mybatis-encrypt-spring-boot-starter 16 | A spring-boot starter to make it easy to encrypt and decrypt some column of database tables, supports 17 | for 18 | user custom encryption algorithms, you can even use some encrypted fields as query criteria. 19 | 20 | https://github.com/Weasley-J/mybatis-encrypt-spring-boot-parent 21 | 22 | 23 | 24 | GNU GENERAL PUBLIC LICENSE, Version 3 25 | https://github.com/Weasley-J/mybatis-encrypt-spring-boot-parent/blob/main/LICENSE 26 | repo 27 | 28 | 29 | 30 | 31 | 32 | Weasley J 33 | 1432689025@qq.com 34 | https://github.com/Weasley-J 35 | 36 | 37 | 38 | 39 | https://github.com/Weasley-J/mybatis-encrypt-spring-boot-parent 40 | https://github.com/Weasley-J/mybatis-encrypt-spring-boot-parent.git 41 | https://github.com/Weasley-J/mybatis-encrypt-spring-boot-parent 42 | 43 | 44 | 45 | UTF-8 46 | UTF-8 47 | UTF-8 48 | 3.5.11 49 | 2.0 50 | 51 | 3.9.1.2184 52 | 1.6.13 53 | 3.10.1 54 | 3.4.1 55 | 3.2.1 56 | 3.0.1 57 | 58 | 59 | 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-starter 64 | 65 | 66 | org.springframework.boot 67 | spring-boot-starter-test 68 | test 69 | 70 | 71 | org.springframework.boot 72 | spring-boot-autoconfigure-processor 73 | true 74 | 75 | 76 | org.springframework.boot 77 | spring-boot-configuration-processor 78 | true 79 | 80 | 81 | org.projectlombok 82 | lombok 83 | true 84 | 85 | 86 | commons-codec 87 | commons-codec 88 | 89 | 90 | org.apache.commons 91 | commons-lang3 92 | 93 | 94 | org.slf4j 95 | slf4j-api 96 | 97 | 98 | org.mybatis 99 | mybatis 100 | ${mybatis.version} 101 | 102 | 103 | 104 | 105 | 106 | ossrh 107 | https://s01.oss.sonatype.org/content/repositories/snapshots 108 | 109 | 110 | ossrh 111 | https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/ 112 | 113 | 114 | 115 | 116 | ${project.artifactId} 117 | 118 | 119 | src/main/resources 120 | 121 | **/* 122 | 123 | 124 | 125 | 126 | 127 | org.sonarsource.scanner.maven 128 | sonar-maven-plugin 129 | ${sonar-maven-plugin.version} 130 | 131 | 132 | org.sonatype.plugins 133 | nexus-staging-maven-plugin 134 | ${nexus-staging.version} 135 | true 136 | 137 | ossrh 138 | https://s01.oss.sonatype.org/ 139 | true 140 | 141 | 142 | 143 | org.apache.maven.plugins 144 | maven-surefire-plugin 145 | 146 | true 147 | 148 | 149 | 150 | org.apache.maven.plugins 151 | maven-source-plugin 152 | 153 | 154 | attach-sources 155 | package 156 | 157 | jar-no-fork 158 | 159 | 160 | 161 | 162 | 163 | org.apache.maven.plugins 164 | maven-javadoc-plugin 165 | ${maven-javadoc.version} 166 | 167 | private 168 | true 169 | UTF-8 170 | UTF-8 171 | UTF-8 172 | 173 | -Xdoclint:none 174 | 175 | 176 | 177 | date 178 | o 179 | Ignore 'date' tag rule 180 | 181 | 182 | apiNote 183 | o 184 | Ignore 'apiNote' tag rule 185 | 186 | 187 | implNote 188 | o 189 | Ignore 'implNote' tag rule 190 | 191 | 192 | 193 | 194 | 195 | attach-javadoc 196 | compile 197 | 198 | jar 199 | 200 | 201 | 202 | 203 | 204 | org.apache.maven.plugins 205 | maven-gpg-plugin 206 | ${maven-gpg.version} 207 | 208 | 209 | sign-artifacts 210 | verify 211 | 212 | sign 213 | 214 | 215 | 216 | 217 | 218 | org.apache.maven.plugins 219 | maven-compiler-plugin 220 | ${maven-compiler-plugin.version} 221 | 222 | 8 223 | 8 224 | 225 | 226 | 227 | 228 | 229 | 230 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/annotation/EnableMybatisEncryption.java: -------------------------------------------------------------------------------- 1 | package io.github.weasleyj.mybatis.encrypt.annotation; 2 | 3 | import io.github.weasleyj.mybatis.encrypt.config.MybatisEncryptConfigurer; 4 | import io.github.weasleyj.mybatis.encrypt.core.DefaultAesEncryptStrategyImpl; 5 | import io.github.weasleyj.mybatis.encrypt.core.DefaultBase64EncryptStrategyImpl; 6 | import io.github.weasleyj.mybatis.encrypt.interceptor.DefaultMybatisEncryptInterceptor; 7 | import org.springframework.context.annotation.Import; 8 | 9 | import java.lang.annotation.Documented; 10 | import java.lang.annotation.ElementType; 11 | import java.lang.annotation.Inherited; 12 | import java.lang.annotation.Retention; 13 | import java.lang.annotation.RetentionPolicy; 14 | import java.lang.annotation.Target; 15 | 16 | /** 17 | * To Enable autoconfiguration for Mybatis Encryption 18 | * 19 | * @author weasley 20 | * @version 1.0.0 21 | */ 22 | @Inherited 23 | @Documented 24 | @Target(ElementType.TYPE) 25 | @Retention(RetentionPolicy.RUNTIME) 26 | @Import({MybatisEncryptConfigurer.class, DefaultMybatisEncryptInterceptor.class, DefaultAesEncryptStrategyImpl.class, DefaultBase64EncryptStrategyImpl.class,}) 27 | public @interface EnableMybatisEncryption { 28 | } 29 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/annotation/Encryption.java: -------------------------------------------------------------------------------- 1 | package io.github.weasleyj.mybatis.encrypt.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Inherited; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | 10 | /** 11 | * To annotate a field for encrypt and decrypt 12 | * 13 | * @author weasley 14 | * @version 1.0.0 15 | */ 16 | @Inherited 17 | @Documented 18 | @Target(ElementType.FIELD) 19 | @Retention(RetentionPolicy.RUNTIME) 20 | public @interface Encryption { 21 | } 22 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/config/MybatisEncryptConfigurer.java: -------------------------------------------------------------------------------- 1 | package io.github.weasleyj.mybatis.encrypt.config; 2 | 3 | import io.github.weasleyj.mybatis.encrypt.annotation.EnableMybatisEncryption; 4 | import io.github.weasleyj.mybatis.encrypt.constant.EncryptType; 5 | import io.github.weasleyj.mybatis.encrypt.core.DefaultAesEncryptStrategyImpl; 6 | import io.github.weasleyj.mybatis.encrypt.core.DefaultBase64EncryptStrategyImpl; 7 | import io.github.weasleyj.mybatis.encrypt.core.EncryptStrategy; 8 | import io.github.weasleyj.mybatis.encrypt.interceptor.DefaultMybatisEncryptInterceptor; 9 | import lombok.Getter; 10 | import org.apache.ibatis.session.SqlSessionFactory; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.beans.factory.InitializingBean; 14 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 15 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 16 | import org.springframework.boot.context.properties.ConfigurationPropertiesScan; 17 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 18 | import org.springframework.context.annotation.Lazy; 19 | import org.springframework.objenesis.instantiator.util.ClassUtils; 20 | import org.springframework.stereotype.Component; 21 | 22 | import java.util.List; 23 | import java.util.Map; 24 | import java.util.concurrent.ConcurrentHashMap; 25 | 26 | import static io.github.weasleyj.mybatis.encrypt.config.MybatisEncryptProperties.AesProperties; 27 | import static io.github.weasleyj.mybatis.encrypt.config.MybatisEncryptProperties.DiyProperties; 28 | import static io.github.weasleyj.mybatis.encrypt.constant.EncryptType.AES; 29 | import static io.github.weasleyj.mybatis.encrypt.constant.EncryptType.BASE64; 30 | import static io.github.weasleyj.mybatis.encrypt.constant.EncryptType.DIY; 31 | 32 | /** 33 | * Mybatis Encrypt Configuration 34 | * 35 | * @author weasley 36 | * @version 1.0.0 37 | */ 38 | @Getter 39 | @Component 40 | @Lazy(value = false) 41 | @ConditionalOnClass({SqlSessionFactory.class}) 42 | @ConditionalOnBean(annotation = {EnableMybatisEncryption.class}) 43 | @ConfigurationPropertiesScan(basePackages = {"io.github.weasleyj.mybatis.encrypt.config"}) 44 | @EnableConfigurationProperties({MybatisEncryptProperties.class, AesProperties.class, DiyProperties.class}) 45 | public class MybatisEncryptConfigurer implements InitializingBean { 46 | /** 47 | * The clients of encrypt strategies 48 | */ 49 | public static final Map STRATEGY_CLIENTS = new ConcurrentHashMap<>(6); 50 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 51 | private final DiyProperties diyProperties; 52 | private final AesProperties aesProperties; 53 | /** 54 | * The list of 'SqlSessionFactory' 55 | */ 56 | private final List sqlSessionFactories; 57 | private final DefaultMybatisEncryptInterceptor defaultMybatisEncryptInterceptor; 58 | 59 | public MybatisEncryptConfigurer(DiyProperties diyProperties, 60 | AesProperties aesProperties, 61 | List sqlSessionFactories, 62 | DefaultMybatisEncryptInterceptor defaultMybatisEncryptInterceptor) { 63 | this.diyProperties = diyProperties; 64 | this.aesProperties = aesProperties; 65 | this.sqlSessionFactories = sqlSessionFactories; 66 | this.defaultMybatisEncryptInterceptor = defaultMybatisEncryptInterceptor; 67 | } 68 | 69 | @Override 70 | public void afterPropertiesSet() throws Exception { 71 | sqlSessionFactories.forEach(sqlSessionFactory -> { 72 | org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration(); 73 | if (null != configuration && !configuration.getInterceptors().contains(defaultMybatisEncryptInterceptor)) { 74 | configuration.addInterceptor(defaultMybatisEncryptInterceptor); 75 | } 76 | }); 77 | if (null != diyProperties.getEncryptStrategy()) { 78 | STRATEGY_CLIENTS.put(DIY, ClassUtils.newInstance(diyProperties.getEncryptStrategy())); 79 | } 80 | STRATEGY_CLIENTS.put(BASE64, new DefaultBase64EncryptStrategyImpl()); 81 | STRATEGY_CLIENTS.put(AES, new DefaultAesEncryptStrategyImpl(aesProperties)); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/config/MybatisEncryptProperties.java: -------------------------------------------------------------------------------- 1 | package io.github.weasleyj.mybatis.encrypt.config; 2 | 3 | import io.github.weasleyj.mybatis.encrypt.constant.EncryptType; 4 | import io.github.weasleyj.mybatis.encrypt.core.EncryptStrategy; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | import lombok.experimental.Accessors; 9 | import org.springframework.boot.context.properties.ConfigurationProperties; 10 | 11 | import static io.github.weasleyj.mybatis.encrypt.config.MybatisEncryptProperties.PREFIX; 12 | import static io.github.weasleyj.mybatis.encrypt.constant.EncryptType.BASE64; 13 | 14 | /** 15 | * Mybatis Encrypt Properties 16 | */ 17 | @Data 18 | @NoArgsConstructor 19 | @AllArgsConstructor 20 | @Accessors(chain = true) 21 | @ConfigurationProperties(prefix = PREFIX) 22 | public class MybatisEncryptProperties { 23 | /** 24 | * The prefix of configuration properties 25 | */ 26 | public static final String PREFIX = "mybatis.encrypt"; 27 | /** 28 | * enable encryption for mybatis 29 | */ 30 | private Boolean enable = true; 31 | /** 32 | * The type of encryption. 33 | * 34 | * @see EncryptType 35 | */ 36 | private EncryptType encryptType = BASE64; 37 | 38 | /** 39 | * The configuration properties of AES 40 | */ 41 | @Data 42 | @NoArgsConstructor 43 | @AllArgsConstructor 44 | @Accessors(chain = true) 45 | @ConfigurationProperties(prefix = PREFIX + ".aes") 46 | public static class AesProperties { 47 | /** 48 | * The secret key for AES encrypt, the length must be 16. 49 | */ 50 | private String key; 51 | /** 52 | * The offset for secretKey, the length must be 16. 53 | */ 54 | private String keyIv; 55 | 56 | public String getKeyIv() { 57 | if (keyIv.length() != 16) { 58 | throw new IllegalArgumentException("The length of keyIv must be 16: " + keyIv); 59 | } 60 | return keyIv; 61 | } 62 | 63 | public String getKey() { 64 | if (key.length() != 16) { 65 | throw new IllegalArgumentException("secret-key length must be 16: " + key); 66 | } 67 | return key; 68 | } 69 | } 70 | 71 | /** 72 | * The configuration properties of user DIY encrypt strategy 73 | */ 74 | @Data 75 | @NoArgsConstructor 76 | @AllArgsConstructor 77 | @Accessors(chain = true) 78 | @ConfigurationProperties(prefix = PREFIX + ".diy") 79 | public static class DiyProperties { 80 | /** 81 | * Developer defines encryption and decryption policies 82 | */ 83 | private Class encryptStrategy = null; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/constant/EncryptConstant.java: -------------------------------------------------------------------------------- 1 | package io.github.weasleyj.mybatis.encrypt.constant; 2 | 3 | import java.math.BigDecimal; 4 | import java.util.*; 5 | 6 | /** 7 | * The encryption constant 8 | * 9 | * @author weasley 10 | * @version 1.0.0 11 | */ 12 | public interface EncryptConstant { 13 | /** 14 | * SQL start with insert 15 | */ 16 | String INSERT = "INSERT"; 17 | /** 18 | * SQL start with update 19 | */ 20 | String UPDATE = "UPDATE"; 21 | /** 22 | * SQL start with select 23 | */ 24 | String SELECT = "SELECT"; 25 | 26 | /** 27 | * UNDERLYING_DATA_TYPES 28 | */ 29 | @SuppressWarnings({"all"}) 30 | Set> UNDERLYING_DATA_TYPES = new HashSet>() {{ 31 | add(String.class); 32 | add(Boolean.class); 33 | add(Short.class); 34 | add(Double.class); 35 | add(Integer.class); 36 | add(Long.class); 37 | add(BigDecimal.class); 38 | add(List.class); 39 | add(ArrayList.class); 40 | add(Collection.class); 41 | add(Map.class); 42 | add(HashMap.class); 43 | add(LinkedHashMap.class); 44 | add(Object.class); 45 | }}; 46 | } 47 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/constant/EncryptType.java: -------------------------------------------------------------------------------- 1 | package io.github.weasleyj.mybatis.encrypt.constant; 2 | 3 | import io.github.weasleyj.mybatis.encrypt.config.MybatisEncryptProperties; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Getter; 6 | 7 | /** 8 | * The encryption type 9 | * 10 | * @author weasley 11 | * @version 1.0.0 12 | */ 13 | @Getter 14 | @AllArgsConstructor 15 | public enum EncryptType implements EncryptConstant { 16 | /** 17 | * Use AES for encryption and decryption 18 | * 19 | * @see MybatisEncryptProperties.AesProperties 20 | */ 21 | AES, 22 | /** 23 | * Use BASE64 for encryption and decryption 24 | */ 25 | BASE64, 26 | /** 27 | * User defined encrypt strategy 28 | * 29 | * @see MybatisEncryptProperties.DiyProperties 30 | */ 31 | DIY 32 | } 33 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/core/DefaultAesEncryptStrategyImpl.java: -------------------------------------------------------------------------------- 1 | package io.github.weasleyj.mybatis.encrypt.core; 2 | 3 | import io.github.weasleyj.mybatis.encrypt.annotation.EnableMybatisEncryption; 4 | import io.github.weasleyj.mybatis.encrypt.exception.MybatisEncryptException; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 8 | import org.springframework.stereotype.Component; 9 | import org.springframework.util.Assert; 10 | 11 | import javax.crypto.Cipher; 12 | import javax.crypto.SecretKey; 13 | import javax.crypto.spec.IvParameterSpec; 14 | import javax.crypto.spec.SecretKeySpec; 15 | import java.nio.charset.StandardCharsets; 16 | import java.util.Base64; 17 | 18 | import static io.github.weasleyj.mybatis.encrypt.config.MybatisEncryptProperties.AesProperties; 19 | 20 | /** 21 | * The default AES encrypt strategy implementation 22 | * 23 | * @author weasley 24 | * @version 1.0.0 25 | */ 26 | @Component 27 | @ConditionalOnBean(annotation = {EnableMybatisEncryption.class}) 28 | public class DefaultAesEncryptStrategyImpl implements EncryptStrategy { 29 | private static final String KEY_ALGORITHM = "AES"; 30 | private static final String CIPHER_ALGORITHM = "AES/CBC/NoPadding"; 31 | protected final Logger logger = LoggerFactory.getLogger(this.getClass()); 32 | /** 33 | * The configuration properties of AES 34 | */ 35 | private final AesProperties aesProperties; 36 | 37 | public DefaultAesEncryptStrategyImpl(AesProperties aesProperties) { 38 | this.aesProperties = aesProperties; 39 | } 40 | 41 | @Override 42 | public String encrypt(Object plaintext) { 43 | Assert.notNull(plaintext, "Plaintext cannot be null"); 44 | try { 45 | SecretKey secretKey = new SecretKeySpec(aesProperties.getKey().getBytes(StandardCharsets.UTF_8), KEY_ALGORITHM); 46 | Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); 47 | @SuppressWarnings({"all"}) IvParameterSpec ivSpec = new IvParameterSpec(aesProperties.getKeyIv().getBytes(StandardCharsets.UTF_8)); 48 | int blockSize = cipher.getBlockSize(); 49 | byte[] dataBytes = String.valueOf(plaintext).getBytes(StandardCharsets.UTF_8); 50 | int dataByteLength = dataBytes.length; 51 | if (dataByteLength % blockSize != 0) { 52 | dataByteLength = dataByteLength + (blockSize - (dataByteLength % blockSize)); 53 | } 54 | byte[] newPlaintext = new byte[dataByteLength]; 55 | System.arraycopy(dataBytes, 0, newPlaintext, 0, dataBytes.length); 56 | cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); 57 | byte[] encrypted = cipher.doFinal(newPlaintext); 58 | String encoded = Base64.getEncoder().encodeToString(encrypted); 59 | if (logger.isDebugEnabled()) { 60 | logger.debug("plaintext: {}, ciphertext: {}", plaintext, encoded); 61 | } 62 | return encoded; 63 | } catch (Exception e) { 64 | throw new MybatisEncryptException("AES encrypt exception:", e); 65 | } 66 | } 67 | 68 | @Override 69 | public String decrypt(Object ciphertext) { 70 | Assert.notNull(ciphertext, "Ciphertext cannot be null"); 71 | try { 72 | byte[] decodeFromBase64 = Base64.getDecoder().decode(String.valueOf(ciphertext)); 73 | Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); 74 | SecretKey secretKey = new SecretKeySpec(aesProperties.getKey().getBytes(StandardCharsets.UTF_8), KEY_ALGORITHM); 75 | @SuppressWarnings({"all"}) IvParameterSpec ivSpec = new IvParameterSpec(aesProperties.getKeyIv().getBytes(StandardCharsets.UTF_8)); 76 | cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec); 77 | byte[] originalBytes = cipher.doFinal(decodeFromBase64); 78 | String decrypted = new String(originalBytes, StandardCharsets.UTF_8).trim(); 79 | if (logger.isDebugEnabled()) { 80 | logger.debug("ciphertext: {}, plaintext: {}", ciphertext, decrypted); 81 | } 82 | return decrypted; 83 | } catch (Exception e) { 84 | throw new MybatisEncryptException("AES decrypt exception:", e); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/core/DefaultBase64EncryptStrategyImpl.java: -------------------------------------------------------------------------------- 1 | package io.github.weasleyj.mybatis.encrypt.core; 2 | 3 | import io.github.weasleyj.mybatis.encrypt.annotation.EnableMybatisEncryption; 4 | import org.apache.commons.codec.binary.Base64; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 8 | import org.springframework.stereotype.Component; 9 | import org.springframework.util.Assert; 10 | 11 | import java.nio.charset.StandardCharsets; 12 | 13 | /** 14 | * The default base64 encrypt strategy implementation 15 | * 16 | * @author weasley 17 | * @version 1.0.0 18 | */ 19 | @Component 20 | @ConditionalOnBean(annotation = {EnableMybatisEncryption.class}) 21 | public class DefaultBase64EncryptStrategyImpl implements EncryptStrategy { 22 | protected final Logger logger = LoggerFactory.getLogger(this.getClass()); 23 | 24 | @Override 25 | public String encrypt(Object plaintext) { 26 | Assert.notNull(plaintext, "Plaintext cannot be null"); 27 | return Base64.encodeBase64String(String.valueOf(plaintext).getBytes(StandardCharsets.UTF_8)); 28 | } 29 | 30 | @Override 31 | public String decrypt(Object ciphertext) { 32 | Assert.notNull(ciphertext, "Ciphertext cannot be null"); 33 | return new String(Base64.decodeBase64(String.valueOf(ciphertext)), StandardCharsets.UTF_8); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/core/EncryptStrategy.java: -------------------------------------------------------------------------------- 1 | package io.github.weasleyj.mybatis.encrypt.core; 2 | 3 | import io.github.weasleyj.mybatis.encrypt.annotation.Encryption; 4 | import io.github.weasleyj.mybatis.encrypt.constant.EncryptType; 5 | import io.github.weasleyj.mybatis.encrypt.exception.MybatisEncryptException; 6 | import org.apache.commons.lang3.reflect.FieldUtils; 7 | import org.springframework.util.Assert; 8 | import org.springframework.util.CollectionUtils; 9 | 10 | import java.lang.reflect.Field; 11 | import java.util.List; 12 | 13 | import static io.github.weasleyj.mybatis.encrypt.config.MybatisEncryptConfigurer.STRATEGY_CLIENTS; 14 | 15 | /** 16 | * The interface for encrypt strategy 17 | * 18 | * @author weasley 19 | * @version 1.0.0 20 | */ 21 | public interface EncryptStrategy { 22 | /** 23 | * When using encrypted fields as query fields, you may need to encrypt plaintext fields before they can be recognized by the database as query parameters 24 | * 25 | * @param plainBean The bean to encrypt its fields to ciphertext which annotated by {@link Encryption} 26 | * @param The type of raw bean 27 | * @return The bean with fields encrypt to ciphertext 28 | */ 29 | static E convert(E plainBean, EncryptType encryptType) { 30 | Assert.notNull(plainBean, "Plain bean must be not null"); 31 | Assert.notNull(encryptType, "Encrypt type must be not null"); 32 | if (plainBean.getClass() == Object.class) return plainBean; 33 | List encryptionFields = FieldUtils.getFieldsListWithAnnotation(plainBean.getClass(), Encryption.class); 34 | if (CollectionUtils.isEmpty(encryptionFields)) return plainBean; 35 | EncryptStrategy encryptStrategy = STRATEGY_CLIENTS.get(encryptType); 36 | if (null == encryptStrategy) return plainBean; 37 | for (Field field : encryptionFields) { 38 | try { 39 | Object plaintextFieldValue = FieldUtils.readField(field, plainBean, true); 40 | if (null == plaintextFieldValue) continue; 41 | String encrypt = encryptStrategy.encrypt(plaintextFieldValue); 42 | FieldUtils.writeField(field, plainBean, encrypt, true); 43 | } catch (IllegalAccessException e) { 44 | throw new MybatisEncryptException("Covert plain bean to cipher bean error:", e); 45 | } 46 | } 47 | return plainBean; 48 | } 49 | 50 | /** 51 | * To encrypt a raw text that human-readable 52 | * 53 | * @param plaintext The raw text 54 | * @return The encrypted text 55 | */ 56 | default String encrypt(Object plaintext) { 57 | return null; 58 | } 59 | 60 | /** 61 | * To decrypt an encrypted text that human-unreadable 62 | * 63 | * @param ciphertext The encrypted text to decrypt 64 | * @return The decrypted text that human-readable 65 | */ 66 | default String decrypt(Object ciphertext) { 67 | return null; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/exception/MybatisEncryptException.java: -------------------------------------------------------------------------------- 1 | package io.github.weasleyj.mybatis.encrypt.exception; 2 | 3 | /** 4 | * Mybatis encrypt exception 5 | * 6 | * @author weasley 7 | * @version 1.0.0 8 | */ 9 | public class MybatisEncryptException extends RuntimeException { 10 | /** 11 | * The code for mybatis encrypt exception 12 | */ 13 | private int code = 10089; 14 | /** 15 | * The message for mybatis encrypt exception 16 | */ 17 | private String message; 18 | 19 | 20 | public MybatisEncryptException() { 21 | super(); 22 | } 23 | 24 | public MybatisEncryptException(String message) { 25 | super(message); 26 | } 27 | 28 | public MybatisEncryptException(Integer code, String message) { 29 | this.code = code; 30 | this.message = message; 31 | } 32 | 33 | public MybatisEncryptException(String message, Throwable cause) { 34 | super(message, cause); 35 | } 36 | 37 | @Override 38 | public String getMessage() { 39 | return message; 40 | } 41 | 42 | public void setMessage(String message) { 43 | this.message = message; 44 | } 45 | 46 | public Integer getCode() { 47 | return code; 48 | } 49 | 50 | public void setCode(Integer code) { 51 | this.code = code; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-starter/src/main/java/io/github/weasleyj/mybatis/encrypt/interceptor/DefaultMybatisEncryptInterceptor.java: -------------------------------------------------------------------------------- 1 | package io.github.weasleyj.mybatis.encrypt.interceptor; 2 | 3 | import io.github.weasleyj.mybatis.encrypt.annotation.EnableMybatisEncryption; 4 | import io.github.weasleyj.mybatis.encrypt.annotation.Encryption; 5 | import io.github.weasleyj.mybatis.encrypt.config.MybatisEncryptProperties; 6 | import io.github.weasleyj.mybatis.encrypt.core.EncryptStrategy; 7 | import org.apache.commons.lang3.reflect.FieldUtils; 8 | import org.apache.ibatis.cache.CacheKey; 9 | import org.apache.ibatis.executor.Executor; 10 | import org.apache.ibatis.executor.statement.StatementHandler; 11 | import org.apache.ibatis.mapping.BoundSql; 12 | import org.apache.ibatis.mapping.MappedStatement; 13 | import org.apache.ibatis.plugin.Interceptor; 14 | import org.apache.ibatis.plugin.Intercepts; 15 | import org.apache.ibatis.plugin.Invocation; 16 | import org.apache.ibatis.plugin.Signature; 17 | import org.apache.ibatis.session.ResultHandler; 18 | import org.apache.ibatis.session.RowBounds; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 22 | import org.springframework.stereotype.Component; 23 | import org.springframework.util.CollectionUtils; 24 | 25 | import java.lang.reflect.Field; 26 | import java.lang.reflect.InvocationTargetException; 27 | import java.sql.Connection; 28 | import java.util.Collection; 29 | import java.util.List; 30 | import java.util.Map; 31 | 32 | import static io.github.weasleyj.mybatis.encrypt.config.MybatisEncryptConfigurer.STRATEGY_CLIENTS; 33 | 34 | /** 35 | * Default mybatis encrypt interceptor 36 | * 37 | * @author weasley 38 | * @version 1.0.0 39 | */ 40 | @Component 41 | @ConditionalOnBean(annotation = {EnableMybatisEncryption.class}) 42 | @Intercepts(value = { 43 | @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}), 44 | @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}), 45 | @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), 46 | @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}), 47 | }) 48 | public class DefaultMybatisEncryptInterceptor implements Interceptor { 49 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 50 | private final MybatisEncryptProperties mybatisEncryptProperties; 51 | 52 | public DefaultMybatisEncryptInterceptor(MybatisEncryptProperties mybatisEncryptProperties) { 53 | this.mybatisEncryptProperties = mybatisEncryptProperties; 54 | } 55 | 56 | @Override 57 | public Object intercept(Invocation invocation) throws Throwable { 58 | if (Boolean.FALSE.equals(mybatisEncryptProperties.getEnable())) return invocation.proceed(); 59 | 60 | Object[] args = invocation.getArgs(); 61 | Object target = invocation.getTarget(); 62 | Executor executor = target instanceof Executor ? ((Executor) target) : null; 63 | StatementHandler statementHandler = target instanceof StatementHandler ? ((StatementHandler) target) : null; 64 | MappedStatement ms = args[0] instanceof MappedStatement ? ((MappedStatement) args[0]) : null; 65 | 66 | if (null != ms) { 67 | switch (ms.getSqlCommandType()) { 68 | case INSERT: 69 | case UPDATE: 70 | this.processInsertOrUpdateCommandType(invocation); 71 | break; 72 | case SELECT: 73 | return this.processSelectCommandType(invocation); 74 | default: 75 | break; 76 | } 77 | } 78 | 79 | return invocation.proceed(); 80 | } 81 | 82 | /** 83 | * Process insert or update sql command type 84 | * 85 | * @param invocation The invocation of mybatis 86 | * @throws IllegalAccessException The illegal access exception 87 | */ 88 | public void processInsertOrUpdateCommandType(Invocation invocation) throws IllegalAccessException { 89 | Object parameter = invocation.getArgs()[1]; 90 | Class clazz = parameter.getClass(); 91 | if (clazz != Object.class) { 92 | List encryptFields = FieldUtils.getFieldsListWithAnnotation(clazz, Encryption.class); 93 | if (CollectionUtils.isEmpty(encryptFields)) return; 94 | for (Field field : encryptFields) { 95 | Object plaintextFieldValue = FieldUtils.readField(field, parameter, true); 96 | if (null == plaintextFieldValue) continue; 97 | String encrypt = this.deduceEncryptStrategy().encrypt(plaintextFieldValue); 98 | FieldUtils.writeField(field, parameter, encrypt, true); 99 | if (logger.isDebugEnabled()) { 100 | logger.debug("Encrypt field for '{}', Plaintext: {}, Ciphertext: {}", field.getName(), plaintextFieldValue, encrypt); 101 | } 102 | } 103 | } 104 | } 105 | 106 | /** 107 | * Process elect sql command type 108 | * 109 | * @param invocation The invocation of mybatis 110 | * @return The result of proceed 111 | * @throws IllegalAccessException The illegal access exception 112 | * @throws InvocationTargetException The invocation target exception 113 | */ 114 | public Object processSelectCommandType(Invocation invocation) throws IllegalAccessException, InvocationTargetException { 115 | Object proceed = invocation.proceed(); 116 | if (proceed instanceof Collection) { 117 | Collection proceedResults = (Collection) proceed; 118 | if (CollectionUtils.isEmpty(proceedResults)) return proceed; 119 | for (Object obj : proceedResults) { 120 | if (null == obj) continue; 121 | List decryptFields = FieldUtils.getFieldsListWithAnnotation(obj.getClass(), Encryption.class); 122 | if (!CollectionUtils.isEmpty(decryptFields)) { 123 | for (Field field : decryptFields) { 124 | Object ciphertextFieldValue = FieldUtils.readField(field, obj, true); 125 | if (null == ciphertextFieldValue) continue; 126 | String decrypt = this.deduceEncryptStrategy().decrypt(ciphertextFieldValue); 127 | FieldUtils.writeField(field, obj, decrypt, true); 128 | if (logger.isDebugEnabled()) { 129 | logger.debug("Decrypt field for '{}', Ciphertext: {}, Plaintext: {}", field.getName(), ciphertextFieldValue, decrypt); 130 | } 131 | } 132 | } 133 | } 134 | } 135 | if (proceed instanceof Map) { 136 | Map map = (Map) proceed; 137 | } 138 | return proceed; 139 | } 140 | 141 | /** 142 | * Deduce encrypt strategy client 143 | * 144 | * @return The instance of {@link EncryptStrategy} 145 | */ 146 | public EncryptStrategy deduceEncryptStrategy() { 147 | return STRATEGY_CLIENTS.get(mybatisEncryptProperties.getEncryptType()); 148 | } 149 | 150 | } 151 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-starter/src/test/java/io/github/weasleyj/mybatis/encrypt/core/DefaultAesEncryptStrategyImplTest.java: -------------------------------------------------------------------------------- 1 | package io.github.weasleyj.mybatis.encrypt.core; 2 | 3 | import io.github.weasleyj.mybatis.encrypt.config.MybatisEncryptProperties; 4 | import org.junit.jupiter.api.Test; 5 | 6 | class DefaultAesEncryptStrategyImplTest { 7 | 8 | static EncryptStrategy encryptStrategy = new DefaultAesEncryptStrategyImpl( 9 | new MybatisEncryptProperties.AesProperties() 10 | .setKey("Jidkdp1mWL1tRyK=") 11 | .setKeyIv("Jidkdp1mWL1jijK=") 12 | ); 13 | 14 | String raw = "这是一个AES的加密解密测试!Abc123,!@#$%^&*()_+,!@#¥%%……&*()"; 15 | 16 | @Test 17 | void testEncrypt() { 18 | System.out.println(encryptStrategy.encrypt(raw)); 19 | } 20 | 21 | @Test 22 | void testDecrypt() { 23 | String encrypt = encryptStrategy.encrypt(raw); 24 | System.out.println(encryptStrategy.decrypt(encrypt)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-starter/src/test/java/io/github/weasleyj/mybatis/encrypt/core/DefaultBase64EncryptStrategyImplTest.java: -------------------------------------------------------------------------------- 1 | package io.github.weasleyj.mybatis.encrypt.core; 2 | 3 | import org.apache.commons.codec.binary.Base64; 4 | import org.junit.jupiter.api.DisplayName; 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.util.Assert; 7 | import org.springframework.util.Base64Utils; 8 | 9 | import java.nio.charset.StandardCharsets; 10 | 11 | class DefaultBase64EncryptStrategyImplTest { 12 | 13 | static EncryptStrategy encryptStrategy = new DefaultBase64EncryptStrategyImpl(); 14 | 15 | String raw = "这是一个Base64的加密解密测试!Abc123,!@#$%^&*()_+,!@#¥%%……&*()"; 16 | 17 | @Test 18 | void encrypt() { 19 | String encrypt = encryptStrategy.encrypt(raw); 20 | System.out.println("encrypt = " + encrypt); 21 | } 22 | 23 | @Test 24 | void decrypt() { 25 | String encrypt = encryptStrategy.encrypt(raw); 26 | String decrypt = encryptStrategy.decrypt(encrypt); 27 | System.out.println(decrypt); 28 | Assert.isTrue(raw.equals(decrypt), "解密后的明文由于原始内容一致"); 29 | } 30 | 31 | public String encrypt(Object plaintext) { 32 | Assert.notNull(plaintext, "Plaintext cannot be null"); 33 | return Base64Utils.encodeToString(String.valueOf(plaintext).getBytes(StandardCharsets.UTF_8)); 34 | } 35 | 36 | 37 | public String decrypt(Object ciphertext) { 38 | Assert.notNull(ciphertext, "Ciphertext cannot be null"); 39 | return new String(Base64Utils.decodeFromString(String.valueOf(ciphertext)), StandardCharsets.UTF_8); 40 | } 41 | 42 | @Test 43 | @DisplayName("encoded1 == encoded2") 44 | void func1() { 45 | String encoded1 = encrypt(raw); 46 | String encoded2 = Base64.encodeBase64String(raw.getBytes(StandardCharsets.UTF_8)); 47 | Assert.isTrue(encoded1.equals(encoded2), "encoded1 == encoded2"); 48 | } 49 | 50 | @Test 51 | @DisplayName("decoded1 == decoded2") 52 | void func2() { 53 | String encoded1 = encrypt(raw); 54 | String encoded2 = Base64.encodeBase64String(raw.getBytes(StandardCharsets.UTF_8)); 55 | Assert.isTrue(encoded1.equals(encoded2), "encoded1 == encoded2"); 56 | 57 | String decrypt1 = decrypt(encoded1); 58 | String decrypt2 = new String(Base64.decodeBase64(encoded2)); 59 | Assert.isTrue(decrypt1.equals(decrypt2), "decrypt1 == decrypt2"); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/h2.mv.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/julxxy/mybatis-encrypt-spring-boot-parent/2b99ff3e855e48ffdbbafd111f18ad183db85e9a/mybatis-encrypt-spring-boot-tests/h2.mv.db -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.7.6 9 | 10 | 11 | 12 | com.example 13 | mybatis-encrypt-spring-boot-tests 14 | 1.0.0-SNAPSHOT 15 | mybatis-encrypt-spring-boot-tests 16 | mybatis-encrypt-spring-boot-tests 17 | 18 | 19 | 1.8 20 | 21 | 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-validation 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-configuration-processor 34 | true 35 | 36 | 37 | org.projectlombok 38 | lombok 39 | true 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-starter-test 44 | test 45 | 46 | 47 | 48 | 49 | io.github.weasley-j 50 | mybatis-encrypt-spring-boot-starter 51 | 1.0.3 52 | 53 | 54 | 55 | io.github.weasley-j 56 | dtt-spring-boot-starter 57 | 1.3.9 58 | 59 | 60 | com.github.therapi 61 | therapi-runtime-javadoc-scribe 62 | 0.15.0 63 | provided 64 | 65 | 66 | 67 | 68 | com.baomidou 69 | mybatis-plus-boot-starter 70 | 3.5.2 71 | 72 | 73 | 74 | 75 | org.mybatis.spring.boot 76 | mybatis-spring-boot-starter 77 | 3.0.0 78 | 79 | 80 | 81 | 82 | com.github.pagehelper 83 | pagehelper-spring-boot-starter 84 | 1.4.6 85 | 86 | 87 | 88 | 89 | tk.mybatis 90 | mapper-spring-boot-starter 91 | 4.2.2 92 | 93 | 94 | 95 | 96 | com.oracle.database.jdbc 97 | ojdbc8 98 | runtime 99 | 100 | 101 | 102 | mysql 103 | mysql-connector-java 104 | 8.0.30 105 | runtime 106 | 107 | 108 | com.h2database 109 | h2 110 | runtime 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | org.springframework.boot 120 | spring-boot-maven-plugin 121 | 122 | 123 | 124 | org.projectlombok 125 | lombok 126 | 127 | 128 | 129 | 130 | 131 | org.apache.maven.plugins 132 | maven-surefire-plugin 133 | 134 | true 135 | 136 | 137 | 138 | 139 | 140 | 141 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/java/com/example/MybatisEncryptTestsApp.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import cn.alphahub.dtt.plus.framework.annotations.EnableDtt; 4 | import io.github.weasleyj.mybatis.encrypt.annotation.EnableMybatisEncryption; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | 8 | /** 9 | * Mybatis encrypt main class of Tests 10 | */ 11 | 12 | @EnableDtt(scanBasePackages = {"com.example.demain"}) 13 | @SpringBootApplication 14 | @EnableMybatisEncryption 15 | public class MybatisEncryptTestsApp { 16 | 17 | public static void main(String[] args) { 18 | SpringApplication.run(MybatisEncryptTestsApp.class, args); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/java/com/example/common/config/Jackson2ObjectMapperConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.common.config; 2 | 3 | import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; 4 | import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; 5 | import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer; 6 | import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; 7 | import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; 8 | import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | 14 | import java.time.LocalDate; 15 | import java.time.LocalDateTime; 16 | import java.time.LocalTime; 17 | import java.time.format.DateTimeFormatter; 18 | import java.util.TimeZone; 19 | 20 | /** 21 | * Spring Boot中LocalDateTime日期格式处理 22 | * 23 | * @author liuwenjing 24 | */ 25 | @Configuration 26 | public class Jackson2ObjectMapperConfig { 27 | /** 28 | * 日期时间格式,没有在yml里面配置默认采用: yyyy-MM-dd HH:mm:ss 29 | */ 30 | @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}") 31 | private String pattern; 32 | /** 33 | * 时区,没有在yml里面配置默认采用: GMT+8 34 | */ 35 | @Value("${spring.jackson.time-zone:GMT+8}") 36 | private String timeZone; 37 | 38 | /** 39 | * @return Jackson2ObjectMapperBuilderCustomizer 40 | */ 41 | @Bean 42 | public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { 43 | return builder -> { 44 | builder.serializerByType(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss"))); 45 | builder.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); 46 | builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern))); 47 | 48 | builder.deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss"))); 49 | builder.deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); 50 | builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern))); 51 | 52 | builder.simpleDateFormat(pattern); 53 | builder.timeZone(TimeZone.getTimeZone(timeZone)); 54 | }; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/java/com/example/common/page/PageHandler.java: -------------------------------------------------------------------------------- 1 | package com.example.common.page; 2 | 3 | import com.github.pagehelper.Page; 4 | 5 | import java.util.List; 6 | import java.util.Objects; 7 | 8 | /** 9 | * 分页工具类 10 | *

11 | * 分页示例 12 | *

13 |  * import cn.com.winning.common.basic.share.domain.ApiHisLog;
14 |  * import cn.com.winning.common.basic.share.service.ApiHisLogService;
15 |  * import cn.com.winning.common.entity.PageParam;
16 |  * import cn.com.winning.common.page.PageHandler;
17 |  * import cn.com.winning.common.page.PageWrapper;
18 |  * import cn.hutool.json.JSONUtil;
19 |  * import com.github.pagehelper.Page;
20 |  * import com.github.pagehelper.page.PageMethod;
21 |  * import lombok.extern.slf4j.Slf4j;
22 |  * import org.springframework.beans.factory.annotation.Autowired;
23 |  * import org.springframework.stereotype.Service;
24 |  *
25 |  * import java.util.List;
26 |  *
27 |  * {@code @Slf4j}
28 |  * {@code @Service}
29 |  * public class HisLogPageDemoService {
30 |  *
31 |  * {@code @Autowired}
32 |  * private ApiHisLogService apiHisLogService;
33 |  *
34 |  * public PageWrapper{@code } pages(PageParam pageParam) {
35 |  *     log.info("分页入参 {}", JSONUtil.toJsonPrettyStr(pageParam));
36 |  *     Page{@code } page = PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize());
37 |  *     List{@code } apiHisLogs = apiHisLogService.list();
38 |  *     PageWrapper{@code } render = PageHandler.render(page, apiHisLogs);
39 |  *     log.info("分页数据 {}", JSONUtil.toJsonPrettyStr(render));
40 |  *     return render;
41 |  *   }
42 |  * }
43 |  * 
44 | */ 45 | public final class PageHandler { 46 | 47 | private PageHandler() { 48 | } 49 | 50 | public static PageWrapper render(Page page, List list) { 51 | PageWrapper pageWrapper = new PageWrapper<>(); 52 | if (null != page) { 53 | pageWrapper.setPageNum(page.getPageNum()); 54 | pageWrapper.setPageSize(page.getPageSize()); 55 | pageWrapper.setTotal(page.getTotal()); 56 | pageWrapper.setPages(page.getPages()); 57 | pageWrapper.setList(list); 58 | } 59 | return pageWrapper; 60 | } 61 | 62 | public static PageWrapper render(int pageNum, int pageSize, long total, List list) { 63 | PageWrapper pageWrapper = new PageWrapper<>(); 64 | pageWrapper.setPageNum(pageNum); 65 | pageWrapper.setPageSize(pageSize); 66 | pageWrapper.setTotal(total); 67 | if (pageSize > 0) { 68 | pageWrapper.setPages((int) (total / (long) pageSize + (long) (total % (long) pageSize == 0L ? 0 : 1))); 69 | } else { 70 | pageWrapper.setPages(0); 71 | } 72 | 73 | pageWrapper.setList(list); 74 | return pageWrapper; 75 | } 76 | 77 | public static , T> R render(Page page, List list, R result) { 78 | if (Objects.nonNull(page)) { 79 | result.setPageNum(page.getPageNum()); 80 | result.setPageSize(page.getPageSize()); 81 | result.setTotal(page.getTotal()); 82 | result.setPages(page.getPages()); 83 | result.setList(list); 84 | } 85 | return result; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/java/com/example/common/page/PageWrapper.java: -------------------------------------------------------------------------------- 1 | package com.example.common.page; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | import java.io.Serializable; 8 | import java.util.List; 9 | 10 | /** 11 | * 分页返回对象 12 | * 13 | * @author weasley 14 | * @version 1.0 15 | * @date 2022/6/29 16 | */ 17 | @Data 18 | @AllArgsConstructor 19 | @NoArgsConstructor 20 | public class PageWrapper implements Serializable { 21 | /** 22 | * 当前页码 23 | */ 24 | private int pageNum; 25 | /** 26 | * 页大小 27 | */ 28 | private int pageSize; 29 | /** 30 | * 总记录数 31 | */ 32 | private long total; 33 | /** 34 | * 总页数 35 | */ 36 | private int pages; 37 | /** 38 | * 列表实体数据 39 | */ 40 | private List list; 41 | 42 | /** 43 | * 获取空的初始化 44 | * 45 | * @param pageNum 46 | * @param pageSize 47 | * @param 48 | * @return 49 | */ 50 | public static PageWrapper instance(int pageNum, int pageSize) { 51 | PageWrapper wrapper = new PageWrapper<>(); 52 | wrapper.setPageSize(pageSize); 53 | wrapper.setPageNum(pageNum); 54 | return wrapper; 55 | } 56 | 57 | /** 58 | * 判断当前页是否还有数据,用于优化减少查询list 59 | * 60 | * @return 61 | */ 62 | public boolean hadData() { 63 | return (long) (pageNum - 1) * pageSize < total; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/java/com/example/controller/MemberController.java: -------------------------------------------------------------------------------- 1 | package com.example.controller; 2 | 3 | import cn.alphahub.dtt.plus.util.JacksonUtil; 4 | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; 5 | import com.baomidou.mybatisplus.core.toolkit.Wrappers; 6 | import com.baomidou.mybatisplus.extension.plugins.pagination.Page; 7 | import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO; 8 | import com.example.common.page.PageHandler; 9 | import com.example.common.page.PageWrapper; 10 | import com.example.demain.DttMember; 11 | import com.example.service.MemberService; 12 | import com.github.pagehelper.page.PageMethod; 13 | import io.github.weasleyj.mybatis.encrypt.config.MybatisEncryptProperties; 14 | import io.github.weasleyj.mybatis.encrypt.core.EncryptStrategy; 15 | import lombok.extern.slf4j.Slf4j; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.http.ResponseEntity; 18 | import org.springframework.transaction.annotation.Transactional; 19 | import org.springframework.validation.annotation.Validated; 20 | import org.springframework.web.bind.annotation.*; 21 | 22 | import java.time.LocalDate; 23 | import java.time.LocalDateTime; 24 | import java.time.LocalTime; 25 | import java.util.Arrays; 26 | import java.util.List; 27 | 28 | /** 29 | * 用户信息 30 | * 31 | * @author Weasley 32 | */ 33 | @Slf4j 34 | @RestController 35 | @RequestMapping("/api/member") 36 | public class MemberController { 37 | 38 | @Autowired 39 | private MemberService memberService; 40 | @Autowired 41 | private MybatisEncryptProperties mybatisEncryptProperties; 42 | 43 | /** 44 | * 用户信息分页查询(Pagehelper写法) 45 | * 46 | * @param member 用户信息查询参数 47 | * @param pageNum 前页码, 默认: 1 48 | * @param pageSize 每页显示条数,默认: 10 49 | * @return 用户信息分页数据 50 | * @apiNote 请求示例: 请求示例 51 | * @see 多数据源分页推荐使用pagehelper 52 | * @see pagehelper多数据源分页配置 53 | * @see PageWrapper类源码 54 | * @see PageHandler类源码 55 | */ 56 | @GetMapping("/page/pagehelper") 57 | public ResponseEntity> pageByPagehelper(@RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum, 58 | @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize, 59 | @ModelAttribute(value = "member", binding = true) DttMember member) { 60 | com.github.pagehelper.Page page = PageMethod.startPage(pageNum, pageSize); 61 | List pageResults = memberService.list(Wrappers.lambdaQuery(member)); 62 | return ResponseEntity.ok(PageHandler.render(page, pageResults)); 63 | } 64 | 65 | /** 66 | * 用户信息分页查询(Mybatis-Plus写法) 67 | * 68 | * @param pageParam 分页参数: current(当前页码,默认1), size(每页显示条数,默认10) 69 | * @param member 用户信息查询参数 70 | * @return 用户信息分页数据 71 | * @apiNote 请求示例: 请求示例 72 | * @see Mybatis Plus官方分页插件配置示例 73 | * @see 多数据源分页推荐使用pagehelper 74 | */ 75 | @GetMapping("/page/mmp") 76 | public ResponseEntity> pageByMmp(@ModelAttribute("pageParam") PageDTO pageParam, @ModelAttribute("member") DttMember member) { 77 | Page params = new Page<>(); 78 | params.setSize(pageParam.getSize()); 79 | params.setCurrent(pageParam.getCurrent()); 80 | Page page = memberService.page(params, Wrappers.lambdaQuery(member)); 81 | return ResponseEntity.ok(page); 82 | } 83 | 84 | /** 85 | * Use encrypted fields as query criteria 86 | */ 87 | @GetMapping("/lis/encrypted/fields") 88 | public ResponseEntity> selectByEncryptedFields(@ModelAttribute("member") DttMember member) { 89 | log.info("{}", JacksonUtil.toPrettyJson(member)); 90 | DttMember dttMember = EncryptStrategy.convert(member, mybatisEncryptProperties.getEncryptType()); 91 | log.info("EncryptStrategy.convert {}", JacksonUtil.toPrettyJson(dttMember)); 92 | List members = this.memberService.list(Wrappers.lambdaQuery(DttMember.class) 93 | .eq(DttMember::getNickname, dttMember.getNickname())); 94 | return ResponseEntity.ok(members); 95 | } 96 | 97 | /** 98 | * 获取用户信息详情 99 | * 100 | * @param memberId 用户信息主键id 101 | * @return 用户信息详细信息 102 | */ 103 | @GetMapping("/info/{memberId}") 104 | public ResponseEntity info(@PathVariable("memberId") Long memberId) { 105 | DttMember member = memberService.getById(memberId); 106 | return ResponseEntity.ok(member); 107 | } 108 | 109 | /** 110 | * 新增用户信息 111 | * 112 | * @param member 用户信息元数据 113 | * @return 成功返回true, 失败返回false 114 | */ 115 | @PostMapping("/save") 116 | @Transactional(rollbackFor = {Exception.class}) 117 | public ResponseEntity save(@RequestBody @Validated DttMember member) { 118 | boolean save = memberService.save(member); 119 | return ResponseEntity.ok(save); 120 | } 121 | 122 | /** 123 | * 新增用户信息 124 | * 125 | * @return 成功返回true, 失败返回false 126 | */ 127 | @PostMapping("/save/direct") 128 | @Transactional(rollbackFor = {Exception.class}) 129 | public ResponseEntity saveNoParams() { 130 | String json = "{\n" + 131 | " \"openId\": \"fawezOE5sT\",\n" + 132 | " \"nickname\": \"蒋震南\",\n" + 133 | " \"isEnable\": true,\n" + 134 | " \"balance\": 865,\n" + 135 | " \"birthday\": \"2022-08-19 22:18:51\",\n" + 136 | " \"status\": 0,\n" + 137 | " \"deleted\": 1\n" + 138 | "}"; 139 | DttMember member = JacksonUtil.readValue(json, DttMember.class); 140 | member.setBirthday(LocalDateTime.now()); 141 | member.setRegistrarDate(LocalDate.now()); 142 | member.setUpdateTime(LocalDateTime.now()); 143 | member.setAccelerateBeginTime(LocalTime.now()); 144 | member.setAccelerateEndTime(LocalTime.now()); 145 | DttMember dttMember = memberService.getOne(new QueryWrapper().select("MAX(member_id) memberId")); 146 | if (null != dttMember) { 147 | member.setMemberId(dttMember.getMemberId() + 1); 148 | } else member.setMemberId(1L); 149 | log.info("{}", JacksonUtil.toJson(member)); 150 | boolean save = memberService.save(member); 151 | return ResponseEntity.ok(save); 152 | } 153 | 154 | /** 155 | * 修改用户信息 156 | * 157 | * @param member 用户信息, 根据id选择性更新 158 | * @return 成功返回true, 失败返回false 159 | */ 160 | @PutMapping("/update") 161 | @Transactional(rollbackFor = {Exception.class}) 162 | public ResponseEntity update(@RequestBody @Validated DttMember member) { 163 | boolean update = memberService.updateById(member); 164 | return ResponseEntity.ok(update); 165 | } 166 | 167 | /** 168 | * 批量删除用户信息 169 | * 170 | * @param memberIds 用户信息id集合 171 | * @return 成功返回true, 失败返回false 172 | */ 173 | @DeleteMapping("/delete/{memberIds}") 174 | @Transactional(rollbackFor = {Exception.class}) 175 | public ResponseEntity delete(@PathVariable("memberIds") Long[] memberIds) { 176 | boolean delete = memberService.removeByIds(Arrays.asList(memberIds)); 177 | return ResponseEntity.ok(delete); 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/java/com/example/demain/DttMember.java: -------------------------------------------------------------------------------- 1 | package com.example.demain; 2 | 3 | import com.baomidou.mybatisplus.annotation.TableId; 4 | import io.github.weasleyj.mybatis.encrypt.annotation.Encryption; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Builder; 7 | import lombok.Data; 8 | import lombok.NoArgsConstructor; 9 | import lombok.experimental.Accessors; 10 | 11 | import java.io.Serializable; 12 | import java.math.BigDecimal; 13 | import java.time.LocalDate; 14 | import java.time.LocalDateTime; 15 | import java.time.LocalTime; 16 | 17 | /** 18 | * 用户信息 19 | */ 20 | @Data 21 | @Builder 22 | @AllArgsConstructor 23 | @NoArgsConstructor 24 | @Accessors(chain = true) 25 | public class DttMember implements Serializable { 26 | /** 27 | * 主键id 28 | * 29 | * @primaryKey 30 | */ 31 | @TableId 32 | private Long memberId; 33 | /** 34 | * 用户openId 35 | * 36 | * @defaultValue e1be63305 37 | * @length 16 38 | */ 39 | private String openId; 40 | /** 41 | * 用户昵称 42 | * 43 | * @length 32 44 | */ 45 | @Encryption 46 | private String nickname; 47 | /** 48 | * 是否启用, 默认:1 49 | * 50 | * @defaultValue true 51 | */ 52 | private Boolean isEnable; 53 | /** 54 | * 用户积分余额, 默认:0.00 55 | * 56 | * @precision 10 57 | * @scale 4 58 | * @defaultValue 0.01 59 | */ 60 | private BigDecimal balance; 61 | /** 62 | * 出生日期,格式:yyyy-MM-dd HH:mm:ss 63 | */ 64 | private LocalDateTime birthday; 65 | /** 66 | * 用户状态;0 正常(默认),1 已冻结,2 账号已封,3 账号异常 67 | * 68 | * @defaultValue 3 69 | */ 70 | private Integer status; 71 | /** 72 | * 账户注销状态;0 未注销(默认),1 已销户 73 | * 74 | * @defaultValue 1 75 | * @dbDataType SMALLINT 76 | */ 77 | private Integer deleted; 78 | /** 79 | * 注册时间,格式: yyyy-MM-dd 80 | */ 81 | private LocalDate registrarDate; 82 | /** 83 | * 会员加速开始时间, 格式:HH:mm:ss 84 | */ 85 | private LocalTime accelerateBeginTime; 86 | /** 87 | * 会员加速结束时间, 格式:HH:mm:ss 88 | */ 89 | private LocalTime accelerateEndTime; 90 | /** 91 | * 修改时间 92 | */ 93 | private LocalDateTime updateTime; 94 | } 95 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/java/com/example/mapper/MemberMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.mapper; 2 | 3 | import com.baomidou.mybatisplus.core.mapper.BaseMapper; 4 | import com.example.demain.DttMember; 5 | import org.apache.ibatis.annotations.Mapper; 6 | 7 | /** 8 | * The mybatis mapper interface of 用户信息 9 | */ 10 | @Mapper 11 | public interface MemberMapper extends BaseMapper { 12 | 13 | } 14 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/java/com/example/service/MemberService.java: -------------------------------------------------------------------------------- 1 | package com.example.service; 2 | 3 | import com.baomidou.mybatisplus.extension.service.IService; 4 | import com.example.demain.DttMember; 5 | 6 | /** 7 | * 用户信息Service接口 8 | */ 9 | public interface MemberService extends IService { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/java/com/example/service/impl/MemberServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.service.impl; 2 | 3 | import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; 4 | import com.example.demain.DttMember; 5 | import com.example.mapper.MemberMapper; 6 | import com.example.service.MemberService; 7 | import org.springframework.stereotype.Service; 8 | 9 | /** 10 | * 用户信息Service实现 11 | */ 12 | @Service 13 | public class MemberServiceImpl extends ServiceImpl implements MemberService { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/resources/application-h2.yml: -------------------------------------------------------------------------------- 1 | logging: 2 | level: 3 | #cn.alphahub.dtt.plus.framework.core.template.DefaultTemplateResolver: debug 4 | org.springframework.jdbc.core.JdbcTemplate: debug 5 | jdbc.sqltiming: debug 6 | 7 | spring: 8 | datasource: 9 | embedded-database-connection: h2 10 | driver-class-name: org.h2.Driver 11 | #url: jdbc:h2:mem:h2;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE 12 | url: jdbc:h2:/Users/weasley/Development/IdeaProjects/mybatis-encrypt-spring-boot-parent/mybatis-encrypt-spring-boot-tests/h2;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE 13 | username: "" 14 | password: "" 15 | 16 | h2: 17 | console: 18 | path: /h2 19 | enabled: true 20 | settings: 21 | web-allow-others: false 22 | web-admin-password: 123456 23 | 24 | mybatis-plus: 25 | mapper-locations: classpath:mapper/**/*Mapper.xml,mapper/**/*Dao.xml 26 | type-aliases-package: com.example.domain 27 | global-config: 28 | db-config: 29 | id-type: auto 30 | configuration: 31 | map-underscore-to-camel-case: true 32 | log-impl: org.apache.ibatis.logging.stdout.StdOutImpl 33 | 34 | 35 | alphahub: 36 | dtt: 37 | show-sql: on 38 | all-in-one-table: 39 | enable: true 40 | filename: all_in_one.sql 41 | filepath: /Users/weasley/Downloads 42 | code-generator: 43 | is-enable: on 44 | include-controller: on 45 | include-interface: on 46 | override-exists: off 47 | remove-prefix: dtt 48 | base-classes: 49 | - com.example.demain.DttMember 50 | module-name: example 51 | module-package: com.example 52 | module-path: /Users/weasley/Development/IdeaProjects/mybatis-encrypt-spring-boot-parent/mybatis-encrypt-spring-boot-tests 53 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/resources/application-mysql.yml: -------------------------------------------------------------------------------- 1 | logging: 2 | level: 3 | org.springframework.jdbc.core.JdbcTemplate: debug 4 | jdbc.sqltiming: debug 5 | 6 | spring: 7 | datasource: 8 | driver-class-name: com.mysql.cj.jdbc.Driver 9 | url: jdbc:mysql://192.168.31.23:3306/db_demo?serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true&autoReconnect=true&allowMultiQueries=true 10 | username: root 11 | password: 123456 12 | 13 | mybatis-plus: 14 | mapper-locations: classpath:mapper/**/*Mapper.xml,mapper/**/*Dao.xml 15 | type-aliases-package: com.example.domain.dtt,com.example.domain.order 16 | global-config: 17 | db-config: 18 | id-type: auto 19 | configuration: 20 | map-underscore-to-camel-case: true 21 | log-impl: org.apache.ibatis.logging.stdout.StdOutImpl 22 | 23 | 24 | # mybatis encryption configuration 25 | mybatis: 26 | encrypt: 27 | enable: on 28 | encrypt-type: aes 29 | aes: 30 | key: Jidkdp1mWL1tRyK= 31 | key-iv: Poikdp1mWL1jijK= 32 | 33 | alphahub: 34 | dtt: 35 | is-enable: on 36 | banner-mode: ON 37 | show-sql: off 38 | mybatis-orm-support: 39 | is-enable: on 40 | all-in-one-table: 41 | enable: true 42 | filename: AllInOne.sql 43 | filepath: /Users/weasley/Downloads 44 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/resources/application-oracle.yml: -------------------------------------------------------------------------------- 1 | logging: 2 | level: 3 | #cn.alphahub.dtt.plus.framework.core.template.DefaultTemplateResolver: debug 4 | org.springframework.jdbc.core.JdbcTemplate: debug 5 | jdbc.sqltiming: debug 6 | 7 | spring: 8 | datasource: 9 | driver-class-name: oracle.jdbc.OracleDriver 10 | #driver-class-name: oracle.jdbc.driver.OracleDriver 11 | url: jdbc:oracle:thin:@//192.168.31.23:1521/lwj 12 | username: C##DTT 13 | password: 123456 14 | 15 | mybatis-plus: 16 | mapper-locations: classpath:mapper/**/*Mapper.xml,mapper/**/*Dao.xml 17 | type-aliases-package: com.example.domain.dtt,com.example.domain.order 18 | global-config: 19 | db-config: 20 | id-type: auto 21 | configuration: 22 | map-underscore-to-camel-case: true 23 | log-impl: org.apache.ibatis.logging.stdout.StdOutImpl 24 | 25 | 26 | # mybatis encryption configuration 27 | mybatis: 28 | encrypt: 29 | enable: on 30 | encrypt-type: aes 31 | aes: 32 | key: Jidkdp1mWL1tRyK= 33 | key-iv: Poikdp1mWL1jijK= 34 | 35 | alphahub: 36 | dtt: 37 | show-sql: on 38 | all-in-one-table: 39 | enable: true 40 | filename: AllInOne.sql 41 | filepath: /Users/weasley/Downloads 42 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | logging: 2 | level: 3 | io.github.weasleyj.mybatis.encrypt.interceptor.DefaultMybatisEncryptInterceptor: debug 4 | 5 | server: 6 | port: 8080 7 | 8 | spring: 9 | application: 10 | name: mybatis-encrypt-spring-boot-tests 11 | 12 | profiles: 13 | active: h2 14 | 15 | jackson: 16 | date-format: yyyy-MM-dd HH:mm:ss 17 | time-zone: GMT+8 18 | locale: zh_CN 19 | 20 | mvc: 21 | format: 22 | date-time: yyyy-MM-dd HH:mm:ss 23 | date: yyyy-MM-dd 24 | time: HH:mm:ss 25 | 26 | # mybatis encryption configuration 27 | mybatis: 28 | encrypt: 29 | enable: on 30 | encrypt-type: aes 31 | aes: 32 | key: Jidkdp1mWL1tRyK= 33 | key-iv: Poikdp1mWL1jijK= 34 | 35 | # PageHelper 36 | pagehelper: 37 | reasonable: true 38 | support-methods-arguments: true 39 | params: count=countSql 40 | auto-dialect: true 41 | auto-runtime-dialect: true 42 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/resources/mapper/example/MemberMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/main/resources/member.json: -------------------------------------------------------------------------------- 1 | { 2 | "pageNum": 1, 3 | "pageSize": 10, 4 | "total": 5, 5 | "pages": 1, 6 | "list": [ 7 | { 8 | "memberId": 1, 9 | "openId": "fawezOE5sT", 10 | "nickname": "蒋震南", 11 | "isEnable": true, 12 | "balance": 865.0000, 13 | "birthday": "2022-12-20 01:58:00", 14 | "status": 0, 15 | "deleted": 1, 16 | "registrarDate": "2022-12-20", 17 | "accelerateBeginTime": "01:58:01", 18 | "accelerateEndTime": "01:58:01", 19 | "updateTime": "2022-12-20 01:58:00" 20 | }, 21 | { 22 | "memberId": 2, 23 | "openId": "fawezOE5sT", 24 | "nickname": "蒋震南", 25 | "isEnable": true, 26 | "balance": 865.0000, 27 | "birthday": "2022-12-20 02:00:03", 28 | "status": 0, 29 | "deleted": 1, 30 | "registrarDate": "2022-12-20", 31 | "accelerateBeginTime": "02:00:03", 32 | "accelerateEndTime": "02:00:03", 33 | "updateTime": "2022-12-20 02:00:03" 34 | }, 35 | { 36 | "memberId": 3, 37 | "openId": "fawezOE5sT", 38 | "nickname": "蒋震南", 39 | "isEnable": true, 40 | "balance": 865.0000, 41 | "birthday": "2022-12-20 02:00:04", 42 | "status": 0, 43 | "deleted": 1, 44 | "registrarDate": "2022-12-20", 45 | "accelerateBeginTime": "02:00:04", 46 | "accelerateEndTime": "02:00:04", 47 | "updateTime": "2022-12-20 02:00:04" 48 | }, 49 | { 50 | "memberId": 4, 51 | "openId": "fawezOE5sT", 52 | "nickname": "蒋震南", 53 | "isEnable": true, 54 | "balance": 865.0000, 55 | "birthday": "2022-12-20 02:00:04", 56 | "status": 0, 57 | "deleted": 1, 58 | "registrarDate": "2022-12-20", 59 | "accelerateBeginTime": "02:00:05", 60 | "accelerateEndTime": "02:00:05", 61 | "updateTime": "2022-12-20 02:00:04" 62 | }, 63 | { 64 | "memberId": 5, 65 | "openId": "fawezOE5sT", 66 | "nickname": "蒋震南", 67 | "isEnable": true, 68 | "balance": 865.0000, 69 | "birthday": "2022-12-20 02:00:06", 70 | "status": 0, 71 | "deleted": 1, 72 | "registrarDate": "2022-12-20", 73 | "accelerateBeginTime": "02:00:06", 74 | "accelerateEndTime": "02:00:06", 75 | "updateTime": "2022-12-20 02:00:06" 76 | } 77 | ] 78 | } 79 | -------------------------------------------------------------------------------- /mybatis-encrypt-spring-boot-tests/src/test/java/com/example/EncryptionTestsAppTests.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import cn.alphahub.dtt.plus.util.JacksonUtil; 4 | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; 5 | import com.baomidou.mybatisplus.core.toolkit.Wrappers; 6 | import com.example.common.page.PageWrapper; 7 | import com.example.demain.DttMember; 8 | import com.example.service.MemberService; 9 | import com.fasterxml.jackson.core.type.TypeReference; 10 | import io.github.weasleyj.mybatis.encrypt.config.MybatisEncryptProperties; 11 | import io.github.weasleyj.mybatis.encrypt.core.EncryptStrategy; 12 | import lombok.extern.slf4j.Slf4j; 13 | import org.apache.commons.io.IOUtils; 14 | import org.apache.commons.lang3.RandomStringUtils; 15 | import org.junit.jupiter.api.Test; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.boot.test.context.SpringBootTest; 18 | import org.springframework.util.Assert; 19 | 20 | import java.io.IOException; 21 | import java.nio.charset.StandardCharsets; 22 | import java.util.ArrayList; 23 | import java.util.List; 24 | 25 | @Slf4j 26 | @SpringBootTest 27 | class EncryptionTestsAppTests { 28 | 29 | @Autowired 30 | private MemberService memberService; 31 | @Autowired 32 | private MybatisEncryptProperties mybatisEncryptProperties; 33 | 34 | @Test 35 | void contextLoads() { 36 | } 37 | 38 | @Test 39 | void testBatchInsert() throws IOException { 40 | String resource = IOUtils.resourceToString("member.json", StandardCharsets.UTF_8, Thread.currentThread().getContextClassLoader()); 41 | PageWrapper pageWrapper = JacksonUtil.readValue(resource, new TypeReference>() { 42 | }); 43 | 44 | List list = pageWrapper.getList(); 45 | List insertList = new ArrayList<>(); 46 | int i = 1000; 47 | Long id = null; 48 | 49 | DttMember one = memberService.getOne(new QueryWrapper().select("MAX(member_id) memberId")); 50 | if (null != one) { 51 | id = one.getMemberId(); 52 | } else id = 1L; 53 | 54 | for (DttMember dttMember : list) { 55 | i += 1; 56 | id += 1; 57 | dttMember.setOpenId(RandomStringUtils.randomAlphanumeric(16)); 58 | dttMember.setMemberId(id + 1); 59 | dttMember.setNickname(dttMember.getNickname() + i); 60 | insertList.add(dttMember); 61 | } 62 | 63 | boolean batch = memberService.saveBatch(insertList); 64 | Assert.isTrue(batch); 65 | } 66 | 67 | @Test 68 | void testUpdateSingle() { 69 | DttMember member = JacksonUtil.readValue("{\n" + 70 | " \"memberId\": 3,\n" + 71 | " \"openId\": \"fawezOE5sT\",\n" + 72 | " \"nickname\": \"蒋震南1001\",\n" + 73 | " \"isEnable\": true,\n" + 74 | " \"balance\": 865.0000,\n" + 75 | " \"birthday\": \"2022-12-20 01:58:00\",\n" + 76 | " \"status\": 0,\n" + 77 | " \"deleted\": 1,\n" + 78 | " \"registrarDate\": \"2022-12-20\",\n" + 79 | " \"accelerateBeginTime\": \"01:58:01\",\n" + 80 | " \"accelerateEndTime\": \"01:58:01\",\n" + 81 | " \"updateTime\": \"2022-12-20 01:58:00\"\n" + 82 | " }", DttMember.class); 83 | member.setOpenId(RandomStringUtils.randomAlphanumeric(16)); 84 | boolean update = this.memberService.update(member, Wrappers.lambdaUpdate(DttMember.class) 85 | .eq(DttMember::getMemberId, 3) 86 | ); 87 | Assert.isTrue(update, "update must be success"); 88 | 89 | boolean update2 = this.memberService.update(null, Wrappers.lambdaUpdate(DttMember.class) 90 | .eq(DttMember::getMemberId, 3) 91 | .set(DttMember::getIsEnable, false) 92 | ); 93 | Assert.isTrue(update2, "update must be success"); 94 | } 95 | 96 | 97 | /** 98 | * Use an encrypted field to query for data 99 | */ 100 | @Test 101 | void testSelectByEncryptedFields() { 102 | DttMember member = new DttMember().setNickname("蒋震南1005"); 103 | log.info("before {}", JacksonUtil.toJson(member)); 104 | DttMember dttMember = EncryptStrategy.convert(member, mybatisEncryptProperties.getEncryptType()); 105 | log.info("after {}", JacksonUtil.toJson(member)); 106 | List members = this.memberService.list(Wrappers.lambdaQuery(DttMember.class) 107 | .eq(DttMember::getNickname, dttMember.getNickname())); 108 | log.info("select by encrypt filed: {}", JacksonUtil.toJson(members)); 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.7.6 9 | 10 | 11 | 12 | io.github.weasley-j 13 | mybatis-encrypt-spring-boot-parent 14 | 1.0.0 15 | mybatis-encrypt-spring-boot-parent 16 | mybatis-encrypt-spring-boot-parent 17 | pom 18 | 19 | 20 | mybatis-encrypt-spring-boot-starter 21 | mybatis-encrypt-spring-boot-tests 22 | 23 | 24 | 25 | --------------------------------------------------------------------------------