Giter Club home page Giter Club logo

eosjs-ecc's Introduction

NPM Build Status

Elliptic curve cryptography functions (ECC)

Private Key, Public Key, Signature, AES, Encryption / Decryption

Import

import ecc from 'eosjs-ecc'
// or
const ecc = require('eosjs-ecc')

Include

  • Install with: yarn add eosjs-ecc
  • Html script tag, see releases for the correct version and its matching script integrity hash.
<html>
<head>
  <meta charset="utf-8">
  <!--
  sha512-cL+IQQaQ586s9DrXfGtDheRpj5iDKh2M+xlpfwbhNjRIp4BGQ1fkM/vB4Ta8mc+f51YBW9sJiPcyMDIreJe6gQ== lib/eosjs-ecc.js
  sha512-dYFDmK/d9r3/NCp6toLtfkwOjSMRBaEzaGAx1tfRItC0nsI0hVLERk05iNBQR7uDNI7ludYhcBI4vUiFHdjsTQ== lib/eosjs-ecc.min.js
  sha512-eq1SCoSe38uR1UVuQMwR73VgY8qKTBDc87n2nIiC5WLhn1o2y1U6c5wY8lrigVX7INM8fM0PxDlMX5WvpghKig== lib/eosjs-ecc.min.js.map
  -->
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/eosjs-ecc.min.js"
    integrity="sha512-dYFDmK/d9r3/NCp6toLtfkwOjSMRBaEzaGAx1tfRItC0nsI0hVLERk05iNBQR7uDNI7ludYhcBI4vUiFHdjsTQ=="
    crossorigin="anonymous"></script>

</head>
<body>
  See console object: eosjs_ecc
</body>
</html>

Common API

Table of Contents

wif

Wallet Import Format

Type: string

ecc

initialize

Initialize by running some self-checking code. This should take a second to gather additional CPU entropy used during private key generation.

Initialization happens once even if called multiple times.

Returns Promise

unsafeRandomKey

Does not pause to gather CPU entropy.

Returns Promise<PrivateKey> test key

randomKey

Parameters

  • cpuEntropyBits number gather additional entropy from a CPU mining algorithm. This will already happen once by default. (optional, default 0)

Examples

ecc.randomKey().then(privateKey => {
console.log('Private Key:\t', privateKey) // wif
console.log('Public Key:\t', ecc.privateToPublic(privateKey)) // EOSkey...
})

Returns Promise<wif>

seedPrivate

Parameters

  • seed string any length string. This is private. The same seed produces the same private key every time. At least 128 random bits should be used to produce a good private key.

Examples

ecc.seedPrivate('secret') === wif

Returns wif

privateToPublic

Parameters

  • wif wif
  • pubkey_prefix string public key prefix (optional, default 'EOS')

Examples

ecc.privateToPublic(wif) === pubkey

Returns pubkey

isValidPublic

Parameters

  • pubkey pubkey like EOSKey..
  • pubkey_prefix string (optional, default 'EOS')

Examples

ecc.isValidPublic(pubkey) === true

Returns boolean valid

isValidPrivate

Parameters

Examples

ecc.isValidPrivate(wif) === true

Returns boolean valid

sign

Create a signature using data or a hash.

Parameters

  • data (string | Buffer)
  • privateKey (wif | PrivateKey)
  • encoding String data encoding (if string) (optional, default 'utf8')

Examples

ecc.sign('I am alive', wif)

Returns string string signature

signHash

Parameters

  • dataSha256 (String | Buffer) sha256 hash 32 byte buffer or string
  • privateKey (wif | PrivateKey)
  • encoding String dataSha256 encoding (if string) (optional, default 'hex')

Returns string string signature

verify

Verify signed data.

Parameters

  • signature (string | Buffer) buffer or hex string
  • data (string | Buffer)
  • pubkey (pubkey | PublicKey)
  • encoding (optional, default 'utf8')
  • hashData boolean sha256 hash data before verify (optional, default true)

