Field Encryption and Decryption
The
@FieldEncryptannotation provides field-level encryption and decryption, supporting multiple algorithms such asMD5,BASE64,AES,RSA, etc.
@FieldEncrypt
- Data encryption and decryption annotation
algorithm(): Encryption type, default is Base64findDecrypt(): Whether to decrypt when querying. If set to false, no decryption occurs on querykey(): Symmetric encryption key, takes priority over global configurationprivateKey(): Private key for asymmetric encryption, takes priority over global configurationpublicKey(): Public key for asymmetric encryption, takes priority over global configurationencryptor(): Custom encryptor, must implementcom.mongoplus.encryptor.Encryptor
AlgorithmEnum Encryption Types
| Algorithm | Description |
|---|---|
| MD5_32 | 32-bit MD5 algorithm |
| MD5_16 | 16-bit MD5 algorithm |
| BASE64 | Base64 encoding algorithm |
| AES | AES symmetric algorithm |
| RSA | Asymmetric encryption algorithm |
| SM2 | Chinese SM2 asymmetric encryption based on ECC |
| SM3 | Chinese SM3 message digest algorithm (like MD5) |
| SM4 | Chinese SM4 symmetric algorithm, WLAN standard block cipher |
| PBEWithMD5AndDES | Hybrid algorithm |
| PBEWithMD5AndTripleDES | Hybrid algorithm |
| PBEWithSHA1AndDESede | Hybrid algorithm |
| PBEWithSHA1AndRC2_40 | Hybrid algorithm |
Warning
Do not transmit QueryChainWrapper over RPC calls.
- MD5 is irreversible; both stored and queried values are ciphertext.
- SM2, SM3, SM4 require the BouncyCastle library.
Required dependency for SM2, SM3, SM4
xml
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<version>1.78.1</version>
</dependency>GenerateKeyUtil Key Generation Utility
java
public static void main(String[] args) {
try {
// Generate AES key
String aesKey = GenerateKeyUtil.generateAESKey("123456");
// Generate RSA key pair
MutablePair<String, String> rsaKey = GenerateKeyUtil.generateRSAKey();
// Generate SM2 key pair
MutablePair<String, String> sm2Key = GenerateKeyUtil.generateSM2Key();
// Generate SM4 key
String sm4Key = GenerateKeyUtil.generateSM4Key();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Examples
Global Configuration
yml
mongo-plus:
encryptor:
key: XXXXXXXXXXXX
public-key: XXXXXXXXXXXXXXXXXXXXXXX
private-key: XXXXXXXXXXXXXXXXXXXXXXXEntity Class Encryption
java
public class User {
@FieldEncrypt(key = "", publicKey = "", privateKey = "")
private String userName;
}Custom Encryptor
java
public class CustomEncryptor implements Encryptor {
@Override
public String encrypt(String data, String key, String publicKey) throws Exception {
return data;
}
@Override
public String decrypt(String data, String key, String privateKey) throws Exception {
return data;
}
}
// Entity class usage
public class User {
@FieldEncrypt(key = "", publicKey = "", privateKey = "", encryptor = CustomEncryptor.class)
private String userName;
}
