java京东云Kms密钥管理服务使用

java京东云密钥管理服务使用

前段时间项目中使用到了加密,学习使用了下京东云密钥管理服务。这里记录下,方便今后学习使用
登录京东云官网
java京东云Kms密钥管理服务使用_第1张图片
获取accessKeyId和secretAccessKey在另一篇博客中写过,可以查看下:
获取accessKeyId和secretAccessKey

创建一个密钥

密钥id一会会使用到,这里选择的是 华北-北京
java京东云Kms密钥管理服务使用_第2张图片


前期准备好了。就开始上代码

引入pom

<dependency>
    <groupId>com.jdcloud.sdkgroupId>
    <artifactId>kmsartifactId>
    <version>0.3.0version>
dependency>
application.properties
jd.kms.accessKeyId=京东云账号id
jd.kms.secretAccessKey=京东云密钥
jd.kms.kmsKeyId=KMS密钥ID
jd.kms.redionId=华北-北京区

java京东云Kms密钥管理服务使用_第3张图片

KmsConfig
package com.zjy.knife4j.config;

import com.jdcloud.sdk.auth.CredentialsProvider;
import com.jdcloud.sdk.auth.StaticCredentialsProvider;
import com.jdcloud.sdk.service.kms.client.KmsClient;
import com.jdcloud.sdk.service.kms.model.DecryptRequest;
import com.jdcloud.sdk.service.kms.model.DecryptResponse;
import com.jdcloud.sdk.service.kms.model.EncryptRequest;
import com.jdcloud.sdk.service.kms.model.EncryptResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Optional;

@Configuration
public class KmsConfig {

    /**
     * 京东云账号id
     */
    @Value("${jd.kms.accessKeyId}")
    private String accessKeyId;

    /**
     * 京东云密钥
     */
    @Value("${jd.kms.secretAccessKey}")
    private String secretAccessKey;

    /**
     * KMS密钥ID
     */
    @Value("${jd.kms.kmsKeyId}")
    private String kmsKeyId;

    /**
     * 华北-北京区
     */
    @Value("${jd.kms.redionId}")
    private String redionId;

    @Bean
    public KmsClient kmsClient() {

        CredentialsProvider credentialsProvider = new StaticCredentialsProvider(accessKeyId, secretAccessKey);
        KmsClient kmsClient= KmsClient.builder().credentialsProvider(credentialsProvider).build();

        return kmsClient;
    }

    /**
     * 加密
     * @param val
     * @return
     */
    public String encrypt(String val){
        if (StringUtils.isBlank(val)){
            return null;
        }
        try {
            val = Base64.getEncoder().encodeToString(val.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
        }
        EncryptRequest request = new EncryptRequest();
        request.setPlaintext(val);
        request.setKeyId(kmsKeyId);
        request.setRegionId(redionId);
        EncryptResponse encrypt = kmsClient().encrypt(request);
        return Optional.ofNullable(encrypt)
                .map(e -> e.getResult())
                .map(r -> r.getCiphertextBlob())
                .orElse(null);
    }

    /**
     * 解密
     * @param val
     * @return
     */
    public String decrypt(String val){
        if (StringUtils.isBlank(val)){
            return null;
        }
        DecryptRequest request = new DecryptRequest();
        request.setCiphertextBlob(val);
        request.setKeyId(kmsKeyId);
        request.setRegionId(redionId);
        DecryptResponse decrypt = kmsClient().decrypt(request);
        return Optional.ofNullable(decrypt)
                .map(d -> d.getResult())
                .map(r -> r.getPlaintext())
                .map(KmsConfig::getDecoder)
                .orElse(null);
    }

    public static String getDecoder(String value){
        try {
            byte[] decode2 = Base64.getDecoder().decode(value);
            value = new String(decode2, "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        return value;
    }
}

EncryptionController
package com.zjy.knife4j.controller;

import com.zjy.knife4j.config.KmsConfig;
import com.zjy.knife4j.model.ResultBO;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/encryption")
@RestController
public class EncryptionController {

    @Autowired
    private KmsConfig kmsConfig;

    /**日志对象*/
    private static final Logger logger = LoggerFactory.getLogger(EncryptionController.class);

    @ApiOperation(value = "加密", notes = "加密")
    @PostMapping("encrypt")
    public ResultBO encrypt(@RequestParam(value = "name",required = false) String name){

        logger.info("传入的加密参数为:{}", name);
        ResultBO results = new ResultBO();

        String encrypt = kmsConfig.encrypt(name);
        logger.info("加密后的数据为:{}", encrypt);

        results.setCode(200);
        results.setContent(encrypt);
        results.setMsg("调用测试接口成功!");
        results.setSucceed(true);

        logger.info("调用测试接口成功");
        return results;
    }

    @ApiOperation(value = "解密", notes = "解密")
    @PostMapping("decrypt")
    public ResultBO decrypt(@RequestParam(value = "name",required = false) String name){

        logger.info("传入的解密参数为:{}", name);
        ResultBO results = new ResultBO();

        String encrypt = kmsConfig.decrypt(name);
        logger.info("解密后的数据为:{}", encrypt);

        results.setCode(200);
        results.setContent(encrypt);
        results.setMsg("调用测试接口成功!");
        results.setSucceed(true);

        logger.info("调用测试接口成功");
        return results;
    }
}

测试

这里是使用knife4j。这里介绍knife4j使用

加密

java京东云Kms密钥管理服务使用_第4张图片

解密

java京东云Kms密钥管理服务使用_第5张图片

控制台

java京东云Kms密钥管理服务使用_第6张图片

测试OK!

欢迎大神指导,可以留言交流!

======================
本人原创文章,转载注明出入!

=================

你可能感兴趣的:(技术,java,加密解密,spring,boot)