Examples

ecc.verify(signature, 'I am alive', pubkey) === true

Returns boolean

recover

Recover the public key used to create the signature.

Parameters

  • signature (String | Buffer) (EOSbase58sig.., Hex, Buffer)
  • data (String | Buffer) full data
  • encoding String data encoding (if data is a string) (optional, default 'utf8')

Examples

ecc.recover(signature, 'I am alive') === pubkey

Returns pubkey

recoverHash

Parameters

  • signature (String | Buffer) (EOSbase58sig.., Hex, Buffer)
  • dataSha256 (String | Buffer) sha256 hash 32 byte buffer or hex string
  • encoding String dataSha256 encoding (if dataSha256 is a string) (optional, default 'hex')

Returns PublicKey

sha256

Parameters

  • data (string | Buffer) always binary, you may need Buffer.from(data, 'hex')
  • resultEncoding (optional, default 'hex')
  • encoding string result encoding 'hex', 'binary' or 'base64' (optional, default 'hex')

Examples

ecc.sha256('hashme') === '02208b..'
ecc.sha256(Buffer.from('02208b', 'hex')) === '29a23..'

Returns (string | Buffer) Buffer when encoding is null, or string

pubkey

EOSKey..

Type: string

Usage (Object API)

let {PrivateKey, PublicKey, Signature, Aes, key_utils, config} = require('eosjs-ecc')

// Create a new random private key
let privateWif
PrivateKey.randomKey().then(privateKey => privateWif = privateKey.toWif())

// Convert to a public key
pubkey = PrivateKey.fromString(privateWif).toPublic().toString()

Browser

git clone https://github.com/EOSIO/eosjs-ecc.git
cd eosjs-ecc
yarn
yarn build_browser
# builds: ./dist/eosjs-ecc.js
# Verify release hash
<script src=eosjs-ecc.js></script>
var ecc = eosjs_ecc

ecc.randomKey().then(privateWif =>  {
  var pubkey = ecc.privateToPublic(privateWif)
  console.log(pubkey)
})

eosjs-ecc's People

Contributors

barchef avatar c0d3ster avatar greenbusdriver avatar jcalfee avatar jeffreyssmith2nd avatar nsjames avatar ryanwdavies avatar takn avatar tarassh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

eosjs-ecc's Issues

Encrypt data using public key, decrypt using EOS private key

Is it possible to add an assymetric encryption options to the library so it is possible to encrypt the data using one's public key and then decrypt the data using one's private key using the same algorithm as the one used for signing the transactions?

There is only symmetric encryption available when both keys are needed

npm run build does not build eosjs-ecc.js

Output of npm run build:


Angelos-iMac:eosjs-ecc al$ npm run build

[email protected] build /Users/al/Documents/eos-encryption-demo/eosjs-ecc
babel src --out-dir lib

src/aes.js -> lib/aes.js
src/api_common.js -> lib/api_common.js
src/api_object.js -> lib/api_object.js
src/common.test.js -> lib/common.test.js
src/config.js -> lib/config.js
src/ecdsa.js -> lib/ecdsa.js
src/ecsignature.js -> lib/ecsignature.js
src/enforce_types.js -> lib/enforce_types.js
src/hash.js -> lib/hash.js
src/index.js -> lib/index.js
src/key_private.js -> lib/key_private.js
src/key_public.js -> lib/key_public.js
src/key_utils.js -> lib/key_utils.js
src/object.test.js -> lib/object.test.js
src/promise-async.js -> lib/promise-async.js
src/signature.js -> lib/signature.js


Seems to be running without error but then, contrary to the readme, there is no eosjs-ecc.js file to be found.

same public key for different private keys

try to generate the public key for these two private keys you will get an exact same public key

  1. 5KhV5DqYYLYuxKkFjNZj7vGTYFUP8wux1ND4xArGYeLb1rKbNjR
  2. 5KhV5DqYYLYuxKkFjNZj7vGTYFUP8wux1ND4xArGYeLb1rKbNjS

