GithubHelp home page GithubHelp logo

tlsfuzzer / python-ecdsa Goto Github PK

View Code? Open in Web Editor NEW
906.0 906.0 311.0 956 KB

pure-python ECDSA signature/verification and ECDH key agreement

License: Other

Python 99.79% Shell 0.17% PLpgSQL 0.04%
cryptography digital-signatures ecdh ecdsa elliptic-curves python

python-ecdsa's Introduction

Build Status Read the Docs Coverage Status Code Climate

tlsfuzzer

tlsfuzzer is a test suite for SSLv2, SSLv3, TLS 1.0, TLS 1.1, TLS 1.2, and TLS 1.3 implementations. It's in early stages of development, so there are no API stability guarantees. While it uses fuzzing techniques for testing (randomisation of passed in inputs), the scripts are generally written in a way that verifies correct error handling: unlike typical fuzzers it doesn't check only that the system under test didn't crash, it checks that it returned correct error messages.

You can find ready-to-use scripts testing for many vulnerabilities ( ROBOT, DROWN, etc.) and general standards conformity (RFC 5246, RFC 7627, RFC 7905, etc.) in the scripts/ directory.

Dependencies

You'll need:

  • Python 2.6 or later or Python 3.6 or later
  • tlslite-ng 0.8.0-beta1 or later (note that tlslite will not work and they conflict with each other)
  • ecdsa python module (dependency of tlslite-ng, should get installed automatically with it), use at least version 0.15 for optimal performance

Optionally, to make cryptographic calculations significantly faster, you may want to install the following libraries (see tlslite-ng and python-ecdsa README files for details):

  • m2crypto
  • gmpy

