Skip to content

Commit

Permalink
Incorporate save function from auto-utils into Load key function & tests
Browse files Browse the repository at this point in the history
  • Loading branch information
abhi3700 committed Jun 5, 2024
1 parent d679460 commit 1d9cf2f
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 12 deletions.
8 changes: 8 additions & 0 deletions packages/auto-id/src/helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Helper function to safely parse JSON with a fallback
export function tryParseJson(jsonString: string, fallback: string): string {
try {
return JSON.parse(jsonString);
} catch (e) {
return fallback; // Return the original string if it's not JSON
}
}
20 changes: 12 additions & 8 deletions packages/auto-id/src/keyManagement.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { save } from '@autonomys/auto-utils'
import { KeyObject, createPrivateKey, createPublicKey, generateKeyPairSync } from 'crypto'
import { promises as fs } from 'fs'
import { writeFile } from 'fs/promises'
import { tryParseJson } from './helper'

/**
* Generates an RSA key pair.
Expand Down Expand Up @@ -113,7 +113,7 @@ export function keyToPem(key: KeyObject, password?: string): string {
export async function saveKey(key: KeyObject, filePath: string, password?: string): Promise<void> {
try {
const pem = keyToPem(key, password)
await save(filePath, pem);
await save(filePath, pem)
} catch (e: any) {
throw new Error(`Failed to save key: ${e.message}`)
}
Expand Down Expand Up @@ -167,9 +167,11 @@ export function pemToPrivateKey(pemData: string, password?: string): KeyObject {
*/
export async function loadPrivateKey(filePath: string, password?: string): Promise<KeyObject> {
try {
const keyData = await fs.readFile(filePath)
const privateKey = pemToPrivateKey(keyData.toString(), password)
return privateKey
let keyData = await fs.readFile(filePath, {encoding: 'utf-8'})
// Check if keyData is JSON-encoded and parse it
keyData = tryParseJson(keyData, keyData) // Fallback to original data if not JSON
const privateKey = pemToPrivateKey(keyData, password)
return privateKey;
} catch (error: any) {
throw new Error(`Failed to load private key: ${error.message}`)
}
Expand Down Expand Up @@ -213,8 +215,10 @@ export function pemToPublicKey(pemData: string): KeyObject {
*/
export async function loadPublicKey(filePath: string): Promise<KeyObject> {
try {
const keyData = await fs.readFile(filePath)
const publicKey = pemToPublicKey(keyData.toString())
let keyData = await fs.readFile(filePath, { encoding: 'utf8' })
// Check if keyData is JSON-encoded and parse it
keyData = tryParseJson(keyData, keyData); // Fallback to original data if not JSON
const publicKey = pemToPublicKey(keyData);
return publicKey
} catch (error: any) {
throw new Error(`Failed to load public key: ${error.message}`)
Expand Down Expand Up @@ -288,4 +292,4 @@ export function doPublicKeysMatch(publicKey1: KeyObject, publicKey2: KeyObject):

// Compare the serialized public key data
return publicKey1Der.equals(publicKey2Der)
}
}
8 changes: 4 additions & 4 deletions packages/auto-id/tests/keyManagement.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ describe('PEM to Private/Public key for', () => {
}
})

describe('saveKey function', () => {
describe('Save Key', () => {
const keyGenerators = [
{ name: 'RSA', generator: generateRsaKeyPair },
{ name: 'Ed25519', generator: generateEd25519KeyPair },
Expand Down Expand Up @@ -174,7 +174,7 @@ describe('saveKey function', () => {
const fileContents = await fs.readFile(filePath, { encoding: 'utf8' })

// Check if the PEM string matches expected, considering JSON.stringify use
expect(fileContents).toBe(JSON.stringify(keyToPem(privateKeyObject)));
expect(fileContents).toBe(JSON.stringify(keyToPem(privateKeyObject)))
})

test('should save an encrypted private key to a file', async () => {
Expand All @@ -185,7 +185,7 @@ describe('saveKey function', () => {
const fileContents = await fs.readFile(filePath, { encoding: 'utf8' })

// Parse it back to normal string
const actualPemContent = JSON.parse(fileContents);
const actualPemContent = JSON.parse(fileContents)

// Check if the file content starts and ends with the expected encrypted private key headers
expect(actualPemContent.startsWith('-----BEGIN ENCRYPTED PRIVATE KEY-----')).toBe(true)
Expand All @@ -200,7 +200,7 @@ describe('saveKey function', () => {
}
})

describe('Key loading functions', () => {
describe('Load Key', () => {
const keyGenerators = [
{ name: 'RSA', generator: generateRsaKeyPair },
{ name: 'Ed25519', generator: generateEd25519KeyPair },
Expand Down

0 comments on commit 1d9cf2f

Please sign in to comment.