UNPKG

1.98 kBJavaScriptView Raw
1//
2// Copyright (c) Microsoft and contributors. All rights reserved.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
17/**
18 * Functions to work with key and certificate files
19 */
20
21var fs = require('fs');
22var utils = require('./utils');
23
24var KEY_PATT = /(-+BEGIN RSA PRIVATE KEY-+)(\n\r?|\r\n?)([A-Za-z0-9\+\/\n\r]+\=*)(\n\r?|\r\n?)(-+END RSA PRIVATE KEY-+)/;
25var CERT_PATT = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9\+\/\n\r]+\=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/;
26
27exports.readFromFile = function readFromFile(fileName) {
28 // other parameters are optional
29 var data;
30 try {
31 data = fs.readFileSync(fileName, 'utf8');
32 } catch(e) {
33 throw new Error('No account information found. Please import credentials using "azure account import <file>".');
34 }
35 return exports.readFromString(data);
36};
37
38exports.readFromString = function readFromString(data) {
39 var ret = {};
40 var matchKey = data.match(KEY_PATT);
41 if (matchKey) {
42 ret.key = matchKey[1] + '\n' + matchKey[3] + '\n' + matchKey[5] + '\n';
43 }
44
45 var matchCert = data.match(CERT_PATT);
46 if (matchCert) {
47 ret.cert = matchCert[1] + '\n' + matchCert[3] + '\n' + matchCert[5] + '\n';
48 }
49
50 return ret;
51};
52
53exports.writeToFile = function writeToFile(fileName, keyCertData) {
54 utils.writeFileSyncMode(fileName, exports.writeToString(keyCertData), 'utf8');
55};
56
57exports.writeToString = function writeToString(keyCertData) {
58 return (keyCertData.key || '') + (keyCertData.cert || '');
59};