安装加密的工具 crypto-js
安装 crypto-js
npm install crypto-js --save
使用的例子
在使用的 ts 文件中:
import * as CryptoJS from 'crypto-js';
// 对应的类名根据实际情况定
class{
encrypt() {
// 1230
// 4122cb13c7a474c1976c9706ae36521d
let encryptData = CryptoJS.MD5("1230").toString(CryptoJS.enc.Hex);
}
}
完整使用的案例
附录:
import { Component, OnInit } from '@angular/core';
import * as CryptoJS from 'crypto-js';
@Component({
selector: 'app-demo',
templateUrl: './demo.component.html',
styleUrls: ['./demo.component.scss']
})
export class DemoComponent implements OnInit {
encryptData: any;
constructor() { }
ngOnInit() {
}
encrypt() {
// 1230
// 4122cb13c7a474c1976c9706ae36521d
this.encryptData = CryptoJS.MD5("1230").toString(CryptoJS.enc.Hex);
var sHA1 = CryptoJS.SHA1("Message").toString(CryptoJS.enc.Hex);
console.log("sHA1 = %s", sHA1);
var sHA256 = CryptoJS.SHA256("Message").toString(CryptoJS.enc.Hex);
console.log("sHA256 = %s", sHA256);
var hmacMD5 = CryptoJS.HmacMD5("Message", "Secret Passphrase").toString(CryptoJS.enc.Hex);
console.log("hmacMD5 = %s", hmacMD5);
var hmacSHA1 = CryptoJS.HmacSHA1("Message", "Secret Passphrase").toString(CryptoJS.enc.Hex);
console.log("hmacSHA1 = %s", hmacSHA1);
var aesEncrypt = CryptoJS.AES.encrypt("Message", "Secret Passphrase");
console.log("aesEncrypt = %s", aesEncrypt.iv.toString(CryptoJS.enc.Hex));
var aesDecrypt = CryptoJS.AES.decrypt(aesEncrypt, "Secret Passphrase");
console.log("aesDecrypt = %s", aesDecrypt.toString(CryptoJS.enc.Utf8));
// base64 encrypt
var rawStr = "hello world!";
var wordArray = CryptoJS.enc.Utf8.parse(rawStr);
var base64 = CryptoJS.enc.Base64.stringify(wordArray);
console.log('base64Encrypt = ', base64);
// base64 decrypt
var parsedWordArray = CryptoJS.enc.Base64.parse(base64);
var parsedStr = parsedWordArray.toString(CryptoJS.enc.Utf8);
console.log('base64Decrypt = ',parsedStr);
}
}