To get pip (if your python installation doesn't already have it) download get-pip.py and run (or see USAGE.md for alternative configuration that does not require installation of packages):

python get-pip.py

Then install tlslite-ng:

pip install --pre tlslite-ng

(Use --upgrade --pre if you did install it before)

Download the tlsfuzzer:

git clone https://github.com/tlsfuzzer/tlsfuzzer.git

Usage

After all dependencies are installed, make sure:

  • you're in the directory of the project (after git clone just cd tlsfuzzer)
  • the server you want to test is running on the same computer (localhost)
  • the server is listening on port 4433
  • and the server will answer with data to HTTP queries (answer with valid HTTP responses is optional)

Then you can run one of the tests in scripts directory, like so:

PYTHONPATH=. python scripts/test-invalid-compression-methods.py

If test has additional requirements, it will output them to console. No errors printed means that all expecations were met (so for tests with bad data the server rejected our messages).

All scripts also accept --help to print the help message (specification of all the options given script supports), -h to specify the hostname or IP address of the server-to-be-tested and -p to specify the port of the service to be tested.

See USAGE.md for more info and how to interpret errors and failures reported by scripts.

You can find mode detailed documentation for the project at tlsfuzzer.readthedocs.io.

Using tlsfuzzer to test for timing side-channel attacks (Lucky13, padding oracle attacks and timing-based Bleichenbacher oracle) is described in the TIMING.md document.

Server under test configuration

In general, the server under test requires just a RSA certificate, you can create it using the following OpenSSL command:

openssl req -x509 -newkey rsa -keyout localhost.key -out localhost.crt -subj \
/CN=localhost -nodes -batch

Note: tlsfuzzer verifies only TLS level behaviour, it does not perform any checks on the certificate (like hostname validation, CA signatures or key usage). It does however verify if the signatures made on TLS message by the server (like in Server Key Exchange or Certificiate Verify message) match the certificate sent by the server.

More detailed instructions, including how to build the different frameworks from source, are available in the Server setup wiki page.

Example server configurations:

OpenSSL

To test OpenSSL, it's sufficient to pass an extra -www option to a typical s_server command line:

openssl s_server -key localhost.key -cert localhost.crt -www

GnuTLS

To test GnuTLS server, you need to tell it to behave as an HTTP server and additionally, to not ask for client certificates:

gnutls-serv --http -p 4433 --x509keyfile localhost.key --x509certfile \
localhost.crt --disable-client-cert

NSS

To test the Mozilla NSS library server, you first need to create a database with server certificate:

mkdir nssdb
certutil -N -d sql:nssdb --empty-password
openssl pkcs12 -export -passout pass: -out localhost.p12 -inkey localhost.key \
-in localhost.crt -name localhost
pk12util -i localhost.p12 -d sql:nssdb -W ''

Finally, start the server with support for TLSv1.0 and later protocols, DHE ciphers and with the above certificate:

selfserv -d sql:./nssdb -p 4433 -V tls1.0: -H 1 -n localhost

Advanced configuration

More advanced and complex configurations as well as description how to compile the above servers from source is available on the wiki page Server setup.

Contributing

See the CONTRIBUTING.md document for description how to set up your development environment, sanity check the changes and requirements the changes need to follow.

You may also want to read the VISION.md to learn more about the planned scope of the project.

Contributors are expected to follow the project's CODE OF CONDUCT when interacting with other members of the community.

python-ecdsa's People

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

python-ecdsa's Issues

Explicit curve format support

Why does this not work, I used the exact same commands as in the openssl example. It's a secp224r1 curve.

-----BEGIN PUBLIC KEY-----
MIIBKjCB6wYHKoZIzj0CATCB3wIBATAoBgcqhkjOPQEBAh0A////////////////
/////wAAAAAAAAAAAAAAATBTBBz////////////////////+///////////////+
BBy0BQqFDASzq/VBMlZQRLC317/YuicLOUMjVf+0AxUAvXE0R5nVx/zcRbWfo7mr
j2qUi8UEOQS3Dgy9a7S/fzITkLlKA8HTVsIRIjQygNYRXB0hvTdjiLX3I/tMIt/m
zUN1oFoHR2RE1YGZhQB+NAIdAP//////////////////FqLguPA+E90pRVxcKj0C
AQEDOgAEdJYkwBFKz9nru4MVvMeD4DE9KuLx/tMxUOYKZFFMBHxstBpzCjO9+PTu
sOegeFgd/zM7xayysyM=
-----END PUBLIC KEY-----

vk = VerifyingKey.from_pem(open(config['public_key']).read()) yields:

Traceback (most recent call last):
  File "./verify_signature.py", line 83, in <module>
    verifySignature('109.230.215.208', 27145, 'v1:4:redsun:24-04-2018:MDwCHEP6WloptmfHX+ESBMpn38/hl1NJs4LfQtbX/BUCHGIhcUQbKKmNKMtk8/qvo1jPNpiEtwWbE9JZYA4=')
  File "./verify_signature.py", line 72, in verifySignature
    vk = VerifyingKey.from_pem(open(config['public_key']).read())
  File "/usr/local/lib/python3.4/dist-packages/ecdsa/keys.py", line 52, in from_pem
    return klass.from_der(der.unpem(string))
  File "/usr/local/lib/python3.4/dist-packages/ecdsa/keys.py", line 64, in from_der
    oid_curve, empty = der.remove_object(rest)
  File "/usr/local/lib/python3.4/dist-packages/ecdsa/der.py", line 82, in remove_object
    raise UnexpectedDER("wanted object (0x06), got 0x%02x" % n)
ecdsa.der.UnexpectedDER: wanted object (0x06), got 0x30

Edit: I was talking about these openssl commands: https://github.com/warner/python-ecdsa#openssl-compatibility

Error installing / testing on python 2.7.7 64bit on IBM AIX7

Hello,

I'm trying to put together a 64bit python installation and I have this issue when I try to build ecdsa:

#python setup.py build
Traceback (most recent call last):
  File "setup.py", line 5, in <module>
    from ecdsa.six import print_
  File "/tmp/python_modules/ecdsa-0.11/ecdsa/__init__.py", line 3, in <module>
    from .keys import SigningKey, VerifyingKey, BadSignatureError, BadDigestError
  File "/tmp/python_modules/ecdsa-0.11/ecdsa/keys.py", line 3, in <module>
    from . import ecdsa
  File "/tmp/python_modules/ecdsa-0.11/ecdsa/ecdsa.py", line 218, in <module>
    generator_192 = ellipticcurve.Point( curve_192, _Gx, _Gy, _r )
  File "/tmp/python_modules/ecdsa-0.11/ecdsa/ellipticcurve.py", line 73, in __init__
    if self.__curve: assert self.__curve.contains_point( x, y )
AssertionError
#

Tests are not starting:

#python ecdsa/numbertheory.py
Traceback (most recent call last):
  File "ecdsa/numbertheory.py", line 14, in <module>
    from .six import print_, integer_types
ValueError: Attempted relative import in non-package
#

#python ecdsa/ellipticcurve.py
Traceback (most recent call last):
  File "ecdsa/ellipticcurve.py", line 37, in <module>
    from .six import print_
ValueError: Attempted relative import in non-package
#

#python ecdsa/ecdsa.py
Traceback (most recent call last):
  File "ecdsa/ecdsa.py", line 56, in <module>
    from .six import int2byte, b, print_
ValueError: Attempted relative import in non-package
#

#python ecdsa/test_pyecdsa.py
Traceback (most recent call last):
  File "ecdsa/test_pyecdsa.py", line 11, in <module>
    from .six import b, print_, binary_type
ValueError: Attempted relative import in non-package
#

=================================
#python
Python 2.7.7 (default, Jun 18 2014, 09:32:14) [C] on aix7
Type "help", "copyright", "credits" or "license" for more information.
>>>

=================================

My installed modules:
ANSI asyncore imageop setup
BaseHTTPServer atexit imaplib sgmllib
Bastion audiodev imghdr sha
CGIHTTPServer audioop imp shelve
Canvas base64 importlib shlex
ConfigParser bdb imputil shutil
Cookie binascii inspect signal
Crypto binhex io site
Dialog bisect itertools six
DocXMLRPCServer bsddb json smtpd
FSM bz2 keyword smtplib
FileDialog cPickle lib2to3 sndhdr
FixTk cProfile linecache socket
HTMLParser cStringIO locale sqlite3
IN calendar logging sre
MimeWriter cgi macpath sre_compile
Queue cgitb macurl2path sre_constants
ScrolledText chunk mailbox sre_parse
SimpleDialog cmath mailcap ssl
SimpleHTTPServer cmd markupbase stat
SimpleXMLRPCServer code marshal statvfs
SocketServer codecs math string
StringIO codeop md5 stringold
Tix collections mhlib stringprep
Tkconstants colorsys mimetools strop
Tkdnd commands mimetypes struct
Tkinter compileall mimify subprocess
UserDict compiler mmap sunau
UserList contextlib modulefinder sunaudio
UserString cookielib multifile symbol
_LWPCookieJar copy multiprocessing symtable
_MozillaCookieJar copy_reg mutex sys
builtin crypt netrc sysconfig
future csv new syslog
_abcoll ctypes nis tabnanny
_ast curses nntplib tarfile
_bisect cx_Oracle ntpath telnetlib
_bsddb datetime nturl2path tempfile
_codecs dbhash numbers termios
_codecs_cn dbm opcode test
_codecs_hk decimal operator textwrap
_codecs_iso2022 difflib optparse this
_codecs_jp dircache os thread
_codecs_kr dis os2emxpath threading
_codecs_tw distutils paramiko time
_collections dl parser timeit
_csv doctest pdb tkColorChooser
_ctypes_test dumbdbm pexpect tkCommonDialog
_curses dummy_thread pickle tkFileDialog
_elementtree dummy_threading pickletools tkFont
_functools ecdsa pipes tkMessageBox
_hashlib email pkgutil tkSimpleDialog
_heapq encodings platform toaiff
_hotshot errno plistlib token
_io exceptions popen2 tokenize
_json fcntl poplib trace
_locale fdpexpect posix traceback
_lsprof filecmp posixfile ttk
_multibytecodec fileinput posixpath tty
_multiprocessing fnmatch pprint turtle
_osx_support formatter profile types
_pyio fpformat pstats unicodedata
_random fractions pty unittest
_socket ftplib pwd urllib
_sqlite3 functools pxssh urllib2
_sre future_builtins py_compile urlparse
_ssl gc pyclbr user
_strptime gdbm pydoc uu
_struct genericpath pydoc_data uuid
_symtable getopt pyexpat warnings
_sysconfigdata getpass quopri wave
_testcapi gettext random weakref
_threading_local glob re webbrowser
_warnings grp repr whichdb
_weakref gzip resource wsgiref
_weakrefset hashlib rexec xdrlib
abc heapq rfc822 xml
aifc hmac rlcompleter xmllib
antigravity hotshot robotparser xmlrpclib
anydbm htmlentitydefs runpy xxsubtype
argparse htmllib sched zipfile
array httplib screen zipimport
ast idlelib select zlib
asynchat ihooks sets

Thank you in advance!

porting implementation to java

Loving this library managed to get the implementation to work. I wanted to do some porting for a java application, does anyone know the equivalent of this call for signing with der encoding in java?

sk.sign(msg, hashfunc=hashlib.sha1, sigencode=ecdsa.util.sigencode_der)

ecdsa.__version__ returns UNKNOWN for pypi package

Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ecdsa
>>> ecdsa.__version__
'UNKNOWN'

presumably there's some build step missing before submission to pypi..?

test_to_openssl_ failures on Fedora 21

All of the test_to_openssl_* tests fail for me on Fedora 21 (and my CentOS 6.7 box as well).

======================================================================
ERROR: test_to_openssl_secp256k1 (ecdsa.test_pyecdsa.OpenSSL)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/svn/packages/python-ecdsa/trunk/sources/python-ecdsa-python-ecdsa-0.13/ecdsa/test_pyecdsa.py", line 384, in test_to_openssl_secp256k1
    self.do_test_to_openssl(SECP256k1)
  File "/svn/packages/python-ecdsa/trunk/sources/python-ecdsa-python-ecdsa-0.13/ecdsa/test_pyecdsa.py", line 408, in do_test_to_openssl
    run_openssl("dgst %s -verify t/pubkey.der -keyform DER -signature t/data.sig t/data.txt" % mdarg)
  File "/svn/packages/python-ecdsa/trunk/sources/python-ecdsa-python-ecdsa-0.13/ecdsa/test_pyecdsa.py", line 34, in run_openssl
    (OPENSSL, cmd, p.returncode, stdout))