is it the limitation of the ECC ????

Where is 'checksum256' type?

Hello, I'd studied eosjs-ecc, I'd like use string of checksum256 type.
But I can't find this type. Where can I find checksum256?
I NEED this type of js.

signing alogrithm in eosjs-ecc yields different signature from that in eos!

Hi,

I'm working on signature related development and I find that signing alogrithm in eosjs-ecc yields different signature from that in eos!!!! Both tag is dawn-v4.0.0.

Reproduce steps:

Firstly let's generate a signature from eos networks.

1 ) Let's have a transaction, for example:

{"expiration":"2018-05-23T07:29:11","ref_block_num":1,"ref_block_prefix":2,"max_net_usage_words":3,"max_cpu_usage_ms":4,"delay_sec":5,"context_free_actions":[],"actions":[{"account":"eosio.token","name":"issue","authorization":[{"actor":"eosio.token","permission":"active"}],"data":"0000000000ea305580969800000000000455445400000000056973737565"}],"transaction_extensions":[],"signatures":[],"context_free_data":[]}

And we use the default private key 5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3

2 ) I add some printing statements in private_key.cpp:

image

3 ) I send this transaction to v1/wallet/sign_transaction interface via rpc. Then in eos side, we know the digest of the transaction is 9d8815193d76ee236ef08e8b9fb675e6def3af8d8209d7665540ab9e17944e19 (in hex)

image

4 ) The sign_transaction yields result:

{"expiration":"2018-05-22T23:29:11.000+0000","refBlockNum":1,"refBlockPrefix":2,"maxNetUsageWords":3,"maxKcpuUsageMs":4,"delaySec":5,"contextFreeActions":[],"actions":[{"account":"eosio.token","name":"issue","authorization":[{"actor":"eosio.token","permission":"active"}],"data":"0000000000ea305580969800000000000455445400000000056973737565"}],"transactionExtensions":[],"signatures":["SIG_K1_K3dztmFctY8QPgD6BEnxaV4s1gxyfHPZYTqHx8gH9Hiq2MLvn8Uc4ki6w7C89GVXAQ5JFM37BERe5qJSVHAqSkD8AabtKR"],"contextFreeData":[]}

You can see the signature is :

SIG_K1_K3dztmFctY8QPgD6BEnxaV4s1gxyfHPZYTqHx8gH9Hiq2MLvn8Uc4ki6w7C89GVXAQ5JFM37BERe5qJSVHAqSkD8AabtKR

Now let's try it from eosjs-ecc. Steps:

1 ) I write some simple code. The input:

Digest: 9d8815193d76ee236ef08e8b9fb675e6def3af8d8209d7665540ab9e17944e19

private key: 5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3

image

2 ) Execute the code, the signature is:

SIG_K1_KgMrn3yteiHtoUnqBjBcVhjuJRkeXAfwaYFQaCDmMC6sD7mGU5qQRaz3GHWe96Mfvq5Ei56EHBiwjh7sg6GYjBGzcRv81Y

image

Background:

I'm writing a java based eos library and I've finished the java version fc-library. For the same transaction the java version fc-library yields same digest with eos side, however the final signatures are different(although I use the same private key). The signature in eos code refers to secp256k1.c in bitcoin and it is too hard for me to investigate so I have to refer to the eosjs-ecc for the ecc signing algorithm however by which I found that even for same digest and same private key the eosjs-ecc yields different signatures with this eos repository!!!

Any solution or advice on this please?

Regards

Export ecdsa calcPubKeyRecoveryParam

I'm trying to create a new Signature. I already have the r and s value for the signature. Getting i what I'm having a hard time with.

var signature = new ecc.Signature(rBigInteger, sBigInteger, i).toString();

Currently I'm using the calcPubKeyRecoveryParam method in this external sourced ecdsa library to get the i value, however that library is depreciated and also has problem when run through webpack + uglify.
https://github.com/cryptocoinjs/ecdsa

