使用springboot写一个MD5加密的代码
时间: 2023-05-28 17:05:03 浏览: 63
以下是使用Spring Boot编写MD5加密代码的示例:
1. 添加Spring Security依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. 创建一个MD5加密服务类
```java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.springframework.stereotype.Service;
@Service
public class MD5Service {
public String encrypt(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(str.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
```
3. 在控制器中使用MD5加密服务
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MD5Controller {
@Autowired
private MD5Service md5Service;
@GetMapping("/md5/{str}")
public String md5(@PathVariable String str) {
return md5Service.encrypt(str);
}
}
```
现在,当您访问`/md5/{str}`时,您将获得字符串`str`的MD5哈希值。