SubprocessError: cmd 'openssl dgst -SHA1 -verify t/pubkey.der -keyform DER -signature t/data.sig t/data.txt' failed: rc=1, stdout/err was unable to load key file

Is there a workaround? I'm trying to package this as an RPM and would really like to run the tests as part of the %check portion of the RPM build process.

coverage is broken

running tox -e coverage doesn't report the test coverage:

GLOB sdist-make: /home/tomato/workspace/python-ecdsa/setup.py                  
coverage inst-nodeps: /home/tomato/workspace/python-ecdsa/.tox/dist/ecdsa-0.13+33.g2e6691c.zip
coverage installed: attrs==17.4.0,coverage==4.5.1,ecdsa==0.13+33.g2e6691c,more-itertools==4.1.0,pluggy==0.6.0,py==1.5.3,pytest==3.5.0,six==1.11.0
coverage runtests: PYTHONHASHSEED='3926119460'
coverage runtests: commands[0] | coverage run -m pytest src/ecdsa
============================= test session starts ==============================
platform linux -- Python 3.6.4, pytest-3.5.0, py-1.5.3, pluggy-0.6.0
rootdir: /home/tomato/workspace/python-ecdsa, inifile:
collected 50 items                                                             

src/ecdsa/test_ecdsa.py .                                                [  2%]
src/ecdsa/test_ellipticcurve.py .                                        [  4%]
src/ecdsa/test_numbertheory.py .                                         [  6%]
src/ecdsa/test_pyecdsa.py .............................................. [ 98%]
.                                                                        [100%]

