【ShardingSphere】ShardingSphere的加解密器

ShardingSphere默认支持AES和MD5两种加密。

关于ShardingSphere脱敏详细,请到官网详阅:https://shardingsphere.apache.org/document/4.1.1/cn/features/orchestration/encrypt/

1、AES加密配置

#加密方式、密钥配置
spring.shardingsphere.encrypt.encryptors.encryptor_aes.type=aes
spring.shardingsphere.encrypt.encryptors.encryptor_aes.props.aes.key.value=123456

#plainColumn表示明文列,cipherColumn表示脱敏列
spring.shardingsphere.encrypt.tables.user.columns.salary.plainColumn=
spring.shardingsphere.encrypt.tables.user.columns.salary.cipherColumn=salary
spring.shardingsphere.encrypt.tables.user.columns.salary.encryptor=encryptor_aes
# 查询是否使用密文列
spring.shardingsphere.props.query.with.cipher.column=true

2、MD5加密配置

spring.shardingsphere.encrypt.encryptors.encryptor_md5.type=md5
spring.shardingsphere.encrypt.tables.user.columns.email.plainColumn=
spring.shardingsphere.encrypt.tables.user.columns.email.cipherColumn=email
spring.shardingsphere.encrypt.tables.user.columns.email.encryptor=encryptor_md5
# 查询是否使用密文列
spring.shardingsphere.props.query.with.cipher.column=true

3、自定义加密

在Apache ShardingSphere中,很多功能实现类的加载方式是通过SPI注入的方式完成的。 Service Provider Interface (SPI)是一种为了被第三方实现或扩展的API,它可以用于实现框架扩展或组件替换。

1)实现自定义解密器 (实现Sharding Encryptor 接口)
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shardingsphere.encrypt.strategy.spi.Encryptor;
public class Sha256Encryptor implements Encryptor {
	private Properties properties = new Properties();

	@Override
	public void init() {
	}

	@Override
	public String encrypt(Object plaintext) {
		if (null == plaintext) {
			return null;
		}
		return DigestUtils.sha256Hex(String.valueOf(plaintext));
	}

	@Override
	public Object decrypt(String ciphertext) {
		return ciphertext;
	}
  // 加解密器的类型
	@Override
	public String getType() {
		return "SHA256";
	}

	@Override
	public Properties getProperties() {
		return properties;
	}

	@Override
	public void setProperties(Properties properties) {
		this.properties = properties;
	}
}
2) .创建org.apache.shardingsphere.spi.encrypt.ShardingEncryptor 文件

resources/META-INF/services目录下新增配置文件,名字为:org.apache.shardingsphere.encrypt.strategy.spi.Encryptor

配置内容:

com.wcw.encryptor.Sha256Encryptor
3)springboot配置文件
# SHA256 -> Sha256Encryptor.getType
spring.shardingsphere.encrypt.encryptors.encryptor_sha256.type=SHA256
spring.shardingsphere.encrypt.tables.user.columns.email.encryptor=encryptor_sha256

代码下载地址:https://gitee.com/firefish/sharding-sphere-study.git

posted @ 2022-03-23 23:13  二月无雨  阅读(1011)  评论(0编辑  收藏  举报