Springboot + Vue3 使用Rsa加解密示例代码
以下是一个使用Spring Boot和Vue3进行RSA加解密的示例代码:
后端代码(Spring Boot):
import org.springframework.security.crypto.encrypt.RsaEncryptor;
import org.springframework.security.crypto.encrypt.RsaSecretEncryptor;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RsaController {
private final RsaEncryptor rsaEncryptor;
public RsaController(RsaEncryptor rsaEncryptor) {
this.rsaEncryptor = rsaEncryptor;
}
@PostMapping("/encrypt")
public String encrypt(@RequestBody String plainText) {
byte[] encryptedBytes = rsaEncryptor.encrypt(plainText.getBytes());
return Base64Utils.encodeToString(encryptedBytes);
}
@PostMapping("/decrypt")
public String decrypt(@RequestBody String encryptedText) {
byte[] encryptedBytes = Base64Utils.decodeFromString(encryptedText);
byte[] decryptedBytes = rsaEncryptor.decrypt(encryptedBytes);
return new String(decryptedBytes);
}
}
前端代码(Vue3):
<template>
<div>
<input v-model="plainText" type="text" placeholder="Plain Text" />
<button @click="encrypt">Encrypt</button>
<input v-model="encryptedText" type="text" placeholder="Encrypted Text" />
<button @click="decrypt">Decrypt</button>
<input v-model="decryptedText" type="text" placeholder="Decrypted Text" />
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
plainText: '',
encryptedText: '',
decryptedText: '',
};
},
methods: {
async encrypt() {
try {
const response = await axios.post('/encrypt', this.plainText);
this.encryptedText = response.data;
} catch (error) {
console.error(error);
}
},
async decrypt() {
try {
const response = await axios.post('/decrypt', this.encryptedText);
this.decryptedText = response.data;
} catch (error) {
console.error(error);
}
},
},
};
</script>
在上述代码中,后端使用了Spring Boot的RsaEncryptor来进行RSA加密和解密操作。前端使用了Vue3框架,并使用axios库发送加密和解密请求。
请注意,上述代码仅提供了一个基本的示例,实际应用中需要根据具体的需求进行适当的修改和调整
原文地址: https://www.cveoy.top/t/topic/igiM 著作权归作者所有。请勿转载和采集!