user 5 年 前
コミット
b2f1b0a13e

ファイルの差分が大きいため隠しています
+ 2 - 2
__tests__/crypto.test.ts


+ 0 - 0
jest.config.js


+ 1 - 2
lib/crypto-forge.d.ts

@@ -1,9 +1,8 @@
-/// <reference types="node" />
 import { ICrypto } from './crypto';
 import { IKeyPair } from './key-pair';
 export default class CryptoForge implements ICrypto {
     generateRsaKeyPair(bits: number): Promise<IKeyPair>;
-    sign(privateKeyObj: any, data: Buffer): Promise<string>;
+    sign(privateKeyObj: any, dataHexBytes: string): Promise<string>;
     importRsaKeyPair(serialized: any): Promise<IKeyPair>;
     private getPublicHash;
     private getPublicKey;

+ 3 - 2
lib/crypto-forge.js

@@ -30,6 +30,7 @@ class CryptoForge {
                     return;
                 }
                 this.export(privateKey, publicKey).then(generated => {
+                    // tslint:disable-next-line:no-console
                     console.log('generated keypair', generated);
                 });
                 resolve({
@@ -41,10 +42,10 @@ class CryptoForge {
             });
         });
     }
-    sign(privateKeyObj, data) {
+    sign(privateKeyObj, dataHexBytes) {
         return __awaiter(this, void 0, void 0, function* () {
             const sha256 = node_forge_1.md.sha256.create();
-            const buf = node_forge_1.util.hexToBytes(data.toString('hex'));
+            const buf = node_forge_1.util.hexToBytes(dataHexBytes);
             sha256.update(buf);
             const signature = privateKeyObj.sign(sha256);
             const hexed = node_forge_1.util.bytesToHex(signature);

ファイルの差分が大きいため隠しています
+ 1 - 1
lib/crypto-forge.js.map


+ 1 - 2
lib/crypto-node.d.ts

@@ -1,9 +1,8 @@
-/// <reference types="node" />
 import { ICrypto } from './crypto';
 import { IKeyPair } from './key-pair';
 export default class CryptoNode implements ICrypto {
     generateRsaKeyPair(bits: number): Promise<IKeyPair>;
-    sign(privateKeyText: string, data: Buffer): Promise<string>;
+    sign(privateKeyText: string, dataHexBytes: string): Promise<string>;
     importRsaKeyPair(serialized: string): Promise<IKeyPair>;
     private getPublicHash;
     private getPublicKey;

+ 19 - 15
lib/crypto-node.js

@@ -7,13 +7,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
         step((generator = generator.apply(thisArg, _arguments || [])).next());
     });
 };
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
 Object.defineProperty(exports, "__esModule", { value: true });
-const { generateKeyPair, createPublicKey, createPrivateKey, createHash, createSign } = require('crypto');
-const bs58 = require('bs58');
+const crypto_1 = require("crypto");
+const bs58_1 = __importDefault(require("bs58"));
 class CryptoNode {
     generateRsaKeyPair(bits) {
         return new Promise((resolve, reject) => {
-            generateKeyPair('rsa', {
+            crypto_1.generateKeyPair('rsa', {
                 modulusLength: bits,
                 privateKeyEncoding: {
                     format: 'pem',
@@ -37,11 +40,11 @@ class CryptoNode {
             });
         });
     }
-    sign(privateKeyText, data) {
+    sign(privateKeyText, dataHexBytes) {
         return __awaiter(this, void 0, void 0, function* () {
-            const privateKey = createPrivateKey(privateKeyText);
-            const sign = createSign('SHA256');
-            sign.write(data);
+            const privateKey = crypto_1.createPrivateKey(privateKeyText);
+            const sign = crypto_1.createSign('SHA256');
+            sign.write(Buffer.from(dataHexBytes, 'hex'));
             sign.end();
             const signature = sign.sign(privateKey, 'hex');
             return signature;
@@ -49,7 +52,8 @@ class CryptoNode {
     }
     importRsaKeyPair(serialized) {
         return __awaiter(this, void 0, void 0, function* () {
-            const { privateKey, publicKey } = JSON.parse(bs58.decode(serialized));
+            const decoded = bs58_1.default.decode(serialized);
+            const { privateKey, publicKey } = JSON.parse(decoded.toString('utf-8'));
             return {
                 export: () => this.export(privateKey, publicKey),
                 getPublicHash: () => this.getPublicHash(publicKey),
@@ -59,28 +63,28 @@ class CryptoNode {
         });
     }
     getPublicHash(publicKeyText) {
-        const publicKey = createPublicKey(publicKeyText);
+        const publicKey = crypto_1.createPublicKey(publicKeyText);
         const derBytes = publicKey.export({
+            format: 'der',
             type: 'spki',
-            format: 'der'
         });
-        const sha256 = createHash('sha256');
+        const sha256 = crypto_1.createHash('sha256');
         sha256.update(derBytes);
-        const pubHash = bs58.encode(sha256.digest());
+        const pubHash = bs58_1.default.encode(sha256.digest());
         return pubHash;
     }
     getPublicKey(publicKeyText) {
-        const publicKey = createPublicKey(publicKeyText);
+        const publicKey = crypto_1.createPublicKey(publicKeyText);
         const derBytes = publicKey.export({
+            format: 'der',
             type: 'spki',
-            format: 'der'
         });
         return derBytes.toString('hex');
     }
     export(privateKey, publicKey) {
         return __awaiter(this, void 0, void 0, function* () {
             const jsonString = JSON.stringify({ privateKey, publicKey });
-            return bs58.encode(Buffer.from(jsonString, 'utf-8'));
+            return bs58_1.default.encode(Buffer.from(jsonString, 'utf-8'));
         });
     }
 }

ファイルの差分が大きいため隠しています
+ 1 - 1
lib/crypto-node.js.map


+ 7 - 6
lib/index.js

@@ -17,6 +17,7 @@ const contact_book_1 = require("./contact-book");
 const contact_item_1 = require("./contact-item");
 const content_item_1 = require("./content-item");
 const util_1 = require("./util");
+const node_forge_1 = require("node-forge");
 class BankClient {
     constructor(urlBase, ipfsUrlBase, storage, webClient, crypto) {
         this.urlBase = urlBase;
@@ -382,7 +383,7 @@ class BankClient {
                 topic
             }));
             const jsonOutput = JSON.stringify(retrieveRequest);
-            const base64ed = Buffer.from(jsonOutput).toString('base64');
+            const base64ed = node_forge_1.util.encode64(jsonOutput);
             const encoded = encodeURIComponent(base64ed);
             const ws = new ws_1.default(this.wsUrlBase + '/bank/ws?arg=' + encoded);
             ws.on('open', () => {
@@ -419,20 +420,20 @@ class BankClient {
     }
     makePlaintextPayload(message) {
         return __awaiter(this, void 0, void 0, function* () {
-            const messageBytes = Buffer.from(message, 'utf-8');
+            const messageHexString = node_forge_1.util.bytesToHex(message);
             yield this.bootstrap();
             if (!this.privateKey) {
                 throw new Error('missing privateKey');
             }
-            const signatureBytes = yield this.privateKey.sign(messageBytes);
+            const signatureBytes = yield this.privateKey.sign(messageHexString);
             const publicKey = yield this.privateKey.getPublicKey();
             const pubHash = yield this.privateKey.getPublicHash();
             const result = {
                 date: new Date().toISOString(),
-                msg: util_1.encodeHex(messageBytes),
-                pub: util_1.encodeHex(Buffer.from(publicKey, 'hex')),
+                msg: messageHexString,
+                pub: publicKey,
                 pubHash,
-                sig: util_1.encodeHex(Buffer.from(signatureBytes, 'hex')),
+                sig: signatureBytes,
             };
             return result;
         });

ファイルの差分が大きいため隠しています
+ 1 - 1
lib/index.js.map


+ 1 - 2
lib/key-pair.d.ts

@@ -1,7 +1,6 @@
-/// <reference types="node" />
 export interface IKeyPair {
     getPublicKey(): string;
     getPublicHash(): string;
-    sign(data: Buffer): Promise<string>;
+    sign(hexStringData: string): Promise<string>;
     export(): Promise<string>;
 }

+ 12 - 18
lib/sample.js

@@ -14,8 +14,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
 const index_1 = require("./index");
 const storage_node_1 = require("./storage-node");
 const webclient_node_1 = require("./webclient-node");
-const host = 'http://127.0.0.1:8082';
-const ipfsHost = 'http://127.0.0.1:5001';
+// const host = 'http://127.0.0.1:8082';
+// const ipfsHost = 'http://127.0.0.1:5001';
+const host = 'https://distributing.fun';
+const ipfsHost = 'https://distributing.fun';
 const crypto_node_1 = __importDefault(require("./../src/crypto-node"));
 const bankClient = new index_1.BankClient(host, ipfsHost, new storage_node_1.StorageNode('bankClient'), new webclient_node_1.WebClientNode(), new crypto_node_1.default());
 (() => __awaiter(this, void 0, void 0, function* () {
@@ -24,14 +26,6 @@ const bankClient = new index_1.BankClient(host, ipfsHost, new storage_node_1.Sto
     console.log('peerId', peerId);
     const balance = yield bankClient.getBalance();
     console.log('my balance', balance);
-    // const uploadResult = await bankClient.upload({
-    //     fileData: 't2',
-    //     fileName: 't3.txt',
-    //     type: 'file',
-    //     title: '442a',
-    //     text: 'txt'
-    // });
-    // console.log('upl', uploadResult);
     // await bankClient.appendBank('bank:qmlink/📥', uploadResult);
     // console.log('added.');
     // const publishRes = await bankClient.appendPrivate(peerId, 'bleh', 'zdj7Wjbc1NqWsVVRaQjWhvvc49MGtszd2VZQ3pWnVKbh6tDWi');
@@ -59,14 +53,14 @@ const bankClient = new index_1.BankClient(host, ipfsHost, new storage_node_1.Sto
     // const items = await bankClient.getItemsForCommaList('1563498096_SL_bafkreiaocpbrzrc45xdkmnwobospujpewrb4t4hk2thqqs5kldtehy62qu');
     // console.log('items', items);
     // setTimeout(async () => {
-    // const uploadResult = await bankClient.upload({
-    //     type: 'file',
-    //     text: 'txt',
-    //     title: 'New random entry in outbox'
-    // });
-    // console.log('upl', uploadResult);
-    // await bankClient.appendBank('QmXRkCwxqecBMXs4DQucS9w85pW16i26tdKcZHExt9z8s5', '📤', uploadResult);
-    // console.log('added.');
+    const uploadResult = yield bankClient.upload({
+        title: 'New random entry in outbox',
+        text: 'txt',
+        type: 'file',
+    });
+    console.log('upl', uploadResult);
+    yield bankClient.appendPrivate('QmXRkCwxqecBMXs4DQucS9w85pW16i26tdKcZHExt9z8s5', '📥', uploadResult);
+    console.log('added.');
     // }, 10000);
     setTimeout(() => {
         console.log('done');

ファイルの差分が大きいため隠しています
+ 1 - 1
lib/sample.js.map


+ 5 - 4
src/crypto-forge.ts

@@ -27,6 +27,7 @@ export default class CryptoForge implements ICrypto {
                 }
 
                 this.export(privateKey, publicKey).then(generated => {
+                  // tslint:disable-next-line:no-console
                   console.log('generated keypair', generated);
                 });
 
@@ -34,15 +35,15 @@ export default class CryptoForge implements ICrypto {
                     export: () => this.export(privateKey, publicKey),
                     getPublicHash: () => this.getPublicHash(publicKey),
                     getPublicKey: () => this.getPublicKey(publicKey),
-                    sign: (data: Buffer) => this.sign(privateKey, data),
+                    sign: (data: string) => this.sign(privateKey, data),
                 });
               });
         });
     }
 
-      public async sign(privateKeyObj: any, data: Buffer): Promise<string> {
+      public async sign(privateKeyObj: any, dataHexBytes: string): Promise<string> {
         const sha256 = md.sha256.create();
-        const buf = util.hexToBytes(data.toString('hex'));
+        const buf = util.hexToBytes(dataHexBytes);
         sha256.update(buf);
         const signature = privateKeyObj.sign(sha256);
         const hexed = util.bytesToHex(signature);
@@ -59,7 +60,7 @@ export default class CryptoForge implements ICrypto {
           export: () => this.export(privateKeyObj, publicKeyObj),
           getPublicHash: () => this.getPublicHash(publicKeyObj),
           getPublicKey: () => this.getPublicKey(publicKeyObj),
-          sign: (data: Buffer) => this.sign(privateKeyObj, data),
+          sign: (data: string) => this.sign(privateKeyObj, data),
       };
     }
 

+ 11 - 10
src/crypto-node.ts

@@ -1,10 +1,10 @@
-import fs = require('fs');
-const { generateKeyPair, createPublicKey, createPrivateKey, createHash, createSign } = require('crypto');
-const bs58 = require('bs58');
+import {createHash, createPrivateKey, createPublicKey, createSign, generateKeyPair} from "crypto";
 
 import { ICrypto } from './crypto';
 import { IKeyPair } from './key-pair';
 
+import bs58 from "bs58";
+
 export default class CryptoNode implements ICrypto {
 
     public generateRsaKeyPair(bits: number): Promise<IKeyPair> {
@@ -30,37 +30,38 @@ export default class CryptoNode implements ICrypto {
                       export: () => this.export(privateKey, publicKey),
                       getPublicHash: () => this.getPublicHash(publicKey),
                       getPublicKey: () => this.getPublicKey(publicKey),
-                      sign: (data: Buffer) => this.sign(privateKey, data),
+                      sign: (data: string) => this.sign(privateKey, data),
                   });
                 });
             });
     }
 
-    public async sign(privateKeyText: string, data: Buffer): Promise<string> {
+    public async sign(privateKeyText: string, dataHexBytes: string): Promise<string> {
       const privateKey = createPrivateKey(privateKeyText);
       const sign = createSign('SHA256');
-      sign.write(data);
+      sign.write(Buffer.from(dataHexBytes, 'hex'));
       sign.end();
       const signature = sign.sign(privateKey, 'hex');
       return signature;
     }
 
     public async importRsaKeyPair(serialized: string): Promise<IKeyPair> {
-        const { privateKey, publicKey } = JSON.parse(bs58.decode(serialized));
+      const decoded = bs58.decode(serialized);
+        const { privateKey, publicKey } = JSON.parse(decoded.toString('utf-8'));
 
         return {
           export: () => this.export(privateKey, publicKey),
           getPublicHash: () => this.getPublicHash(publicKey),
           getPublicKey: () => this.getPublicKey(publicKey),
-          sign: (data: Buffer) => this.sign(privateKey, data),
+          sign: (data: string) => this.sign(privateKey, data),
       };
     }
 
     private getPublicHash(publicKeyText: string): string {
       const publicKey = createPublicKey(publicKeyText);
       const derBytes = publicKey.export({
+        format: 'der',
         type: 'spki',
-        format: 'der'
       });
 
       const sha256 = createHash('sha256');
@@ -72,8 +73,8 @@ export default class CryptoNode implements ICrypto {
     private getPublicKey(publicKeyText: string): string {
       const publicKey = createPublicKey(publicKeyText);
       const derBytes = publicKey.export({
+        format: 'der',
         type: 'spki',
-        format: 'der'
       });
       return derBytes.toString('hex');
     }

+ 8 - 6
src/index.ts

@@ -11,6 +11,8 @@ import { UploadItemParameters } from './upload-item-parameters';
 import { encodeHex, mergeDeep, uuid } from './util';
 import { IWebClient } from './webclient';
 
+import { asn1, md, pki, util } from 'node-forge';
+
 export class BankClient {
 
   public static parseBankLink(bankLink: string) {
@@ -378,7 +380,7 @@ export class BankClient {
       }));
 
       const jsonOutput = JSON.stringify(retrieveRequest);
-      const base64ed = Buffer.from(jsonOutput).toString('base64');
+      const base64ed = util.encode64(jsonOutput);
       const encoded = encodeURIComponent(base64ed);
       const ws = new WebSocket(this.wsUrlBase + '/bank/ws?arg=' + encoded);
       
@@ -418,21 +420,21 @@ export class BankClient {
   }
 
   private async makePlaintextPayload(message: string) {
-    const messageBytes = Buffer.from(message, 'utf-8');
+    const messageHexString = util.bytesToHex(message);
     await this.bootstrap();
     if (!this.privateKey) {
       throw new Error('missing privateKey');
     }
-    const signatureBytes = await this.privateKey.sign(messageBytes);
+    const signatureBytes = await this.privateKey.sign(messageHexString);
     const publicKey = await this.privateKey.getPublicKey();
     const pubHash = await this.privateKey.getPublicHash();
 
     const result = {
       date: new Date().toISOString(),
-      msg: encodeHex(messageBytes),
-      pub: encodeHex(Buffer.from(publicKey, 'hex')),
+      msg: messageHexString,
+      pub: publicKey,
       pubHash,
-      sig: encodeHex(Buffer.from(signatureBytes, 'hex')),
+      sig: signatureBytes,
     };
     return result;
   }

+ 1 - 1
src/key-pair.ts

@@ -4,7 +4,7 @@ export interface IKeyPair {
 
     getPublicHash(): string;
 
-    sign(data: Buffer): Promise<string>;
+    sign(hexStringData: string): Promise<string>;
 
     export(): Promise<string>;
 

+ 14 - 19
src/sample.ts

@@ -1,8 +1,11 @@
 import { BankClient } from './index';
 import { StorageNode } from './storage-node';
 import { WebClientNode } from './webclient-node';
-const host = 'http://127.0.0.1:8082';
-const ipfsHost = 'http://127.0.0.1:5001';
+// const host = 'http://127.0.0.1:8082';
+// const ipfsHost = 'http://127.0.0.1:5001';
+
+const host = 'https://distributing.fun';
+const ipfsHost  = 'https://distributing.fun';
 import CryptoNode from './../src/crypto-node';
 
 const bankClient = new BankClient(host, ipfsHost, new StorageNode('bankClient'), new WebClientNode(), new CryptoNode());
@@ -13,15 +16,7 @@ const bankClient = new BankClient(host, ipfsHost, new StorageNode('bankClient'),
     console.log('peerId', peerId);
     const balance = await bankClient.getBalance();
     console.log('my balance', balance);
-    // const uploadResult = await bankClient.upload({
-    //     fileData: 't2',
-    //     fileName: 't3.txt',
-    //     type: 'file',
-    //     title: '442a',
-    //     text: 'txt'
-    // });
-    
-    // console.log('upl', uploadResult);
+
     // await bankClient.appendBank('bank:qmlink/📥', uploadResult);
     // console.log('added.');
     // const publishRes = await bankClient.appendPrivate(peerId, 'bleh', 'zdj7Wjbc1NqWsVVRaQjWhvvc49MGtszd2VZQ3pWnVKbh6tDWi');
@@ -52,14 +47,14 @@ const bankClient = new BankClient(host, ipfsHost, new StorageNode('bankClient'),
     // console.log('items', items);
 
     // setTimeout(async () => {
-    // const uploadResult = await bankClient.upload({
-    //     type: 'file',
-    //     text: 'txt',
-    //     title: 'New random entry in outbox'
-    // });
-    // console.log('upl', uploadResult);
-    // await bankClient.appendBank('QmXRkCwxqecBMXs4DQucS9w85pW16i26tdKcZHExt9z8s5', '📤', uploadResult);
-    // console.log('added.');
+    const uploadResult = await bankClient.upload({
+        title: 'New random entry in outbox',
+        text: 'txt',
+        type: 'file',
+    });
+    console.log('upl', uploadResult);
+    await bankClient.appendPrivate('QmXRkCwxqecBMXs4DQucS9w85pW16i26tdKcZHExt9z8s5', '📥', uploadResult);
+    console.log('added.');
     // }, 10000);
     
     setTimeout(() => {