繁体   English   中英

从 Node.js 中的 Azure 密钥库获取正确的 pfx 文件

[英]Get correct pfx file from Azure keyvault in Node.js

我正在尝试从 azure keyvault 获取 pfx 文件,而不是将其放在本地计算机上。 我打算用它来创建一个 HTTPS 服务器。

但是,当我从密钥库中读取它并写入本地的 pfx 文件时。 该文件的大小似乎略有变化,即使使用正确的密码也无法生成证书。 我在 java 上尝试了相同的方法,但似乎不是特定于平台的。

    client.getSecret("https://sl-dev-keys.vault.azure.net/secrets/newcertpfx/888175c395264e6096bf0a02ef73de1a", function(getErr, getSecretBundle) {    
    if (getErr) throw getErr;
    console.log('\n\nSecret ', getSecretBundle.value, ' is retrieved.\n');

    var fs = require('fs');
    var fileContent = getSecretBundle.value;

    let writeStream = fs.createWriteStream('test.pfx');

    // write some data with a base64 encoding
    writeStream.write(fileContent, 'base64');

    // the finish event is emitted when all data has been flushed from the stream
    writeStream.on('finish', () => {  
        console.log('wrote all data to file');
    });

    // close the stream
    writeStream.end('end');

下面是如何设置 node.js https 服务器的示例,该服务器的证书作为从 Azure 密钥库中获取的机密文件。

import { SecretClient } from '@azure/keyvault-secrets';
import https from 'https';

...

const client = new SecretClient(url, credential);
const secret = await client.getSecret(certificateName);

const options = {
  pfx: new Buffer(secret.value, 'base64')
};

https.createServer(options, app).listen(PORT);

如果证书文件需要存储在硬盘上,那么您可能需要使用密码对其进行加密。

作为参考,这里有一个用于检索 pfx 文件和添加密码的 PowerShell 脚本:

$kvSecret = Get-AzureKeyVaultSecret -VaultName $vaultName -Name $secretName
$kvSecretBytes = [System.Convert]::FromBase64String($kvSecret.SecretValueText)
$certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certCollection.Import($kvSecretBytes,$null,[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)

$password = '******'
$protectedCertificateBytes = $certCollection.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $password)
$pfxPath = [Environment]::GetFolderPath("Desktop") + "\MyCert.pfx"
[System.IO.File]::WriteAllBytes($pfxPath, $protectedCertificateBytes)

有关详细信息,请参阅Azure Key Vault 证书入门

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM