这是我用python加密和解密的代码。
def encrypt(self, raw, key):
raw = self._pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw))
def decrypt(self, enc, key):
enc = base64.b64decode(enc)
iv = enc[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')
def _pad(self, s):
return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
@staticmethod
def _unpad(s):
return s[:-ord(s[len(s)-1:])]
我想用angularscript在angular 7中实现相同的加密/解密。我总是最后得到一个空字符串。这是我在打字稿中加密和解密的代码。
import {Component, OnInit} from '@angular/core';
import {EncryptionService} from './shared';
import * as CryptoJS from 'crypto-js';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private encryptionService: EncryptionService) {
}
title = 'reactiveForm';
ngOnInit() {
const decryptedValue = '8Tp7dEA2MfjL0Q4SF51fLS6oivJtsURyvGQ3q5P9WujZHzfIKZTcRJrfpeQ42T34afV+AkWaTUnmrLxo0jjgHMpS/HVX7KSOUg6G/jNht8Y=';
const secretKey = 'd8xYs6TtzrkhYcpgvHCNO0DvLu5LFBAA';
const decrypted = this.decrypt(secretKey, decryptedValue);
console.log('Decrypted :' + decrypted);
}
decrypt(keys, value) {
const key = CryptoJS.enc.Utf8.parse(keys);
const iv = CryptoJS.enc.Utf8.parse(keys);
const decrypted = CryptoJS.AES.decrypt(this.decodeBase64(value), key, {
keySize: 128 / 8,
iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
};
encrypt(keys, value) {
const key = CryptoJS.enc.Utf8.parse(keys);
const iv = CryptoJS.enc.Utf8.parse(keys);
const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(value.toString()), key,
{
keySize: 128 / 8,
iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString();
};
decodeBase64(data) {
return CryptoJS.enc.Base64.parse(data);
}
}
我在应用程序组件中编写了加密/解密功能,只是为了测试它是否可以正常工作。