簡體   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