我已经在node中实现了一个加密方法,可以正常工作,但由于typeScript问题,我在解密时遇到了麻烦。这是我的加密方法,它工作得很好,下面是我的示例
example
private encryptWifiPassword = (param1: string, password: string) => {
const ENCRYPTION_KEY = param1.padStart(32, '0'); // Must be 256 bits (32 characters)
const IV_LENGTH = 16; // For AES, this is always 16
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv('aes-256-gcm', Buffer.from(ENCRYPTION_KEY), iv);
let encrypted = cipher.update('prefix'+ password);
encrypted = Buffer.concat([encrypted, cipher.final()]);
const pskEncripted = iv.toString('base64') + ':' + encrypted.toString('base64')
return pskEncripted
};这是我的解密方法,不起作用
private decryptWifiPassword(param1: string, password: string): string {
const ENCRYPTION_KEY = param1.padStart(32, '0')
let textParts = password.split(':');
let iv = Buffer.from(textParts.shift(),'base64'); //this is the part with the issue
let encryptedText = Buffer.from(textParts.join(':'), 'base64');
let decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(ENCRYPTION_KEY), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}当我尝试解密时,我得到的消息是这样的:
No overload matches this call.
Overload 1 of 5, '(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number | undefined, length?: number | undefined): Buffer', gave the following error.
Argument of type 'string | undefined' is not assignable to parameter of type 'ArrayBuffer | SharedArrayBuffer'.
Type 'undefined' is not assignable to type 'ArrayBuffer | SharedArrayBuffer'.
Overload 2 of 5, '(obj: { valueOf(): string | object; } | { [Symbol.toPrimitive](hint: "string"): string; }, byteOffset?: number | undefined, length?: number | undefined): Buffer', gave the following error.
Argument of type 'string | undefined' is not assignable to parameter of type '{ valueOf(): string | object; } | { [Symbol.toPrimitive](hint: "string"): string; }'.
Type 'undefined' is not assignable to type '{ valueOf(): string | object; } | { [Symbol.toPrimitive](hint: "string"): string; }'.
Overload 3 of 5, '(str: string, encoding?: "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex" | undefined): Buffer', gave the following error.
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.我尝试过这样做-->设iv = Buffer.from(textParts,'base64');但这就是我所得到的解密结果
Decipheriv {
_decoder: null,
_options: undefined,
[Symbol(kHandle)]: {}
}我也试过了,但也不起作用
let iv = Buffer.from(textParts.shift(),'base64') as string我是密码新手,如果能帮上忙就太好了。
非常提前感谢您。
发布于 2020-11-24 21:07:01
TypeScript告诉您textParts.shift()的返回类型可能是undefined。在调用Buffer.from()之前,您需要签入函数以确认值不是undefined,或者使用non-null assertion
let iv = Buffer.from(textParts.shift()!, 'base64');https://stackoverflow.com/questions/64986612
复制相似问题