I see eosjs-ecc has it's own copy of this ecdsa lib but I can't see an easy way to call it. Could you please export this method or explain how I can call that method without directly pathing into the node_modules folder.

ecc.recover() does not seem to function as expected

The below code signs a string "123" and then called recover .. for some reason the key returned does not match the expected key. Please explain or flag as bug.

The output of the below looks as follows:
123
SIG_K1_K1K6bCbJ9AqxYgeYLGxqtG4MhiyBodTqGsjEeeGcguBTWpBEg54rywEGkNUYbn9uPF7QtCUo9sD8XKd7By3FbJDd78cY9m
recovered key: EOS5Q36JqHkTrsBuEufZTFLgKn7YQ582ew6STCFWmwVTuEFEgERec

	function recoverTest() {

		var initaPrivate = '5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3';
		var initaPublic = 'EOS6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV';

		var action = document.getElementById('transaction').value;
		console.log(action);

		var sign = ecc.sign(action, initaPrivate ,'hex').toString();
		console.log(sign);

		var recover = ecc.recover(sign, action);
		console.log("recovered key: "+recover);
	}

Creating Address from my own Mnemonic/Seed

let bip39 = require('bip39');

let {PrivateKey, PublicKey} = require('eosjs-ecc')
 
let privateWif;
let Address;

let sampleMnemonic = "fun swamp jump history obvious scare struggle deputy cannon village buzz state power play expose moral million lift gravity size chalk grocery scout toss";
let seed = bip39.mnemonicToSeed(sampleMnemonic); 
const privateKey = PrivateKey.fromBuffer(seed);
 privateWif = privateKey.toWif() 
 Address = PrivateKey.fromWif(privateWif).toPublic().toString();
 console.log("Your EOS Seed Address:" + Address);
 console.log("Your Private Key:" + privateWif);

The above code creates a consistent Address & Private Key, but when passing my seed into the Buffer I get a warning message that my buffer is 64 bytes and the fromBuffer() is expecting 32. I can see from this post: #7 that I need to divide my seed into a chain code? but I don't see how that is possible.

PrivateKey.fromWif not support compressed WIF format

It seems that PrivateKey.fromWif doesn't support WIF with compressed format.
When I use a WIF private key with compressed format, some warning shows up:
WARN: Expecting 32 bytes, instead got 33, stack trace: Error
And I can get a result from the function. However, the result is not correct.

So I read the souce code. PrivateKey.fromWif will generate a BigInteger from buffer generated from WIF format. So if I provide a compressed WIF which has an extra compressed flag byte, it will use the 33 bytes data to generate the private key. But it is not my original private key.

Unable to reliably recover Public Key deterministically from transaction

I have test cases based on 2 signatures produced by the EOS C++ executable and I am unable to reliably (works or fails depending on signature) recover the Public Key matching the Private Key that was used for those signatures.

Keypair : EOS6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV / 5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3

Signatures:
EOSK5yY5ehsnDMc6xcRhsLYzFuZGUaKwb4hc8oLmP5HA1EhU42NRo3ygx3zvLRJ1nkw1NA5nCSegwcYkSfkZBQBzqMDsCGnNK
EOSKkwLhwDoRF8gpGFbcUKiaPdeeKo6U7eDuXQw9szMiNE4K4cFe17sffk6hmy3mWf1ogtzd5J5kvnvFD3Lq5cF6VyYb3KsGy

Test case 1 (PASS - matches Pub Key)
eosjs_ecc.Signature.fromString('EOSK5yY5ehsnDMc6xcRhsLYzFuZGUaKwb4hc8oLmP5HA1EhU42NRo3ygx3zvLRJ1nkw1NA5nCSegwcYkSfkZBQBzqMDsCGnNK').recover(eos.Buffer('00'.repeat(32) + '20d8af5a0000b32bcc0e37eb0000000000010000000000ea305500409e9a2264b89a010000000000ea305500000000a8ed32327c0000000000ea305500001059b1abe93101000000010002c0ded2bc1f1305fb0faac5e6c03ee3a1924234985427b6167ca569d13df435cf01000001000000010002c0ded2bc1f1305fb0faac5e6c03ee3a1924234985427b6167ca569d13df435cf0100000100000000010000000000ea305500000000a8ed32320100', 'hex')).toString()

