首页 > 解决方案 > 如何在 PEM 文件中保留换行符,使用 NodeJS 将其拉入我的应用程序?

问题描述

使用 NodeJS,我将 PEM 文件拉入我的应用程序。该文件位于 AWS S3 和我的本地环境中。当我在本地运行应用程序时,一切都很好。但是,当我在 EC2 上运行它时,我收到以下错误:

错误:无效的私钥字符串,必须包含换行符

我正在使用AWS CloudFront URL 签名实用程序

这是我的功能:

    function createSignedCookie(domain){

        // we need the domain
        if (!domain) {
            return false;
        }

        const cookieLifeSpan = 900000; // milliseconds, is equal to 15 mins
        const expires = new Date().getTime() + cookieLifeSpan;
        const keyPairId = config.accessKeyId;
        const keyPath = config.pemFilePath;

        const options = {expireTime: expires, keypairId: keyPairId, privateKeyPath: keyPath}

        const signedCookies = cfsign.getSignedCookies(domain + '/*', options);

        return signedCookies;
    }

我尝试在 PEM 的每一行末尾添加 \n ,但这并没有解决它。
我还尝试在 PEM 的每一行末尾添加 \r ,但这并没有解决它。
我看着这个,但它没有帮助

这是getSignedCookies方法:

function getSignedCookies(cfUrl, params){
  var privateKey = _getPrivateKey(params);
  var policy = _createPolicy(
    cfUrl, _getExpireTime(params), _getIpRange(params));
  var signature = _createPolicySignature(policy, privateKey);
  var policyStr = new Buffer(policy.toJSON()).toString('base64');

  var cookies = {};
  cookies['CloudFront-Policy'] = normalizeBase64(policyStr);
  cookies['CloudFront-Signature'] = normalizeBase64(signature);
  cookies['CloudFront-Key-Pair-Id'] = params.keypairId;

  return cookies;
}

这是_privateKey方法

function _getPrivateKey(params) {
  var privateKeyString = params.privateKeyString;
  var pem;

  if (params.privateKeyPath) {
    pem = fs.readFileSync(params.privateKeyPath);

    privateKeyString = pem.toString('ascii');
    console.log(privateKeyString);
  }

  var newLinePattern = /\r|\n/;
  var lineBreakExists = newLinePattern.test(privateKeyString);
  if (!lineBreakExists) {
      throw new Error('Invalid private key string, must include line breaks');
  }

  return privateKeyString;
}

上述两种方法都附带AWS CloudFront URL 签名实用程序

标签: node.jsamazon-s3amazon-cloudfront

解决方案


只需在使用值之前替换 \n :

var private_value = process.env.PRIVATE_KEY.replace(/\\n/g, '\n');
console.log(private_value);

推荐阅读