========================== 50 passed in 12.07 seconds ==========================
Coverage.py warning: No data was collected. (no-data-collected)
___________________________________ summary ____________________________________
  coverage: commands succeeded
  congratulations :)

py3.2 incompatibility

The new rfc6979 tests fail on py3.2:

 File "/home/travis/build/warner/python-ecdsa/ecdsa/test_pyecdsa.py", line 571, in test_1
hsh = unhexlify("AF2BDBE1AA9B6EC1E2ADE1D694F41FC71A831D0268E9891562113D8A62ADD1BF"),
TypeError: 'str' does not support the buffer interface

and some others.

Looks pretty shallow.

"bin()" breaks py2.5 compatibility

Looks like we missed a py2.5 compatibility issue with the recent deterministic-signature PR. @slush0, do you know of any simple py2.5-compatible replacement for bin() as used in rfc6979.bit_length()?

Mistake in README.md

In the first Example, under Usage, is the line:

assert sk.verify(signature, "message")

But it should be:

assert vk.verify(signature, "message")

Import key from hex

Hello, I know that I can import an ECDSA Key from PEM:

from ecdsa import SigningKey, SECP256k1 #secp256k1: the one bitcoin uses

sk = SigningKey.from_pem("""-----BEGIN EC PRIVATE KEY----- ............................. -----END EC PRIVATE KEY-----""")