Test case 2 (FAIL - Pub Key is different)
eosjs_ecc.Signature.fromStringOrThrow('EOSKkwLhwDoRF8gpGFbcUKiaPdeeKo6U7eDuXQw9szMiNE4K4cFe17sffk6hmy3mWf1ogtzd5J5kvnvFD3Lq5cF6VyYb3KsGy').recover(eosjs_ecc.Buffer('00'.repeat(32) + '30d3b35a0000be0194c22fe70000000000010000000000ea305500409e9a2264b89a010000000000ea305500000000a8ed32327c0000000000ea305500000059b1abe93101000000010002c0ded2bc1f1305fb0faac5e6c03ee3a1924234985427b6167ca569d13df435cf01000001000000010002c0ded2bc1f1305fb0faac5e6c03ee3a1924234985427b6167ca569d13df435cf0100000100000000010000000000ea305500000000a8ed32320100', 'hex')).toString()

Can I use eosjs-ecc to decrypt wallet file? If not, what should I do?

Hello, I have a test wallet and the content is

{
  "cipher_keys": "702e87d25a5acb0bb64b1cfa6045f51f86092a58f1d88c9c2caff0d69d7024bcbff6b68972b4b3d2ae8e0b83e3a23bff79e2d6a21aed9b1a341ee8d0d9f981b220a5e36802f056d27797a939ac5d0349fb16bdeb596fc1c24262cf292757e515d0f9ac84fb66fecfdc5e8574f734768d67c09745bb5b4c01f2f170339dfe4b0d3ee2af4c164f521a8fc07c860473849e"
}

Can I use eosjs-ecc to decrypt it? If not, what should I do?

Please help me, thank you.

Add encoding parameter for a Signature's data

Adding an encoding parameter will make it possible to use hex strings helping to avoid the requirement to use a Buffer in the API (allows for hex strings).

Update: sign, verify, and recover methods..

This change applied to the recover method: b62b37c

pubkey =“XXX”

Hello, how do I formulate the prefix for generating the public key in the browser?

This library is very comprehensive. Thank you.
ecc.privateToPublic(wif) === pubkey

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'map' of undefined

Getting error on account creation :-
const defaultPrivateKey = "5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3"; // bob
const signatureProvider = new JsSignatureProvider(['5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3']);
const api = new Api({ rpc, signatureProvider, textDecoder: new TextDecoder(), textEncoder: new TextEncoder() });

const result = await api.transact(
{
account: 'eosio',
name: 'newaccount',
authorization: [{
actor: 'eosio',
permission: 'active',
}],
data: {
creator: 'eosio',
name: 'mynewaccount',
owner: {
threshold: 1,
keys: [{
key: '6FPFZqw5ahYrR9jD96yDbbDNTdKtNqRbze6oTDLntrsANgQKZu',
weight: 1
}],
accounts: [],
waits: []
},
active: {
threshold: 1,
keys: [{
key: '6FPFZqw5ahYrR9jD96yDbbDNTdKtNqRbze6oTDLntrsANgQKZu',
weight: 1
}],
accounts: [],
waits: []
},
},
},
{
blocksBehind: 3,
expireSeconds: 30,
}
);

Standardize public, private, and signature key formats

I would like to standardize on this format: PUB_K1_xxx and PUB_R1_xxx and SIG_xxx. The original WIF private and EOS public key can be accepted but the format would be normalized to the new format.

Back end changes to the private, public, and signature formats:
EOSIO/eos@573be19

