| 115 | } |
| 116 | |
| 117 | function tryDecryptWithKey(encrypted: string, key: Buffer): string | null { |
| 118 | try { |
| 119 | const parts = encrypted.slice(ENCRYPTED_PREFIX.length).split(':') |
| 120 | if (parts.length !== 3) return null |
| 121 | |
| 122 | const [ivBase64, authTagBase64, ciphertext] = parts |
| 123 | const iv = Buffer.from(ivBase64, 'base64') |
| 124 | const authTag = Buffer.from(authTagBase64, 'base64') |
| 125 | |
| 126 | const decipher = createDecipheriv(ALGORITHM, key, iv) |
| 127 | decipher.setAuthTag(authTag) |
| 128 | |
| 129 | let decrypted = decipher.update(ciphertext, 'base64', 'utf8') |
| 130 | decrypted += decipher.final('utf8') |
| 131 | return decrypted |
| 132 | } catch { |
| 133 | return null |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | /** |
| 138 | * 解密旧加密 API Key,尝试所有可用的 device key 和 legacy machine-id 密钥 |