But, how do I import a private key (or public key) from hex?
For example, a hex private key in secp256k1:

0xDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF

Issue with test execution

Hello,

I want to include this package in a larger script that checks security issues. I'm having trouble with running it (stand-alone) - when I run python setup.py test I get the following output:
running test
running egg_info
writing dependency_links to src\ecdsa.egg-info\dependency_links.txt
writing src\ecdsa.egg-info\PKG-INFO
writing requirements to src\ecdsa.egg-info\requires.txt
writing top-level names to src\ecdsa.egg-info\top_level.txt
reading manifest file 'src\ecdsa.egg-info\SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching 'ecdsa_version.py'
writing manifest file 'src\ecdsa.egg-info\SOURCES.txt'
running build_ext


Ran 0 tests in 0.000s

OK

What am I missing? Why aren't the tests running and what does the warning mean?
I'm using Python 3.5 on Windows 7.

Thank you

How do I get the public key of the signer?

Can I explicitly display the public key so that I know who signed the message?
Currently, my solution feels like it is relying too much on the internals rather than an api for displaying the public key

publicKey = SigningKey.generate().get_verifying_key()
"".join(publicKey.to_pem().decode().split("\n")[1:-2])

Python 3: SigningKey.to_string() return a bytes object instead of a string

>>> import ecdsa
>>> type(ecdsa.SigningKey.generate().to_string())
<class 'bytes'>

Is this normal?

Example of how to get a string for someone that need to display a key:

>>> import codecs
>>> sk = ecdsa.SigningKey.generate().to_string()
>>> codecs.encode(sk, 'hex').decode("utf-8")  # maybe there is a simpler way
'5d9411d69b0286f51d5ef52300dcd02b617d843877c8a881'

add script to produce benchmark/perf data

In README.md, I have a section named "Speed" that provides timing data for creating/signing/verifying with various curves. I should dig up the script I used to produce that and include a copy in the source tree, so setup.py bench will produce the same table on your local machine.

Also, we should add similar data for the recently-added secp256k1 curve.

need help with maintenance

I'm not doing a great job maintaining this package: I'm horribly behind on landing PRs and responding to issues. I'm not using it for any of my work or personal projects, which doesn't help. And there are a surprisingly high number of downloads on pypi.. I think it might be a dependency of some JWT library that must be a dependency of something pretty popular, but I haven't done the legwork to figure out what. So it deserves better than what I'm giving it.

Could anyone lend a hand? I'd like to add two or three folks as "Contributors" who can review/land patches. Eventually I want to hand off ownership to someone else. Preferably folks who use it on a regular basis and have a sense of how/where it's being used downstream, so we can be sure to not break anything important to our userbase.

OpenSSL signatures no longer compatible with ecdsa RAW format (README outdated)

Hi,

While trying to convert from ecdsa to python cryptography (which wraps OpenSSL) I discovered that the current iteration of OpenSSL (libssl 1.0.2g+) returns a DER formatted signature value instead of a raw pair of 32octect numbers. (FWIW: the signature appears to be a Sequence of NamedTypes containing Integers)

If, say, a JWT that has a signature from a direct OpenSSL wrapper that is unaware of this is attempted to be run through ecdsa, it'll fail due to the signature length check*. Folks who wish to use this library should check signature length != 64 and perform whatever transmogrification required to get the raw pair of key values that ecdsa requires.

Also: might want to update the examples in the "OpenSSL Compatibility" section of the README to reflect this.

I'm going to try to follow up with other library owners in the chain to make sure that they're aware or at least comment about this problem lest others develop the same drinking habit I seem to have.

*really wish that some of these returned more meaningful errors than "AssertionError(71, 64)"

Please do not bundle `six`

Is there any reason to bundle the six module? If it is only convenience for the user please remove it and add an install_requires=['six'] to setup.py.

Bundling 3rd packages leads to duplicate code in a system and may lead to maintenance problems. And in your case not doing this saves you the work of updating the packages regularly :-)

RFC6979 proper handling of bad r or s.

https://github.com/warner/python-ecdsa/blob/master/ecdsa/ecdsa.py#L147

Currently deterministic signing will bring the code to this point and fail in the (EXTREMELY) unlikely event of r == 0 or s == 0.

However, RFC 6979 states that:

If that value of k is within the [1,q-1] range, and is
suitable for DSA or ECDSA (i.e., it results in an r value
that is not 0
; see Section 3.4), then the generation of k is
finished. The obtained value of k is used in DSA or ECDSA.
Otherwise, compute:

