Skip to content

Commit

Permalink
[Key Manager] CryptoJS.AES (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
bh2smith authored Jan 31, 2024
1 parent 7990048 commit 455100a
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 189 deletions.
202 changes: 14 additions & 188 deletions ts-lib/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions ts-lib/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
"dependencies": {
"@nearfoundation/near-js-encryption-box": "^0.1.2",
"bs58": "^5.0.0",
"crypto-js": "^4.2.0",
"ethers": "^6.10.0",
"near-api-js": "^3.0.2"
},
"devDependencies": {
"@types/crypto-js": "^4.2.2",
"@types/jest": "^29.5.11",
"@types/node": "^20.11.10",
"dotenv": "^16.4.1",
Expand Down
46 changes: 46 additions & 0 deletions ts-lib/src/encryption/cryptojs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* This Key Manager is based on the cryptography package provided by
* @nearfoundation/near-js-encryption-box
* It relies on base58 encoding and requires a nonce to decrypt the key!
*/

import { HDNodeWallet } from "ethers";
import { KeyContract } from "../keyContract";
import { EthKeyManager } from "./interface";
import { NearAccount } from "../types";
import CryptoJS from "crypto-js";

export class CryptoJSKeyManager implements EthKeyManager {
// EthKeyContract connected to account for `nearPrivateKey`.
contract: KeyContract;

constructor(contract: KeyContract) {
this.contract = contract;
}

async encryptAndSetKey(
ethWallet: HDNodeWallet,
encryptionKey: string,
): Promise<string | undefined> {
let encryptedKey = CryptoJS.AES.encrypt(
ethWallet.privateKey,
encryptionKey,
);
console.log("Posting Encrypted Key", encryptedKey.toString());
await this.contract.methods.set_key({
encrypted_key: encryptedKey.toString(),
});
return undefined;
}

async retrieveAndDecryptKey(
nearAccount: NearAccount,
// nonce?: string | undefined,
): Promise<string> {
const retrievedKey = await this.contract.methods.get_key({
account_id: nearAccount.accountId,
});
let bytes = CryptoJS.AES.decrypt(retrievedKey!, nearAccount.privateKey);
return bytes.toString(CryptoJS.enc.Utf8);
}
}
1 change: 1 addition & 0 deletions ts-lib/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from "./encryption/base58";
export * from "./encryption/cryptojs";
export * from "./keyContract";
export * from "./types";
Loading

0 comments on commit 455100a

Please sign in to comment.