Delimiter changed from . to _ EOSIO/eos@f55f431

EOSpubkey    => PUB_K1_base58pubkey (public key w/legacy fallback) [unit tests](https://github.com/EOSIO/eos/blob/master/libraries/fc/test/crypto/test_cypher_suites.cpp)
EOSsignature => SIG_K1_base58sig (rename signature prefix)
WIF          => PVT_K1_base58private private key prefix

This change affects eosjs-keygen ..

Remove import of old bytebuffer. Can't build a library that includes eosjs-ecc

I'm trying to build an NPM package that includes eosjs-ecc. When I build it I get this:

WARNING in ./node_modules/bytebuffer/dist/bytebuffer-node.js
Module not found: Error: Can't resolve 'memcpy' in '/home/steve/Documents/GitHub/aikon/ore-js/node_modules/bytebuffer/dist'
@ ./node_modules/bytebuffer/dist/bytebuffer-node.js
@ ./node_modules/eosjs-ecc/lib/aes.js
@ ./node_modules/eosjs-ecc/lib/api_common.js
@ ./node_modules/eosjs-ecc/lib/index.js
@ ./src/verifier.js
@ ./src/index.js

When I try and run a project that includes this library it stops and just gives this error:

(node:17758) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

eosjs-ecc imports browserify-aes which imports byteBuffer

─┬ [email protected]
│ ├── [email protected]
│ ├─┬ [email protected]
│ │ ├── [email protected]
│ │ ├─┬ [email protected]
│ │ │ ├── [email protected] deduped
│ │ │ └── [email protected] deduped
│ │ ├── [email protected] deduped
│ │ ├─┬ [email protected]
│ │ │ ├── [email protected] deduped
│ │ │ └── [email protected] deduped
│ │ ├── [email protected] deduped
│ │ └── [email protected] deduped
│ ├─┬ [email protected]
│ │ └─┬ [email protected]
│ │ └── [email protected] deduped
│ ├─┬ [email protected]
│ │ └── [email protected]

Is this something you could fix in your library? Get rid or replace browserify-aes?

Thanks

Can the toPublic method add an pubkey_prefix parameter for user-defined use?

function toPublic() {

Original edition

function toPublic() {
        if (public_key) {
            // cache
            // S L O W in the browser
            return public_key
        }
        const Q = secp256k1.G.multiply(d);
        return public_key = PublicKey.fromPoint(Q);
    }

Revised

function toPublic(pubkey_prefix = 'EOS') {
        if (public_key) {
            // cache
            // S L O W in the browser
            return public_key
        }
        const Q = secp256k1.G.multiply(d);
        return public_key = PublicKey.fromPoint(Q, pubkey_prefix );
    }

https://www.bcskill.com/index.php/archives/700.html

mnemonic

hi,
i lost my private key, but have mnemonic.

is there any way to solve this problem?....

Why use hash concatenating more zero bytes when calculating K

Hey everyone
I want to known why EOS need the lenR and lenS are both 32 , It's not a requirement in ethereum.

while (true) {
        ecsignature = ecdsa.sign(curve, dataSha256, privateKey.d, nonce++);
        der = ecsignature.toDER();
        console.log("der: " + der.toString('hex'))
        lenR = der[3];
        lenS = der[5 + lenR];
        if (lenR === 32 && lenS === 32) {
            i = ecdsa.calcPubKeyRecoveryParam(curve, e, ecsignature, privateKey.toPublic().Q);
            i += 4; // compressed
            i += 27; // compact  //  24 or 27 :( forcing odd-y 2nd key candidate)
            break;
        }
        if (nonce % 10 === 0) {
            console.log("WARN: " + nonce + " attempts to find canonical signature");
        }
    }

and why to generate a new K by changing the hash.

function deterministicGenerateK(curve, hash, d, checkSig, nonce) {

  enforceType('Buffer', hash);
  enforceType(BigInteger, d);

  if (nonce) {
    hash = crypto.sha256(Buffer.concat([hash, new Buffer(nonce)]));
  }
  console.log('toSign: ' + hash.toString('hex'))

  // sanity check
  assert.equal(hash.length, 32, 'Hash must be 256 bit');

  var x = d.toBuffer(32);
  var k = new Buffer(32);
  var v = new Buffer(32);

  // Step B
  v.fill(1);

  // Step C
  k.fill(0);

  // Step D
  k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([0]), x, hash]), k);

  // Step E
  v = crypto.HmacSHA256(v, k);

  // Step F
  k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([1]), x, hash]), k);

  // Step G
  v = crypto.HmacSHA256(v, k);

  // Step H1/H2a, ignored as tlen === qlen (256 bit)
  // Step H2b
  v = crypto.HmacSHA256(v, k);

  var T = BigInteger.fromBuffer(v);

  // Step H3, repeat until T is within the interval [1, n - 1]
  while (T.signum() <= 0 || T.compareTo(curve.n) >= 0 || !checkSig(T)) {
    k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([0])]), k);
    v = crypto.HmacSHA256(v, k);

    // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
    // Step H2b again
    v = crypto.HmacSHA256(v, k);

    T = BigInteger.fromBuffer(v);
  }

  return T;
}

