rsa加密返回
package com.csw.encryptiontechnology.utils.rsa.jiaMi;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside // 表示自定义自己的注解Sensitive
@JsonSerialize(using = SensitiveInfoSerialize.class) // 该注解使用序列化的方式
public @interface RSAEncrypted {
}
package com.csw.encryptiontechnology.utils.rsa.jiaMi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
@Slf4j
@Component
public class RSAUtils {
public static String publicKeyStr;
public static String privateKeyStr;
public RSAUtils(@Value("${rsa.secretKey.publicKey}") String publicKeyStr,
@Value("${rsa.secretKey.privateKey}") String privateKeyStr) {
RSAUtils.publicKeyStr = publicKeyStr;
RSAUtils.privateKeyStr = privateKeyStr;
}
private static final Logger logger = LoggerFactory.getLogger(RSAUtils.class);
private static int kEY_LENGTH = 1024;
public static void main(String[] args) {
try {
// 创建密钥对生成器,指定 RSA 算法
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
// 设置密钥长度
keyPairGenerator.initialize(kEY_LENGTH);
// 生成密钥对
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 获取公钥和私钥
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 将公钥和私钥转换为 Base64 编码的字符串以便输出
String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());
String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());
System.out.println("公钥:" + publicKeyStr);
System.out.println("私钥:" + privateKeyStr);
//测试加密和解密1
String s = encrypt("张三安徽的人123456", publicKeyStr);
System.out.println("加密后]" + s);
String decrypt = decrypt(s, privateKeyStr);
System.out.println("解密后]" + decrypt);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String encrypt(String plainText, String publicKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException, Exception {
byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String privateKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException, Exception {
byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
public static String encrypt(String plainText) throws NoSuchAlgorithmException, InvalidKeySpecException, Exception {
return encrypt(plainText, publicKeyStr);
}
public static String decrypt(String encryptedText) throws NoSuchAlgorithmException, InvalidKeySpecException, Exception {
return decrypt(encryptedText, privateKeyStr);
}
}
package com.csw.encryptiontechnology.utils.rsa.jiaMi;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import java.io.IOException;
import java.util.Objects;
public class SensitiveInfoSerialize extends JsonSerializer<String> implements ContextualSerializer {
/**
* 步骤一
* 方法来源于ContextualSerializer,获取属性上的注解属性,同时返回一个合适的序列化器
*/
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
// 获取自定义注解
RSAEncrypted annotation = beanProperty.getAnnotation(RSAEncrypted.class);
// 注解不为空,且标注的字段为String
if (Objects.nonNull(annotation) && Objects.equals(String.class, beanProperty.getType().getRawClass())) {
//自定义情况,返回本序列化器,将顺利进入到该类中的serialize方法中
return this;
}
// 注解为空,字段不为String,寻找合适的序列化器进行处理
return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
}
/**
* 步骤二
* 方法来源于JsonSerializer<String>:指定返回类型为String类型,serialize()将修改后的数据返回
*/
@Override
public void serialize(String str, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// 定义策略不为空,返回策略处理过的字符串
try {
jsonGenerator.writeString(RSAUtils.encrypt(str, RSAUtils.publicKeyStr));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
脱敏返回
package com.csw.encryptiontechnology.utils.rsa.tuoMin;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@JacksonAnnotationsInside
@JsonSerialize(using = DesensitizationJsonSerializable.class)
public @interface Desensitization {
/**
* 脱敏策略
*
* @return
*/
DesensitizationStrategy value();
}
package com.csw.encryptiontechnology.utils.rsa.tuoMin;
import cn.hutool.core.util.DesensitizedUtil;
import java.util.function.Function;
public enum DesensitizationStrategy {
//收获,保留前三后四,其他的替换为*
PHONE(s -> DesensitizedUtil.desensitized(s, DesensitizedUtil.DesensitizedType.MOBILE_PHONE)),
// 邮箱,保留前一位即@和后面的部分,其他的替换为*
EMAIL(s -> DesensitizedUtil.desensitized(s, DesensitizedUtil.DesensitizedType.EMAIL)),
// 身份证号,保留前一位和后2位,其他的替换为*
ID_CARD(s -> DesensitizedUtil.desensitized(s, DesensitizedUtil.DesensitizedType.ID_CARD)),
// 地址,保留前四位,其他的替换为*
ADDRESS(s -> DesensitizedUtil.desensitized(s, DesensitizedUtil.DesensitizedType.ADDRESS)),
// 银行卡,保留前后四位,其他的替换为*
BANK_CARD(s -> DesensitizedUtil.desensitized(s, DesensitizedUtil.DesensitizedType.BANK_CARD)),
// 姓名,保留前一位,其他的替换为*
NAME(s -> DesensitizedUtil.desensitized(s, DesensitizedUtil.DesensitizedType.CHINESE_NAME)),
// 密码,统一替换为 ******
PASSWORD(s -> "******");
private final Function<String, String> desensitization;
DesensitizationStrategy(Function<String, String> desensitization) {
this.desensitization = desensitization;
}
public Function<String, String> getDesensitization() {
return desensitization;
}
}
package com.csw.encryptiontechnology.utils.rsa.tuoMin;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import java.io.IOException;
import java.util.Objects;
public class DesensitizationJsonSerializable extends JsonSerializer<String> implements ContextualSerializer {
//脱敏策略
private DesensitizationStrategy desensitizationStrategy;
@Override
public void serialize(String s, JsonGenerator gen, SerializerProvider serializers) throws IOException {
// 使用脱敏策略将字符串处理后序列化到json中
gen.writeString(desensitizationStrategy.getDesensitization().apply(s));
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
// 获取属性上的 Desensitization 注解
Desensitization annotation = property.getAnnotation(Desensitization.class);
// 注解不为空 && 属性类型必须是字符串类型
if (Objects.nonNull(annotation) && Objects.equals(String.class, property.getType().getRawClass())) {
//设置脱敏策略
this.desensitizationStrategy = annotation.value();
return this;
}
// 返回默认的序列化器
return prov.findValueSerializer(property.getType(), property);
}
}