You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
982 B

import CryptoJS from 'crypto-js';
import { sm4 } from 'sm-crypto';
import { BaseSymmetricEncryption } from '../base';
/**
* SM4
*/
export class Sm4Encryption extends BaseSymmetricEncryption {
override decrypt(data: string, key: string): string {
this.checkKey(key);
const keyHex = CryptoJS.enc.Hex.stringify(CryptoJS.enc.Utf8.parse(key));
return sm4.decrypt(data, keyHex);
}
override encrypt(data: string, key: string): string {
this.checkKey(key);
/**
* hex
* encryptkey`16进制字符串``原始字符串`
* ab a0x61 b0x62 6162
*/
const keyHex = CryptoJS.enc.Hex.stringify(CryptoJS.enc.Utf8.parse(key));
return sm4.encrypt(data, keyHex);
}
/**
* key16
* @param key key
*/
private checkKey(key: string) {
if (key.length !== 16) {
throw new Error('SM4 key must be 16 bytes');
}
}
}