VUE3+TS实现aes加密解密
时间: 2023-08-01 13:07:32 浏览: 105
可以使用crypto-js库来实现AES加密和解密,下面是一个使用Vue3和TypeScript的示例代码:
```typescript
import { defineComponent } from 'vue';
import CryptoJS from 'crypto-js';
export default defineComponent({
data() {
return {
message: 'Hello world!',
secretKey: 'MySecretKey',
encryptedMessage: '',
decryptedMessage: ''
};
},
methods: {
encrypt(): void {
const ciphertext = CryptoJS.AES.encrypt(this.message, this.secretKey).toString();
this.encryptedMessage = ciphertext;
},
decrypt(): void {
const bytes = CryptoJS.AES.decrypt(this.encryptedMessage, this.secretKey);
const plaintext = bytes.toString(CryptoJS.enc.Utf8);
this.decryptedMessage = plaintext;
}
}
});
```
在上面的代码中,我们使用`CryptoJS.AES.encrypt()`方法进行加密,使用`CryptoJS.AES.decrypt()`方法进行解密。需要注意的是,在使用`AES.decrypt()`方法时,我们需要将加密后的字符串转换为`WordArray`类型的字节流,然后再使用`toString()`方法将其转换为UTF-8编码的字符串。