Is it possible to get the correct K only with the following code?

  // Step H3, repeat until T is within the interval [1, n - 1]
  while (T.signum() <= 0 || T.compareTo(curve.n) >= 0 || !checkSig(T)) {
    k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([0])]), k);
    v = crypto.HmacSHA256(v, k);

    // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
    // Step H2b again
    v = crypto.HmacSHA256(v, k);

    T = BigInteger.fromBuffer(v);
  }

Thanks

Get base58 public key from hex

Not sure if this is the right place for this question.

However here is the problem.

I'm trying get the public key from my ledger nano S.

publicKey: "0436f9684f39d8bea1e54c04140803aff5ab11b90sf005c66e7835cee6c1bc5c1c0f68a3586d3bb2467ae9d91d22ec59075de2576483779eca7430dde0778de3c2"
wif: "EOS5JhbadEK34EGF78UeZTbaofJP7JyqTrppYyxzs59LDPMWyH7p6"

This is the response I get.

Is there any way I can use this library to get the public key in the right format.
I tried using ecc.privatetoPublic(wif) but ti didn't work (remove the eos prefix - got some checksum error.)

Can you in anyway help me with this.

@jcalfee Can you help me with this?

No delimiter in string, cannot determine type Error

It seems that the signature has changed in eos.
It seems that we need to make changes.
libraries/fc/src/crypto/signature.cpp
static signature::storage_type parse_base58(const std::string& base58str)
{
constexpr auto prefix = config::signature_base_prefix;

  const auto pivot = base58str.find('_');
  FC_ASSERT(pivot != std::string::npos, "No delimiter in string, cannot determine type: ${str}", ("str", base58str));

  const auto prefix_str = base58str.substr(0, pivot);
  FC_ASSERT(prefix == prefix_str, "Signature Key has invalid prefix: ${str}", ("str", base58str)("prefix_str", prefix_str));

  auto data_str = base58str.substr(pivot + 1);
  FC_ASSERT(!data_str.empty(), "Signature has no data: ${str}", ("str", base58str));
  return base58_str_parser<signature::storage_type, config::signature_prefix>::apply(data_str);

}

Error Log ==>
EOSIO/eos@f55f431#diff-41a221719ab6bb16c1ddaf8a235c9a47

Improve asset precision handling and validation

Mimic the cleos wallet: assets that are not on the blockchain can derive precision from the amount.

eos.create('eosio', '100000000.00 A')

However, any asset on the blockchain will have the current behavior in eosjs and always get and validate with a precision derived from the contract's stats.max_supply value.

Encrypt the private key with a passphrase?

Hi,

I'm building an application that requires a private key to be encrypted/decrypted with a passphrase. As this is not currently a feature, what advice would you give me regarding how I should go about this? Planning on obviously pushing any changes I make privately to enhance this.