So if the user is using keys.SigningKey.sign_deterministic() and ecdsa.Private_key.sign() returns an invalid r or s, the Step H loop should repeat once more.

Bitcore, for example, uses an int called badrs in the signing function
https://github.com/bitpay/bitcore/blob/master/lib/crypto/ecdsa.js#L204

In the event that r or s is 0, badrs is incremented, and they pass that int to the RFC6979 function to force a loop here:
https://github.com/bitpay/bitcore/blob/master/lib/crypto/ecdsa.js#L100

This is for efficiency, as adding a r and s value check would add an extra calculation of r and s.

However, I think it would be trivial to just add a function checking the r and s value in the current check here, and I don't think it is that much of a computational waste.
https://github.com/warner/python-ecdsa/blob/master/ecdsa/rfc6979.py#L99

Seeing as the ecdsa.Private_key.sign() does not necessarily use keys.SigningKey.sign_deterministic() it would be better to avoid a method like the badrs and create a new function for use in line 99 in rfc6979.py to check if r or s will be 0.

Maybe instead of only passing the curve order to generate_k(), you could pass the entire curve object, and pass along that object to the r and s check function. (which will undoubtedly need the generator, order, etc...)

It's a bit nit-picky, but still. It's written in the RFC.

Thanks in advanced for your thoughts.

I refrained from a pull request, as I first wanted to ask how you would plan to attack this problem.

Tampering with .pem file doesn't make from_pem() fail

Original key:

-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIGvsrpXh8m/E9bj1dq/0o1aBPQVAFJQ6Pzusx685URE0oAoGCCqGSM49
AwEHoUQDQgAEaHYrUu/oFKIXN457GH+8IOuv6OIPBRLqoHjaEKM0wIzJZ0lhfO/A
53hKGjKEjYT3VNTQ3Zq1YB3o5QSQMP/LRg==
-----END EC PRIVATE KEY-----

Changed a single char:

-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIGvsrpXh8m/E9bj1dq/0o1aBPQVAFJQ6Pzusx685URE0oAoGCCqGSM49
AwEHoUQDQgAEaHYrUu/oFKIXN457GH+8IOuv6OIPBRLqoHjaEKM0wIzJZ0lhfO/A
53hKGjKEjYT3VNTQ3Zq1YB3o5QSQMS/LRg==
-----END EC PRIVATE KEY-----

But it still loads fine instead of failing to load. OpenSSL does detect the error however.

VerifyingKey has no attribute default_hashfunc

I receive an error when trying to verify a signature:

  File "/nix/store/6y0dcram1jil24ckidcpr34sw0qjzm19-python3.6-ecdsa-0.13/lib/python3.6/site-packages/ecdsa/keys.py", line 99, in verify
    hashfunc = hashfunc or self.default_hashfunc
AttributeError: 'VerifyingKey' object has no attribute 'default_hashfunc'

On this snippet, sender.verify(self._signature, dumps(self.header)) with sender being <class 'ecdsa.keys.VerifyingKey'>

I'm sending this object over the network with jsonpickle, maybe this destroys inner structure ?

unit test doesn't run

$ python --version
Python 3.6.4
$ python setup.py test
running test
running egg_info
writing src/ecdsa.egg-info/PKG-INFO
writing dependency_links to src/ecdsa.egg-info/dependency_links.txt
writing requirements to src/ecdsa.egg-info/requires.txt
writing top-level names to src/ecdsa.egg-info/top_level.txt
reading manifest file 'src/ecdsa.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching 'ecdsa/_version.py'
writing manifest file 'src/ecdsa.egg-info/SOURCES.txt'
running build_ext

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

add Brainpool curves

Zooko points out that many folks don't like the NIST curves because they don't come with a proof of being generated randomly. The Brainpool curves do. http://cryptopp.svn.sourceforge.net/viewvc/cryptopp/trunk/c5/eccrypto.cpp?r1=441&r2=440&pathrev=441 and http://cryptopp.svn.sourceforge.net/viewvc/cryptopp/trunk/c5/oids.h?r1=441&r2=440&pathrev=441 are where Brainpool support was added to Crypto++.

If OpenSSL supports these curves (so we can do interop testing), I'm happy to add them to python-ecdsa.

Incompatibility (point encoding)

