node.js - 如何在 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 签名实用程序
解决方案
只需在使用值之前替换 \n :
var private_value = process.env.PRIVATE_KEY.replace(/\\n/g, '\n');
console.log(private_value);
推荐阅读
- html - 从 html 文档中删除文本组
- rust - Rust 宏规则!:如何编写生命周期?
- mysql - 如何获得 GROUP BY,其中最小值是显示的值
- javascript - 执行所有以函数名称开头或包含“xx”的函数
- python - 随机数生成器返回之前未生成的数字
- javascript - 使用 Chart.js 对选定数据的条件悬停效果
- javascript - 使用 Javascript 加密/解密图像/视频/音频?
- java - 您可以将时间戳转换为字段值吗?
- python - 发布请求以在 Python 中检索不记名令牌
- android - build.gradle.kts 中的意外标记(使用“;”分隔同一行上的表达式)