Thanks

Add initilization as a separate process

Two functions can be performed and re-used in future requests for random keys:

  • Gather extra entropy (cpu for example)
  • Run some base unit tests to ensure libraries are working as expected

private publick key conversion not working for jungle testnet 2

I create new account on eos jungle testnet 2
with public key : EOS5G3Zg9w8CKAe38ksuqD7KS2P7NjGUjowwvF9YweET86KoNECMf
when using the corresponding private key, they are not matching when converting with eos-ecc
please update things according to eos jungle testnet 2

ecc.isValidPublic() return false on some valid public keys

ecc.isValidPublic('EOS5K6ag7t87u3F4jdkmt73wQtd9oprQFyJsp6vskrrwoQoPqcPdE7') return false #489

Version
eosjs 20.0.0-beta3
eosjs-ecc 4.0.4

Describe the bug

  1. ecc.isValidPublic() return false on 2 public keys of account 1255gdpaftgs
  2. Point.decodeFrom() report 'Invalid sequence tag'

To Reproduce

  1. get the public keys of 1255gdpaftgs

  2. validate these keys using ecc.isValidPublic()

# umu @ UMU-MBP in ~/github/meet-one/mainnet-snapshot on git:master x [21:45:27]
$ cleos -u https://mainnet.meet.one get account 1255gdpaftgs
created: 2018-11-08T01:25:13.500
permissions:
     owner     1:    1 EOS5K6ag7t87u3F4jdkmt73wQtd9oprQFyJsp6vskrrwoQoPqcPdE7
        active     1:    1 EOS5Kkxpsx71txnR8niEmZmcG6d6AeSQqYw1qfXYQBDkgh5v4tbGxH
memory:
     quota:     5.345 KiB    used:     3.365 KiB

net bandwidth:
     staked:          0.1000 EOS           (total stake delegated from account to self)
     delegated:       0.0000 EOS           (total staked delegated to account from others)
     used:                 0 bytes
     available:        79.93 KiB
     limit:            79.93 KiB

cpu bandwidth:
     staked:          0.1000 EOS           (total stake delegated from account to self)
     delegated:       0.0000 EOS           (total staked delegated to account from others)
     used:                 0 us
     available:        12.63 ms
     limit:            12.63 ms

producers:     <not voted>


# umu @ UMU-MBP in ~/github/meet-one/mainnet-snapshot on git:master x [21:45:33]
$ node
> const ecc = require('eosjs-ecc')
undefined
> ecc.isValidPublic('EOS5K6ag7t87u3F4jdkmt73wQtd9oprQFyJsp6vskrrwoQoPqcPdE7')
false
> ecc.isValidPublic('EOS5Kkxpsx71txnR8niEmZmcG6d6AeSQqYw1qfXYQBDkgh5v4tbGxH')
false

Expected behavior
true, but return false.

More
It seems like a bug of ecurve 1.0.5

ecc.PublicKey('EOS5Kkxpsx71txnR8niEmZmcG6d6AeSQqYw1qfXYQBDkgh5v4tbGxH')

type is 128, isValidPublic() = false

ecc.PublicKey('EOS7enq7SL9AUhBYgkYMksj34LPKtAr7iu56KKrNTcUPTRqTp5VaN')

type is 3, isValidPublic() = true

I use C++ code to validate these keys, and the test passes.

BOOST_AUTO_TEST_CASE(test_by_UMU) try {
   auto pub_str = std::string("EOS5Kkxpsx71txnR8niEmZmcG6d6AeSQqYw1qfXYQBDkgh5v4tbGxH");
   auto pub = public_key(pub_str);

   std::cout << pub_str << " => " << pub << std::endl;

   BOOST_CHECK(pub.valid());
   BOOST_CHECK_EQUAL(pub_str, std::string(pub));
} FC_LOG_AND_RETHROW();

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.