I am trying to do message signature authentication over different systems, e.g. JavaScript (http://kjur.github.io/jsrsasign/sample-ecdsa.html) with python-ecdsa. OpenSSL is the baseline for the tests and the JavaScript library is very close to produce the same results. I was expecting the same from python-ecdsa. Unless I am doing something wrong, the public key is always different in size and thus the signature validation fails.

Those are the steps I am doing:
1.) First I am deciding which curve to use, in this case it is prime256v1.
2.) Then I generate the private and public keys in Python by doing this:

privateKey = SigningKey.generate(curve=NIST256p)
publicKey = privateKey.get_verifying_key()

3.) That results in a key pair which the hex representation looks like this:

privateKey = d1d801d3166dc5b7acc2651fc1b901a6f5fc8542851a505e7b76af4c4302a85a
publicKey = 88d1b89b5e1f1a7eeb2007c31416ce743b4e3c23e261ca8b325e746938b218baec1c9d6120ffe91fe8a93d81cc55aa1cb4c995886dba91efd82ac4497cd9abf9

4.) Applying the key pair to the JavaScript testing environment, I can sign the message, but when verifying it, it says the signature is invalid.

When I generate the keys using the JavaScript implementation, I get the following as an example:

privateKey = 7e4cc8d77d6109ac01f47d530945d828673e0809ba3953b14f6fc7558ab6f670
publicKey = 0499dc501f2fe17cc8512a689498d7e1dd4c717d78db8d6a8b40c4bfeed50c01f6120ab2d09eccf741baf04f8f1451bcc99be8d48d0769837d18be934471dc1a1e

As you can see, the privateKey's are both of same size, but the publicKey's are different in size.

To determine if the problem is the JavaScript implementation, I followed the same steps using OpenSSL:

openssl ecparam -genkey -name prime256v1 -out k.pem
openssl ec -in k.pem -noout -text

Private-Key: (256 bit)
priv:
60:54:0c:84:8e:ec:de:b0:df:e6:2e:02:96:f3:d3:
3b:40:e3:fe:14:e8:f8:88:97:5c:bd:a3:2c:3e:5a:
cb:57
pub:
04:c4:9a:71:9d:93:fe:7a:24:c1:fd:ce:c2:28:6a:
a0:4d:2f:83:c1:3b:dd:9c:ab:5d:a6:56:b7:2e:ee:
c3:6b:a2:36:3d:51:2c:66:c3:34:6d:f8:4e:02:94:
8f:59:52:7b:64:30:fb:b8:be:f6:71:45:44:61:31:
32:19:81:93:d6

Once again, the publicKey is different in size from the one from python-ecdsa, but it is the same size as the JavaScript implementation. This leads me to believe that either I am doing something wrong, or there is a problem within the python-ecdsa implementation.

For compatibility and interoperability, it is required that all systems produce valid key pairs which are exchangeable.

Maybe someone can shed some light on this issue?

Typo in the README

Line 200 of the README has a small type for the key name.

openssl dgst -ecdsa-with-SHA1 -prverify vk.pem -signature data.sig data
should read:
openssl dgst -ecdsa-with-SHA1 -prverify sk.pem -signature data.sig data

Sorry for the trivial change

Loading veryfying key from pem or der always defaults to sha1 hash function

Hi,
first I want to say that your package is great :) Helped me a lot while testing ecdsa on my device.
I have noticed that when you read the verifying key from pem or der format you can't specify hashing function and it defaults to sha1. I think it would be great to have it as a parameter as public key does not specify it.
Maybe I could help you with contribution?

Add support for 112, 128, and 160 curves

I would like to use python-ecdsa to produce keys that are compatible with the ellipticlicense project. This project uses 112, 128, and 160 bit curves to produce license keys that, while less secure, are smaller and thus more suitable for that use case.

Would there be any interest from the developers here to add 112, 128, and/or 160 bit curves to python-ecdsa?

Why signature always has the same lenght?

Hi. We generate NIST256p via lib and there is some question.
Why signature always has the same lang? In other languages not. Also for example you generate sign in other language and len > 64 bytes. In this case lib crashes

Testing Commands in README.md

Tests describe running the command:

python ecdsa/test_pyecdsa.py

However, I received an error:

Traceback (most recent call last):
  File "test_pyecdsa.py", line 11, in <module>
    from .six import b, print_, binary_type
ValueError: Attempted relative import in non-package

It worked when running the command:

