文章目录
- 项目环境
- 一 swagger技术的补充
-
- 1.1 [swagger]((https://github.com/OAI/OpenAPI-Specification))介绍
- 1.2 swagger的基础注解
- 1.3 controller添加swagger注解
- 二 项目搭建
-
- 2.1 创建数据库
- 2.2 引入项目依赖
- 2.3 配置数据库的连接
- 2.4 配置swagger的配置信息
- 2.5 编写实体类
- 2.6 编写业务接口和查询实现
- 2.7 启动项目
- 三 项目完成之数字签名
-
- 3.1 编写工具类
-
- 3.1.1 RsaDemo
- 3.1.2 SignatureDemo
- 3.2 添加controller接口
- 3.3 运行程序
项目环境
- JDK19
- springboot 2.7.6
- swagger 2.9.2
- lombok
- commons-io 2.11.0
- mysql 8.0.32
一 swagger技术的补充
1.1 swagger介绍
- OpenAPI规范(OpenAPI Specification 简称OAS)是Linux基金会的一个项目,试图通过定义一种用来描述API格式或API定义的语言,来规范RESTful服务开发过程,目前版本是V3.0,并且已经发布并开源在github上。
- Swagger是全球最大的OpenAPI规范(OAS)API开发工具框架,支持从设计和文档到测试和部署的整个API生命周期的开发。
- Spring Boot 可以集成Swagger,生成Swagger接口,Spring Boot是Java领域的神器,它是Spring项目下快速构建项目的框架
1.2 swagger的基础注解
- swagger通过注解生成接口文档,包括接口名、请求方法、参数、返回信息的等
注释 |
说明 |
@Api |
修饰整个类,描述Controller的作用 |
@ApiOperation |
描述一个类的一个方法,或者说一个接口 |
@ApiParam |
单个参数描述 |
@ApiModel |
用对象实体来作为入参 |
@ApiProperty |
用对象接实体收参数时,描述对象的一个字段 |
@ApiResponse |
HTTP响应其中1个描述 |
@ApiResponses |
HTTP响应整体描述 |
@ApiIgnore |
使用该注解忽略这个API |
@ApiError |
发生错误返回的信息 |
@ApiImplicitParam |
一个请求参数 |
@ApiImplicitParams |
多个请求参数 |
- @ApiOperation
@ApiOperation(value = “接口说明”, httpMethod = “接口请求方式”, response = “接口返回参数类型”, notes = “接口发布说明”)
@RequestMapping("/swagger")
@ResponseBody
@ApiOperation(value = "根据用户名获取用户的信息",notes = "查询数据库中的记录",httpMethod = "POST",response = String.class)
public String getUserInfo(String userName) {
return "1234";
}
}
- @ApiImplicitParam 一个请求参数
@ApiImplicitParam(required = “是否必须参数”, name = “参数名称”, value = “参数具体描述”,dateType=“变量类型”,paramType=”请求方式”)
@ApiImplicitParam(name = "userName",value = "用户名",required = true,dataType = "String",paramType = "query")
public String getUserInfo(String userName) {
return "1234";
}
}
- @ApiImplicitParams 多个请求参数
- 参数和@ApiImplicitParam一致,只是这个注解可以添加多个参数而已
@ApiImplicitParams({
@ApiImplicitParam(name = "nickName",value = "用户的昵称",paramType = "query",dataType = "String",required = true),
@ApiImplicitParam(name = "id",value = "用户的ID",paramType = "query",dataType = "Integer",required = true)
})
public String getUserInfoByNickName(String nickName, Integer id) {
return "1234";
}
1.3 controller添加swagger注解
import com.yang.mapper.UserMapper;
import com.yang.pojo.User;
import com.yang.utils.RsaDemo;
import com.yang.utils.SignatureDemo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.security.PublicKey;
import java.util.List;
@Api(tags = "提供用户的增删改查的功能")
@RestController
public class UserController {
@Autowired
UserMapper userMapper;
@ApiOperation(value = "查询用户")
@RequestMapping(value = "/findAll", method = RequestMethod.GET)
public List<User> queryUserList() {
List<User> userList = userMapper.queryUserList();
for(User user:userList ) {
System.out.println(user);
}
return userList;
}
@ApiOperation(value = "根据id查询用户")
@RequestMapping(value = "/queryUserById",method = RequestMethod.GET)
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "用户的id",paramType = "query",dataType = "int",required = true)
})
public User queryUserById(@RequestParam("id") int Id) {
return userMapper.queryUserById(Id);
}
@ApiOperation(value = "添加用户")
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser() {
userMapper.addUser(new User(6, "三毛", "123456"));
return "finish addUser";
}
@ApiOperation(value = "更新用户")
@RequestMapping(value = "/updateUser", method = RequestMethod.PUT)
public String updateUser() {
userMapper.updateUser(new User(6, "阿毛", "5211314"));
return "finish UpdateUser";
}
@ApiOperation(value = "删除用户")
@RequestMapping(value = "/addUser", method = RequestMethod.DELETE)
public String deleteUer() {
userMapper.deleteUser(6);
return "finish DeleteUser";
}
@ApiOperation(value = "购物")
@RequestMapping(value = "/buy", method = RequestMethod.GET)
public String buy(String price, String num, String signature) {
try {
PublicKey publicKey = RsaDemo.loadPublicKeyFromFile("RSA", "a.pub");
boolean result = SignatureDemo.verifySignature(price + num, "SHA256withRSA", publicKey, signature);
System.out.println(result);
if (result) {
return "购物成功";
}
} catch (Exception e) {
e.printStackTrace();
}
return "购物失败";
}
}
二 项目搭建
2.1 创建数据库
CREATE DATABASE USER;
USE USER;
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(20),
password VARCHAR(50),
)
2.2 引入项目依赖
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>com.mysqlgroupId>
<artifactId>mysql-connector-jartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>3.0.1version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>2.9.2version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>2.9.2version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.11.0version>
dependency>
<dependency>
<groupId>commons-codecgroupId>
<artifactId>commons-codecartifactId>
<version>1.15version>
dependency>
dependencies>
2.3 配置数据库的连接
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
datasource:
username: root
password: yqk.20021027
url: jdbc:mysql://localhost:3306/user?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
type-aliases-package: com.yang.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
2.4 配置swagger的配置信息
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(true)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.yang.controller"))
.build();
}
private ApiInfo apiInfo() {
Contact contact = new Contact("缘友一世", "https://www.csdn.net/", "[email protected]");
return new ApiInfo(
"Spring Boot集成Swagger和加密解密",
"学习Swagger",
"1.0",
"http://localhost",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}
2.5 编写实体类
- 根据数据库表的结果,进行编写实体类
- 可以使用lombok工具快速生成get,set方法和有参、无参构造器
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.ibatis.type.Alias;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Alias("User")
public class User {
private int id;
private String username;
private String password;
}
2.6 编写业务接口和查询实现
- 编写controller接口
import com.yang.mapper.UserMapper;
import com.yang.pojo.User;
import com.yang.utils.RsaDemo;
import com.yang.utils.SignatureDemo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.security.PublicKey;
import java.util.List;
@Api(tags = "提供用户的增删改查的功能")
@RestController
public class UserController {
@Autowired
UserMapper userMapper;
@ApiOperation(value = "查询用户")
@RequestMapping(value = "/findAll", method = RequestMethod.GET)
public List<User> queryUserList() {
List<User> userList = userMapper.queryUserList();
for(User user:userList ) {
System.out.println(user);
}
return userList;
}
@ApiOperation(value = "根据id查询用户")
@RequestMapping(value = "/queryUserById",method = RequestMethod.GET)
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "用户的id",paramType = "query",dataType = "int",required = true)
})
public User queryUserById(@RequestParam("id") int Id) {
return userMapper.queryUserById(Id);
}
@ApiOperation(value = "添加用户")
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser() {
userMapper.addUser(new User(6, "三毛", "123456"));
return "finish addUser";
}
@ApiOperation(value = "更新用户")
@RequestMapping(value = "/updateUser", method = RequestMethod.PUT)
public String updateUser() {
userMapper.updateUser(new User(6, "阿毛", "5211314"));
return "finish UpdateUser";
}
@ApiOperation(value = "删除用户")
@RequestMapping(value = "/addUser", method = RequestMethod.DELETE)
public String deleteUer() {
userMapper.deleteUser(6);
return "finish DeleteUser";
}
}
- 编写mapper接口
@Mapper
@Repository
public interface UserMapper {
List<User> queryUserList();
User queryUserById(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
- 编写mapeer的实现
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yang.mapper.UserMapper">
<select id="queryUserList" resultType="User">
select * from user;
select>
<select id="queryUserById" resultType="User" parameterType="int">
select * from user where id = #{id};
select>
<insert id="addUser" parameterType="User">
insert into user(id,name,pwd) values (#{id},#{name},#{pwd});
insert>
<update id="updateUser" parameterType="User">
update user set name=#{name},pwd=#{pwd} where id=#{id};
update>
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id};
delete>
mapper>
2.7 启动项目
- swagger的访问地址:
http://localhost:8080/swagger-ui.html
- 点击try it out 输入姓名, Execute执行,返回如下图效果
三 项目完成之数字签名
- 模拟购物场景,用户点击购物的时候,在前端生成签名信息,传递给后台服务器进行校验,如果价格,数量,签名都正确,购物成功,如果参数被人修改,则购物失败
3.1 编写工具类
- 两个代码 RsaDemo.java 和 SignatureDemo.java
- RsaDemo:生成并保存公钥和私钥文件
- SignatureDemo:生成数字签名
3.1.1 RsaDemo
package com.yang.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import javax.crypto.Cipher;
public class RsaDemo {
public static void main(String[] args) throws Exception {
generateKeyToFile("RSA", "a.pub", "a.pri");
}
public static void generateKeyToFile(String algorithm, String pubPath, String priPath) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
byte[] publicKeyEncoded = publicKey.getEncoded();
byte[] privateKeyEncoded = privateKey.getEncoded();
String publicKeyString = Base64.encodeBase64String(publicKeyEncoded);
String privateKeyString = Base64.encodeBase64String(privateKeyEncoded);
FileUtils.writeStringToFile(new File(pubPath), publicKeyString,Charset.forName("UTF-8"));
FileUtils.writeStringToFile(new File(priPath), privateKeyString,Charset.forName("UTF-8"));
}
public static PublicKey loadPublicKeyFromFile(String algorithm, String filePath) throws Exception {
String keyString = FileUtils.readFileToString(new File(filePath), Charset.forName("UTF-8"));
return loadPublicKeyFromString(algorithm, keyString);
}
public static PublicKey loadPublicKeyFromString(String algorithm, String keyString) throws Exception {
byte[] decode = Base64.decodeBase64(keyString);
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
X509EncodedKeySpec keyspec = new X509EncodedKeySpec(decode);
return keyFactory.generatePublic(keyspec);
}
public static PrivateKey loadPrivateKeyFromFile(String algorithm, String filePath) throws Exception {
String keyString = FileUtils.readFileToString(new File(filePath),Charset.forName("UTF-8"));
return loadPrivateKeyFromString(algorithm, keyString);
}
public static PrivateKey loadPrivateKeyFromString(String algorithm, String keyString) throws Exception {
byte[] decode = Base64.decodeBase64(keyString);
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
PKCS8EncodedKeySpec keyspec = new PKCS8EncodedKeySpec(decode);
return keyFactory.generatePrivate(keyspec);
}
public static String encrypt(String algorithm, String input, Key key, int maxEncryptSize) throws Exception {
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] data = input.getBytes();
int total = data.length;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
decodeByte(maxEncryptSize, cipher, data, total, baos);
return Base64.encodeBase64String(baos.toByteArray());
}
public static void decodeByte(int maxSize, Cipher cipher, byte[] data, int total, ByteArrayOutputStream baos) throws Exception {
int offset = 0;
byte[] buffer;
while (total - offset > 0) {
if (total - offset >= maxSize) {
buffer = cipher.doFinal(data, offset, maxSize);
offset += maxSize;
} else {
buffer = cipher.doFinal(data, offset, total - offset);
offset = total;
}
baos.write(buffer);
}
}
}
- 运行 RsaDemo.java 生成 公钥和私钥
3.1.2 SignatureDemo
package com.yang.utils;
import org.apache.commons.codec.binary.Base64;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
public class SignatureDemo {
public static void main(String[] args) throws Exception {
String a = "10" + "10";
PublicKey publicKey = RsaDemo.loadPublicKeyFromFile("RSA", "a.pub");
PrivateKey privateKey = RsaDemo.loadPrivateKeyFromFile("RSA", "a.pri");
String signaturedData = getSignature(a, "sha256withrsa", privateKey);
System.out.println(signaturedData);
}
public static String getSignature(String input, String algorithm, PrivateKey privateKey) throws Exception {
Signature signature = Signature.getInstance(algorithm);
signature.initSign(privateKey);
signature.update(input.getBytes());
byte[] sign = signature.sign();
return Base64.encodeBase64String(sign);
}
public static boolean verifySignature(String input, String algorithm, PublicKey publicKey, String signaturedData) throws Exception {
Signature signature = Signature.getInstance(algorithm);
signature.initVerify(publicKey);
signature.update(input.getBytes());
return signature.verify(Base64.decodeBase64(signaturedData));
}
}
3.2 添加controller接口
@ApiOperation(value = "购物")
@RequestMapping(value = "/buy", method = RequestMethod.GET)
public String buy(String price, String num, String signature) {
try {
PublicKey publicKey = RsaDemo.loadPublicKeyFromFile("RSA", "a.pub");
boolean result = SignatureDemo.verifySignature(price + num, "SHA256withRSA", publicKey, signature);
System.out.println(result);
if (result) {
return "购物成功";
}
} catch (Exception e) {
e.printStackTrace();
}
return "购物失败";
}
3.3 运行程序