python -m ecdsa.test_pyecdsa

SECP256k1 curve needed to be included in __init__.py

On the "ecdsa/init.py" file, currently the SECP256k1 is not imported with the other curves. Line 4 looks as follows:

from .curves import NIST192p, NIST224p, NIST256p, NIST384p, NIST521p

Modifying it to the following will allow SECP256k1 to be included like the remaining curves so that it can be easily used:

from .curves import NIST192p, NIST224p, NIST256p, NIST384p, NIST521p, SECP256k1

test failures against openssl-1.0.0a

The openssl-compatibility tests in ecdsa-0.6 are failing on my OS-X 10.6 (snow leopard) box with openssl-1.0.0a (installed from Fink). They pass on my other OS-X and linux boxes (with openssl-0.9.8something).

one sample message is:

ERROR: test_from_openssl_nist192p (__main__.OpenSSL)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "ecdsa/test_pyecdsa.py", line 267, in test_from_openssl_nist192p
    return self.do_test_from_openssl(NIST192p, "prime192v1")
  File "ecdsa/test_pyecdsa.py", line 285, in do_test_from_openssl
    run("openssl dgst -ecdsa-with-SHA1 -sign t/privkey.pem -out t/data.sig t/data.txt")
  File "ecdsa/test_pyecdsa.py", line 28, in run
    (cmd, p.returncode, stdout))
SubprocessError: cmd 'openssl dgst -ecdsa-with-SHA1 -sign t/privkey.pem -out t/data.sig t/data.txt' failed: rc=1, stdout/err was Error setting context
140735073729660:error:100C508A:elliptic curve routines:PKEY_EC_CTRL:invalid digest type:ec_pmeth.c:229:

sk.sign() expects a bytes object?

The usage example in the README:

from ecdsa import SigningKey
sk = SigningKey.generate() # uses NIST192p
vk = sk.get_verifying_key()
signature = sk.sign("message")
assert vk.verify(signature, "message")

With python 3.5 this gives me:

in sign
    h = hashfunc(data).digest()
TypeError: Unicode-objects must be encoded before hashing

signature = sk.sign("message".encode('utf-8')) does work.

Is this expected behavior?

Very slow assert in VerifyingKey.from_string()

This line:
assert ecdsa.point_is_valid(curve.generator, x, y)
takes about 26ms to complete. With my ssh known hosts file has 182 ecdsa keys in, this line alone causes a paramiko client to spend almost five seconds before even connecting to to the server. As the known_hosts file is a in essence a database of trusted keys, I think it should be possible to skip this assert in this case.

the best way to put 64 len string to 32 len string so it can produce public key

Hi guys,

I am following instructions on bitcoin site, how to create public wallet. First step is ofcourse to produce the public key with ecdsa.

in tutorial they use following private_key = '18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725'

and my python code is:

from ecdsa import SigningKey, SECP256k1


a = '18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725'


key = SigningKey.from_string(a, curve=SECP256k1)
pub_key = g.get_verifying_key()

I receive this error:
assert len(string) == curve.baselen, (len(string), curve.baselen)
builtins.AssertionError: (64, 32)

How could i fix this?

Thank you very much!

python3 compatibility

I've been playing with making the jetpack SDK (http://github.com/mozilla/addon-sdk) work under python 3, and ran into a number of python-ecdsa incompatibilities (after running it through 2to3). I'm still working through them, but replacing all the / with // in ellipticcurve.py was a good start.

SigningKey.sign() externally computed hash (no hashing on its own)

It seems to be lack of consequence between README.md and SigningKey.sign() documentation. In README.md:
The hashfunc= argument to sk.sign() and vk.verify() is used to turn an arbitrary string into fixed-length digest, which is then turned into a number that ECDSA can sign, and both sign and verify must use the same approach. The default value is hashlib.sha1

On the other hand help (SigningKey) says the hashfunc is by default None:
sign(self, data, entropy=None, hashfunc=None,

What is the reality? Is passing None to hashfunc really causes that no hash will be computed and data provided to sign() will be signed directly?

pypy3 support

Hello,
I didn't see pypy3 listed in the supported implementations, nor does it appear to be included in your travis.yml test suite. Seems to be working on my end as is, for 0.11. Passed tests on a Gentoo amd64 system.

how to import private key

If I have a private key string generated from a different library/programming language how would I import it to python-ecdsa and to sign it?

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.