├── .gitignore ├── README.md ├── __init__.py ├── asnhelper.py ├── bignum.py ├── curve.py ├── echelper.py ├── keypair.py ├── point.py ├── pyelliptic ├── LICENSE ├── README.md ├── __init__.py └── openssl.py └── sample_lsag.py /.gitignore: -------------------------------------------------------------------------------- 1 | **pyc 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Py-EC 2 | 3 | A wrapper of the OpenSSL elliptic curve functions for easy Python manipulation. 4 | 5 | In Python, dealing directly with the OpenSSL library (through [PyElliptic](https://github.com/yann2192/pyelliptic)) easily becomes a hassle with the use of C pointers and string buffers. 6 | 7 | To make things easier, I decided to make a wrapper for PyElliptic to make the manipulation of elliptic curves and points more Pythonic. 8 | 9 | The wrapper has been tested with all recommended SEC curves (`secp192k1`, `secp192r1`, `secp224k1`, `secp224r1`, `secp256k1`, `secp256r1`, `secp384r1`, `secp521r1`, `sect163k1`, `sect163r1`, `sect163r2`, `sect233k1`, `sect233r1`, `sect239k1`, `sect283k1`, `sect283r1`, `sect409k1`, `sect409r1`, `sect571k1` and `sect571r1`). 10 | 11 | Especially point addition and multiplication is way easier, as the following console example usage shows: 12 | 13 | ## Example use 14 | 15 | ``` 16 | >>> from curve import Curve 17 | >>> c = Curve( 'secp256k1' ) 18 | 19 | >>> c 20 | Curve 21 | 22 | >>> c.p 23 | 115792089237316195423570985008687907853269984665640564039457584007908834671663L 24 | 25 | >>> c.a 26 | 0 27 | 28 | >>> c.b 29 | 7 30 | 31 | >>> c.order 32 | 115792089237316195423570985008687907852837564279074904382605163141518161494337L 33 | 34 | >>> c.G 35 | Point<0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8> 36 | 37 | >>> c.G.x 38 | 55066263022277343669578718895168534326250603453777594175500187360389116729240L 39 | 40 | >>> c.G.y 41 | 32670510020758816978083085130507043184471273380659243275938904335757337482424L 42 | 43 | >>> 4 * c.G + (255 * c.G) 44 | Point<0xC2C80F844B70599812D625460F60340E3E6F36054A14546E6DC25D47376BEA9B, 0x86CA160D68F4D4E718B495B891D3B1B573B871A702B4CF6123ABD4483AA79C64> 45 | 46 | >>> from keypair import KeyPair 47 | >>> kp = KeyPair( c ) 48 | 49 | >>> kp 50 | KeyPair> 51 | 52 | >>> kp.private_key 53 | 36442418189203456142546292588071998273845228785350611568921618467649899682927L 54 | 55 | >>> kp.public_key 56 | Point<0x13FCF42341462150B8366F11659E396DF88D19F65D533CEEAC78C9EC6F94B45D, 0x18DDDF6DCA0C097FC0359E680BAED36403D77657ABE7F76E64E1B787D90C485A> 57 | ``` 58 | 59 | # API 60 | 61 | ## Curve 62 | 63 | ### Getting a curve instance 64 | A curve can be initialized in three ways; by its name, id or by a pointer to an OpenSSL `EC_GROUP` instance: 65 | 66 | 67 | ``` 68 | >>> from curve import Curve 69 | 70 | >>> Curve( curvename='secp256k1' ) 71 | Curve 72 | 73 | >>> Curve( curveid=714 ) 74 | Curve 75 | 76 | >>> from pyelliptic.openssl import OpenSSL 77 | >>> Curve( openssl_group=OpenSSL.EC_GROUP_new_by_curve_name( 714 ) ) 78 | Curve 79 | ``` 80 | 81 | ### Properties of a curve 82 | 83 | Depending on whether the curve is over a prime field, Fp, or a power-of-2 field, F2m, the curve has slightly different properties: 84 | 85 | * `prime_type`: Either `'prime'` or `'power-of-two'` 86 | * `G`: The base `Point` (or generator) of the curve. 87 | * `order`: The order of the curve (amount of elements) 88 | * `h`: The cofactor of the curve 89 | * `a`: The curve coefficient a 90 | * `b`: The curve coefficient b 91 | * `p` (Only Fp): The prime p specifying the field 92 | * `m` (Only F2m): The integer m specifying the field 93 | * `poly_coeffs` (Only F2m): The degrees of the polynomials specifying the field 94 | * `os_group`: A pointer to the underlying `EC_GROUP` instance. 95 | 96 | ``` 97 | >>> from curve import Curve 98 | >>> c1 = Curve( 'secp256k1' ) 99 | >>> c2 = Curve( 'sect239k1' ) 100 | 101 | >>> c1 102 | Curve 103 | >>> c2 104 | Curve 105 | 106 | >>> c1.field_type 107 | 'prime' 108 | >>> c2.field_type 109 | 'power-of-two' 110 | 111 | >>> c1.G 112 | Point<0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8> 113 | >>> c2.G 114 | Point<0x29A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC, 0x76310804F12E549BDB011C103089E73510ACB275FC312A5DC6B76553F0CA> 115 | 116 | >>> c1.order 117 | 115792089237316195423570985008687907852837564279074904382605163141518161494337L 118 | >>> c1.h 119 | 1 120 | >>> c1.a 121 | 0 122 | >>> c1.b 123 | 7 124 | 125 | >>> c1.p 126 | 115792089237316195423570985008687907853269984665640564039457584007908834671663L 127 | 128 | >>> c2.m 129 | 239 130 | >>> c2.poly_coeffs 131 | [158] 132 | ``` 133 | 134 | ## Point 135 | 136 | ### Getting a point instance 137 | You can get the base point from the `G` property of a curve as described above: 138 | 139 | ``` 140 | >>> from curve import Curve 141 | >>> Curve( 'secp256k1' ).G 142 | Point<0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8> 143 | ``` 144 | 145 | You can also create a point on a curve from either (1) the x and y coordinates of the point or (2) by a pointer to an OpenSSL `EC_POINT` instance: 146 | 147 | ``` 148 | >>> from curve import Curve 149 | >>> from point import Point 150 | >>> c = Curve( 'secp256k1' ) 151 | 152 | >>> Point( c, x=255, y=255 ) # Invalid coordinates, only a demonstration 153 | Point<0xFF, 0xFF> 154 | 155 | >>> from pyelliptic.openssl import OpenSSL 156 | >>> Point( c, openssl_point=OpenSSL.EC_POINT_new( c.os_group ) ) 157 | Point<0x0, 0x0> 158 | ``` 159 | 160 | Finally, you can hash a string directly onto a curve (using the 'try-and-increment' method for finding points close to a certain x coordinate): 161 | 162 | ``` 163 | >>> from curve import Curve 164 | >>> c = Curve( 'secp256k1' ) 165 | 166 | >>> c.hash_to_point( 'somestring' ) 167 | Point<0xE4998BB769D5AF19526738527E13ECF753F5CC7AA60DD0ADF94BB0A248CF577A, 0x79FCD45DD59999C5D916FB31C0F023B4A1A1BCD63F11FD3D3E31D5C5E7D79C1D> 168 | 169 | >>> c.hash_to_point( 'someotherstring' ) 170 | Point<0xB661EE62474532EF1C8EA78B1CE3634E2EEC06B8E256E46A5CE25DF0FFABF332, 0x1DAB745A01B745CA9BF276D8E990E8EF11CFA954C5956DF9BF4C0684FABB00A6> 171 | ``` 172 | 173 | ### Performing arithmetics 174 | Point addition and multiplication is intuitive: 175 | 176 | ``` 177 | >>> from curve import Curve 178 | >>> c = Curve( 'secp256k1' ) 179 | 180 | >>> c.G 181 | Point<0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8> 182 | 183 | >>> 2 * c.G 184 | Point<0xC6047F9441ED7D6D3045406E95C07CD85C778E4B8CEF3CA7ABAC09B95C709EE5, 0x1AE168FEA63DC339A3C58419466CEAEEF7F632653266D0E1236431A950CFE52A> 185 | 186 | >>> c.G + c.G 187 | Point<0xC6047F9441ED7D6D3045406E95C07CD85C778E4B8CEF3CA7ABAC09B95C709EE5, 0x1AE168FEA63DC339A3C58419466CEAEEF7F632653266D0E1236431A950CFE52A> 188 | 189 | >>> ( 5 * c.G ) + ( 256 * c.G ) 190 | Point<0x9CF606744CF4B5F3FDF989D3F19FB2652D00CFE1D5FCD692A323CE11A28E7553, 0x8147CBF7B973FCC15B57B6A3CFAD6863EDD0F30E3C45B85DC300C513C247759D> 191 | ``` 192 | 193 | ### Properties of a point 194 | 195 | * `x`: The x coordinate 196 | * `y`: The y coordinate 197 | * `os_point`: A pointer to the underlying `EC_POINT` instance. 198 | 199 | ## Key pair 200 | A key pair is a structure that contains a private and a public key for a given curve. 201 | 202 | ### Getting a key pair instance 203 | A key pair for a curve can be generated randomly or by providing a private key: 204 | 205 | ``` 206 | >>> from curve import Curve 207 | >>> from keypair import KeyPair 208 | >>> c = Curve( 'secp256k1' ) 209 | 210 | >>> KeyPair( c ) # Random key pair 211 | KeyPair> 212 | 213 | >>> KeyPair( c, private_key=12345 ) 214 | KeyPair> 215 | ``` 216 | 217 | Alternatively, you can provide a pointer to an OpenSSL `EC_KEY` instance: 218 | 219 | ``` 220 | >>> from curve import Curve 221 | >>> from keypair import KeyPair 222 | >>> from pyelliptic.openssl import OpenSSL 223 | >>> c = Curve( 'secp256k1' ) 224 | >>> k = OpenSSL.EC_KEY_new_by_curve_name( 714 ) 225 | >>> OpenSSL.EC_KEY_generate_key( k ) 226 | 1 227 | 228 | >>> KeyPair( c, os_key=k ) 229 | KeyPair> 231 | ``` 232 | 233 | ### Properties of a key pair 234 | 235 | * `private_key`: The private key (an integer) 236 | * `public_key`: The public key (a `Point`) 237 | * `os_key`: A pointer to the underlying `EC_KEY` instance. 238 | 239 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '1.0' 2 | 3 | __all__ = [ 4 | 'ASNHelper', 5 | 'BigNum', 6 | 'Curve', 7 | 'ECHelper', 8 | 'KeyPair', 9 | 'Point' 10 | ] 11 | 12 | from asnhelper import ASNHelper 13 | from bignum import BigNum 14 | from curve import Curve 15 | from echelper import ECHelper 16 | from keypair import KeyPair 17 | from point import Point 18 | -------------------------------------------------------------------------------- /asnhelper.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (C) 2014 Jesper Borgstrup 4 | # ------------------------------------------------------------------- 5 | # Permission is hereby granted, free of charge, to any person 6 | # obtaining a copy of this software and associated documentation 7 | # files (the "Software"), to deal in the Software without restriction, 8 | # including without limitation the rights to use, copy, modify, merge, 9 | # publish, distribute, sublicense, and/or sell copies of the Software, 10 | # and to permit persons to whom the Software is furnished to do so, 11 | # subject to the following conditions: 12 | # 13 | # The above copyright notice and this permission notice shall be 14 | # included in all copies or substantial portions of the Software. 15 | # 16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 18 | # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 20 | # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 21 | # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | # DEALINGS IN THE SOFTWARE. 24 | 25 | class ASNHelper: 26 | CLASS_UNIVERSAL = 0 27 | CLASS_APPLICATION = 1 28 | CLASS_CONTEXT_SPECIFIC = 2 29 | CLASS_PRIVATE = 3 30 | 31 | PC_PRIMITIVE = 0 32 | PC_CONSTRUCTED = 1 33 | 34 | TAG_INTEGER = 0x02 35 | TAG_OCTET_STRING = 0x04 36 | TAG_OBJECT_IDENTIFIER = 0x06 37 | TAG_SEQUENCE = 0x10 38 | 39 | @staticmethod 40 | def consume(buf): 41 | while len( buf ) > 0: 42 | buf, (cls, pc, tag) = ASNHelper.consume_type( buf ) 43 | buf, length = ASNHelper.consume_length( buf ) 44 | data, buf = buf[:length], buf[length:] 45 | # print (cls, pc, tag, length) 46 | if tag == ASNHelper.TAG_INTEGER or tag == ASNHelper.TAG_OCTET_STRING: 47 | yield int( "".join( map( lambda x: "%X" % ord(x), data ) ), 16 ) 48 | elif tag == ASNHelper.TAG_OCTET_STRING: 49 | yield data 50 | elif tag == ASNHelper.TAG_OBJECT_IDENTIFIER: 51 | yield ".".join( map( lambda x: "%d" % ord(x), data ) ) 52 | elif tag == ASNHelper.TAG_SEQUENCE: 53 | yield tuple( [ x for x in ASNHelper.consume( data ) ] ) 54 | 55 | @staticmethod 56 | def consume_type(buf): 57 | type_octet, buf = ord(buf[0]), buf[1:] 58 | cls, type_octet = type_octet >> 6, type_octet & 0x3F 59 | pc, type_octet = type_octet >> 5, type_octet & 0x1F 60 | tag = type_octet 61 | return buf, (cls, pc, tag) 62 | 63 | @staticmethod 64 | def consume_length(buf): 65 | first_octet, buf = ord(buf[0]), buf[1:] 66 | long_form = first_octet & 0x80 == 0x80 67 | if not long_form: 68 | return buf, int(first_octet) 69 | else: 70 | octet_count = int(first_octet) - 0x80 71 | length_octets, buf = buf[:octet_count], buf[octet_count:] 72 | length = int( "".join( map( lambda x: "%X" % ord(x), length_octets )), 16 ) 73 | return buf, length 74 | 75 | -------------------------------------------------------------------------------- /bignum.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (C) 2014 Jesper Borgstrup 4 | # ------------------------------------------------------------------- 5 | # Permission is hereby granted, free of charge, to any person 6 | # obtaining a copy of this software and associated documentation 7 | # files (the "Software"), to deal in the Software without restriction, 8 | # including without limitation the rights to use, copy, modify, merge, 9 | # publish, distribute, sublicense, and/or sell copies of the Software, 10 | # and to permit persons to whom the Software is furnished to do so, 11 | # subject to the following conditions: 12 | # 13 | # The above copyright notice and this permission notice shall be 14 | # included in all copies or substantial portions of the Software. 15 | # 16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 18 | # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 20 | # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 21 | # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | # DEALINGS IN THE SOFTWARE. 24 | 25 | from pyelliptic.openssl import OpenSSL 26 | from echelper import ECHelper 27 | 28 | class BigNum: 29 | ''' 30 | classdocs 31 | ''' 32 | 33 | def __init__(self, os_bn=None,decval=None,binval=None): 34 | """ 35 | Constructs a new BN object 36 | and fills it with the value given. 37 | """ 38 | if os_bn is not None: 39 | self.bn = os_bn 40 | self.__created_bn = False 41 | else: 42 | self.bn = OpenSSL.BN_new() 43 | self.__created_bn = True 44 | if decval is None and binval is None: 45 | decval = 0 46 | 47 | if decval is not None: 48 | binval = ECHelper.int2bin( decval ) 49 | 50 | if binval is not None: 51 | OpenSSL.BN_bin2bn( binval, len( binval ), self.bn ) 52 | 53 | def get_value(self): 54 | binary = OpenSSL.malloc(0, OpenSSL.BN_num_bytes( self.bn ) ) 55 | OpenSSL.BN_bn2bin( self.bn, binary ) 56 | return int( binary.raw.encode('hex') or '0', 16 ) 57 | 58 | def __del__(self): 59 | if self.__created_bn: 60 | OpenSSL.BN_free( self.bn ) 61 | 62 | def __str__(self): 63 | return "BigNum<0x%X>" % self.get_value() 64 | 65 | __repr__ = __str__ 66 | -------------------------------------------------------------------------------- /curve.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (C) 2014 Jesper Borgstrup 4 | # ------------------------------------------------------------------- 5 | # Permission is hereby granted, free of charge, to any person 6 | # obtaining a copy of this software and associated documentation 7 | # files (the "Software"), to deal in the Software without restriction, 8 | # including without limitation the rights to use, copy, modify, merge, 9 | # publish, distribute, sublicense, and/or sell copies of the Software, 10 | # and to permit persons to whom the Software is furnished to do so, 11 | # subject to the following conditions: 12 | # 13 | # The above copyright notice and this permission notice shall be 14 | # included in all copies or substantial portions of the Software. 15 | # 16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 18 | # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 20 | # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 21 | # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | # DEALINGS IN THE SOFTWARE. 24 | 25 | import ctypes 26 | import math 27 | import hashlib 28 | 29 | from pyelliptic.openssl import OpenSSL 30 | from echelper import ECHelper 31 | from asnhelper import ASNHelper 32 | import point as ec_point 33 | 34 | class Curve: 35 | ''' 36 | classdocs 37 | ''' 38 | 39 | 40 | def __init__(self, curvename=None, curveid=None, openssl_group=None): 41 | ''' 42 | Constructor 43 | ''' 44 | if curvename != None: 45 | curve = OpenSSL.get_curve( curvename ) 46 | self.os_group = OpenSSL.EC_GROUP_new_by_curve_name( curve ) 47 | elif curveid != None: 48 | self.os_group = OpenSSL.EC_GROUP_new_by_curve_name( curveid ) 49 | elif openssl_group != None: 50 | self.os_group = openssl_group 51 | else: 52 | raise Exception('No curve provided') 53 | self.__set_parameters() 54 | self.__set_base_point() 55 | 56 | def __set_parameters(self): 57 | size = OpenSSL.i2d_ECPKParameters(self.os_group, 0) 58 | mb = ctypes.create_string_buffer(size) 59 | OpenSSL.i2d_ECPKParameters(self.os_group, ctypes.byref(ctypes.pointer(mb))) 60 | asntree = [x for x in ASNHelper.consume( mb.raw )][0] 61 | self.ver, self.field, self.curve, self.G_raw, self.order, self.h = asntree 62 | 63 | if self.field[0] == '42.134.72.206.61.1.1': # Prime field 64 | self.field_type = 'prime' 65 | self.p = self.field[1] 66 | self.bitlength = int( math.ceil( math.log( self.p, 2 ) ) ) 67 | self.a = self.curve[0] 68 | self.b = self.curve[1] 69 | self.f = lambda x: x**3 + self.a*x + self.b 70 | elif self.field[0] == '42.134.72.206.61.1.2': # Characteristic two field 71 | self.field_type = 'power-of-two' 72 | self.m = self.field[1][0] 73 | # Maybe bitlength below is not correct..? 74 | self.bitlength = self.m + 1 75 | if self.field[1][1] == '42.134.72.206.61.1.2.3.2': # Only one coefficient 76 | self.poly_coeffs = [self.field[1][2]] 77 | elif self.field[1][1] == '42.134.72.206.61.1.2.3.3': # Several coefficients 78 | self.poly_coeffs = self.field[1][2] 79 | else: 80 | raise Exception('Unknown field OID %s' % self.field[1][1]) 81 | self.a = self.curve[0] 82 | self.b = self.curve[1] 83 | else: 84 | raise Exception( 'Unknown curve field' ) 85 | 86 | def __set_base_point(self): 87 | self.G = ec_point.Point( self, openssl_point=OpenSSL.EC_GROUP_get0_generator( self.os_group ) ) 88 | 89 | def hash_to_field(self, in_str): 90 | return int( hashlib.sha512( in_str ).hexdigest()[:self.bitlength//4], 16 ) 91 | 92 | def hash_to_point(self, in_str): 93 | return self.find_point_try_and_increment( self.hash_to_field( in_str ) ) 94 | 95 | def find_point_try_and_increment(self, x): 96 | if self.field_type != 'prime': 97 | raise Exception( "find_point_try_and_increment is only implemented for curves over prime fields") 98 | 99 | ## HUSK AT FREE BIGNUMS 100 | found = False 101 | x -= 1 102 | while not found: 103 | x += 1 104 | f_x = self.f( x ) 105 | y = ECHelper.modular_sqrt( f_x, self.p ) 106 | if y != 0: 107 | return ec_point.Point( self, x=x, y=y ) 108 | 109 | def __eq__(self, other): 110 | if type(other) is type(self): 111 | return self.ver == other.ver and \ 112 | self.field == other.field and \ 113 | self.curve == other.curve and \ 114 | self.G_raw == other.G_raw and \ 115 | self.order == other.order and \ 116 | self.h == other.h 117 | return False 118 | def __ne__(self, other): 119 | return not self.__eq__(other) 120 | 121 | def __str__(self): 122 | if self.field_type == 'prime': 123 | field = "Prime field, p: 0x%X" % self.p 124 | equation = "y^2 = x^3" 125 | if self.a != 0: 126 | equation += "%+dx" % ( self.a ) 127 | if self.b != 0: 128 | equation += "%+d" % ( self.b ) 129 | equation += " (mod p)" 130 | elif self.field_type == 'power-of-two': 131 | field = "Power-of-two field, f(x): x^%d+%s1" % ( self.m, "".join( map( lambda x: "x^%d+" % x, reversed( self.poly_coeffs ) ) ) ) 132 | equation = "y^2+xy = x^3" 133 | if self.a != 0: 134 | equation += "%+dx" % ( self.a ) 135 | if self.b != 0: 136 | equation += "%+d" % ( self.b ) 137 | 138 | return "Curve" % ( equation, field ) 139 | 140 | __repr__ = __str__ 141 | -------------------------------------------------------------------------------- /echelper.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (C) 2014 Jesper Borgstrup 4 | # ------------------------------------------------------------------- 5 | # Permission is hereby granted, free of charge, to any person 6 | # obtaining a copy of this software and associated documentation 7 | # files (the "Software"), to deal in the Software without restriction, 8 | # including without limitation the rights to use, copy, modify, merge, 9 | # publish, distribute, sublicense, and/or sell copies of the Software, 10 | # and to permit persons to whom the Software is furnished to do so, 11 | # subject to the following conditions: 12 | # 13 | # The above copyright notice and this permission notice shall be 14 | # included in all copies or substantial portions of the Software. 15 | # 16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 18 | # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 20 | # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 21 | # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | # DEALINGS IN THE SOFTWARE. 24 | 25 | class ECHelper: 26 | @staticmethod 27 | def int2bin(i): 28 | """ 29 | Takes an integer and returns a bitstring (big endian) 30 | representing the integer. 31 | """ 32 | result = [] 33 | while i: 34 | result.append(chr(i&0xFF)) 35 | i >>= 8 36 | result.reverse() 37 | return ''.join(result) 38 | 39 | @staticmethod 40 | def modular_sqrt(a, p): 41 | """ Find a quadratic residue (mod p) of 'a'. p 42 | must be an odd prime. 43 | 44 | Solve the congruence of the form: 45 | x^2 = a (mod p) 46 | And returns x. Note that p - x is also a root. 47 | 48 | 0 is returned is no square root exists for 49 | these a and p. 50 | 51 | The Tonelli-Shanks algorithm is used (except 52 | for some simple cases in which the solution 53 | is known from an identity). This algorithm 54 | runs in polynomial time (unless the 55 | generalized Riemann hypothesis is false). 56 | 57 | Originally taken from 58 | http://eli.thegreenplace.net/2009/03/07/computing-modular-square-roots-in-python/ 59 | """ 60 | # Simple cases 61 | # 62 | if ECHelper.legendre_symbol(a, p) != 1: 63 | return 0 64 | elif a == 0: 65 | return 0 66 | elif p == 2: 67 | return p 68 | elif p % 4 == 3: 69 | return pow(a, (p + 1) / 4, p) 70 | 71 | # Partition p-1 to s * 2^e for an odd s (i.e. 72 | # reduce all the powers of 2 from p-1) 73 | # 74 | s = p - 1 75 | e = 0 76 | while s % 2 == 0: 77 | s /= 2 78 | e += 1 79 | 80 | # Find some 'n' with a legendre symbol n|p = -1. 81 | # Shouldn't take long. 82 | # 83 | n = 2 84 | while ECHelper.legendre_symbol(n, p) != -1: 85 | n += 1 86 | 87 | # Here be dragons! 88 | # Read the paper "Square roots from 1; 24, 51, 89 | # 10 to Dan Shanks" by Ezra Brown for more 90 | # information 91 | # 92 | 93 | # x is a guess of the square root that gets better 94 | # with each iteration. 95 | # b is the "fudge factor" - by how much we're off 96 | # with the guess. The invariant x^2 = ab (mod p) 97 | # is maintained throughout the loop. 98 | # g is used for successive powers of n to update 99 | # both a and b 100 | # r is the exponent - decreases with each update 101 | # 102 | x = pow(a, (s + 1) / 2, p) 103 | b = pow(a, s, p) 104 | g = pow(n, s, p) 105 | r = e 106 | 107 | while True: 108 | t = b 109 | m = 0 110 | for m in xrange(r): 111 | if t == 1: 112 | break 113 | t = pow(t, 2, p) 114 | 115 | if m == 0: 116 | return x 117 | 118 | gs = pow(g, 2 ** (r - m - 1), p) 119 | g = (gs * gs) % p 120 | x = (x * gs) % p 121 | b = (b * g) % p 122 | r = m 123 | 124 | 125 | @staticmethod 126 | def legendre_symbol(a, p): 127 | """ Compute the Legendre symbol a|p using 128 | Euler's criterion. p is a prime, a is 129 | relatively prime to p (if p divides 130 | a, then a|p = 0) 131 | 132 | Returns 1 if a has a square root modulo 133 | p, -1 otherwise. 134 | 135 | Originally taken from 136 | http://eli.thegreenplace.net/2009/03/07/computing-modular-square-roots-in-python/ 137 | """ 138 | ls = pow(a, (p - 1) / 2, p) 139 | return -1 if ls == p - 1 else ls 140 | -------------------------------------------------------------------------------- /keypair.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (C) 2014 Jesper Borgstrup 4 | # ------------------------------------------------------------------- 5 | # Permission is hereby granted, free of charge, to any person 6 | # obtaining a copy of this software and associated documentation 7 | # files (the "Software"), to deal in the Software without restriction, 8 | # including without limitation the rights to use, copy, modify, merge, 9 | # publish, distribute, sublicense, and/or sell copies of the Software, 10 | # and to permit persons to whom the Software is furnished to do so, 11 | # subject to the following conditions: 12 | # 13 | # The above copyright notice and this permission notice shall be 14 | # included in all copies or substantial portions of the Software. 15 | # 16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 18 | # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 20 | # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 21 | # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | # DEALINGS IN THE SOFTWARE. 24 | 25 | from pyelliptic.openssl import OpenSSL 26 | import curve as ec_curve 27 | import point as ec_point 28 | import bignum as ec_bignum 29 | 30 | class KeyPair: 31 | ''' 32 | classdocs 33 | ''' 34 | 35 | 36 | def __init__(self, curve, os_key=None, private_key=None): 37 | ''' 38 | Constructor 39 | ''' 40 | if not isinstance( curve, ec_curve.Curve ): 41 | raise Exception( 'Provided curve is not a Curve object' ) 42 | 43 | self.curve = curve 44 | self.os_group = curve.os_group 45 | 46 | if os_key is not None: 47 | self.os_key = os_key 48 | else: 49 | self.os_key = OpenSSL.EC_KEY_new() 50 | OpenSSL.EC_KEY_set_group( self.os_key, self.os_group ) 51 | if private_key is not None: 52 | privk = ec_bignum.BigNum( decval=private_key ) 53 | pubk = private_key * curve.G 54 | OpenSSL.EC_KEY_set_private_key( self.os_key, privk.bn ) 55 | OpenSSL.EC_KEY_set_public_key( self.os_key, pubk.os_point ) 56 | else: 57 | OpenSSL.EC_KEY_generate_key( self.os_key ) 58 | 59 | try: 60 | priv_key = ec_bignum.BigNum( OpenSSL.EC_KEY_get0_private_key( self.os_key ) ) 61 | self.private_key = priv_key.get_value() 62 | self.public_key = ec_point.Point( self.curve, openssl_point=OpenSSL.EC_KEY_get0_public_key( self.os_key ) ) 63 | finally: 64 | del priv_key 65 | 66 | def __eq__(self, other): 67 | if type(other) is type(self): 68 | return self.private_key == other.private_key and \ 69 | self.public_key == other.public_key 70 | return False 71 | def __ne__(self, other): 72 | return not self.__eq__(other) 73 | 74 | def __str__(self): 75 | return "KeyPair" % ( self.private_key, self.public_key ) 76 | 77 | __repr__ = __str__ 78 | -------------------------------------------------------------------------------- /point.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (C) 2014 Jesper Borgstrup 4 | # ------------------------------------------------------------------- 5 | # Permission is hereby granted, free of charge, to any person 6 | # obtaining a copy of this software and associated documentation 7 | # files (the "Software"), to deal in the Software without restriction, 8 | # including without limitation the rights to use, copy, modify, merge, 9 | # publish, distribute, sublicense, and/or sell copies of the Software, 10 | # and to permit persons to whom the Software is furnished to do so, 11 | # subject to the following conditions: 12 | # 13 | # The above copyright notice and this permission notice shall be 14 | # included in all copies or substantial portions of the Software. 15 | # 16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 18 | # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 20 | # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 21 | # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | # DEALINGS IN THE SOFTWARE. 24 | 25 | import ctypes 26 | from pyelliptic.openssl import OpenSSL 27 | from echelper import ECHelper 28 | import curve as ec_curve 29 | import bignum as ec_bignum 30 | 31 | class Point: 32 | ''' 33 | classdocs 34 | ''' 35 | 36 | 37 | def __init__(self, curve, openssl_point=None, x=None, y=None): 38 | ''' 39 | Constructor 40 | ''' 41 | if not isinstance( curve, ec_curve.Curve ): 42 | raise Exception( 'Provided curve is not a Curve object' ) 43 | 44 | self.curve = curve 45 | self.os_group = curve.os_group 46 | 47 | if openssl_point is not None: 48 | self.__set_to_openssl_point( openssl_point ) 49 | elif x is not None and y is not None: 50 | self.__set_to_coordinates( x, y ) 51 | else: 52 | raise Exception( 'No point given' ) 53 | 54 | def __set_to_openssl_point(self, point): 55 | try: 56 | x, y = ec_bignum.BigNum(), ec_bignum.BigNum() 57 | 58 | # Put X and Y coordinates of public key into x and y vars 59 | OpenSSL.EC_POINT_get_affine_coordinates_GFp( self.os_group, point, x.bn, y.bn, None ) 60 | 61 | self.x, self.y = x.get_value(), y.get_value() 62 | self.os_point = point 63 | finally: 64 | del x, y 65 | 66 | def __set_to_coordinates(self, x_val, y_val): 67 | try: 68 | point= OpenSSL.EC_POINT_new( self.os_group ) 69 | x, y = ec_bignum.BigNum( decval=x_val ), ec_bignum.BigNum( decval=y_val ) 70 | 71 | if self.curve.field_type == 'prime': 72 | OpenSSL.EC_POINT_set_affine_coordinates_GFp( self.os_group, point, x.bn, y.bn, None ) 73 | elif self.curve.field_type == 'characteristic-two': 74 | OpenSSL.EC_POINT_set_affine_coordinates_GF2m( self.os_group, point, x.bn, y.bn, None ) 75 | 76 | self.x, self.y = x_val, y_val 77 | self.os_point = point 78 | finally: 79 | del x, y 80 | 81 | def __eq__(self, other): 82 | if type(other) is type(self): 83 | return self.x == other.x and self.y == other.y 84 | return False 85 | def __ne__(self, other): 86 | return not self.__eq__(other) 87 | 88 | def __add__(self, other): 89 | """ 90 | Add two EC points together 91 | """ 92 | if isinstance( other, Point ): 93 | result = OpenSSL.EC_POINT_new( self.os_group ) 94 | OpenSSL.EC_POINT_add( self.os_group, result, self.os_point, other.os_point, 0 ) 95 | return Point( self.curve, openssl_point=result ) 96 | else: 97 | return NotImplemented 98 | 99 | def __mul__(self, other): 100 | """ 101 | Multiply an EC point by a scalar value 102 | and returns the multiplication result 103 | """ 104 | if isinstance( other, int ) or isinstance( other, long ): 105 | try: 106 | o = ec_bignum.BigNum( decval=other ) 107 | result = OpenSSL.EC_POINT_new( self.os_group ) 108 | OpenSSL.EC_POINT_mul( self.os_group, result, 0, self.os_point, o.bn, 0 ) 109 | return Point( self.curve, openssl_point=result ) 110 | finally: 111 | del o 112 | else: 113 | return NotImplemented 114 | 115 | __rmul__ = __mul__ 116 | 117 | def __str__(self): 118 | return "Point<0x%X, 0x%X>" % ( self.x, self.y ) 119 | 120 | __repr__ = __str__ 121 | -------------------------------------------------------------------------------- /pyelliptic/LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /pyelliptic/README.md: -------------------------------------------------------------------------------- 1 | # PyElliptic 2 | 3 | PyElliptic is a high level wrapper for the cryptographic library : OpenSSL. 4 | Under the GNU General Public License 5 | 6 | Python3 compatible. For GNU/Linux and Windows. 7 | Require OpenSSL 8 | 9 | ## Features 10 | 11 | ### Asymmetric cryptography using Elliptic Curve Cryptography (ECC) 12 | 13 | * Key agreement : ECDH 14 | * Digital signatures : ECDSA 15 | * Hybrid encryption : ECIES (like RSA) 16 | 17 | ### Symmetric cryptography 18 | 19 | * AES-128 (CBC, OFB, CFB) 20 | * AES-256 (CBC, OFB, CFB) 21 | * Blowfish (CFB and CBC) 22 | * RC4 23 | 24 | ### Other 25 | 26 | * CSPRNG 27 | * HMAC (using SHA512) 28 | * PBKDF2 (SHA256 and SHA512) 29 | 30 | ## Example 31 | 32 | ```python 33 | #!/usr/bin/python 34 | 35 | import pyelliptic 36 | 37 | # Symmetric encryption 38 | iv = pyelliptic.Cipher.gen_IV('aes-256-cfb') 39 | ctx = pyelliptic.Cipher("secretkey", iv, 1, ciphername='aes-256-cfb') 40 | 41 | ciphertext = ctx.update('test1') 42 | ciphertext += ctx.update('test2') 43 | ciphertext += ctx.final() 44 | 45 | ctx2 = pyelliptic.Cipher("secretkey", iv, 0, ciphername='aes-256-cfb') 46 | print ctx2.ciphering(ciphertext) 47 | 48 | # Asymmetric encryption 49 | alice = pyelliptic.ECC() # default curve: sect283r1 50 | bob = pyelliptic.ECC(curve='sect571r1') 51 | 52 | ciphertext = alice.encrypt("Hello Bob", bob.get_pubkey()) 53 | print bob.decrypt(ciphertext) 54 | 55 | signature = bob.sign("Hello Alice") 56 | # alice's job : 57 | print pyelliptic.ECC(pubkey=bob.get_pubkey()).verify(signature, "Hello Alice") 58 | 59 | # ERROR !!! 60 | try: 61 | key = alice.get_ecdh_key(bob.get_pubkey()) 62 | except: print("For ECDH key agreement, the keys must be defined on the same curve !") 63 | 64 | alice = pyelliptic.ECC(curve='sect571r1') 65 | print alice.get_ecdh_key(bob.get_pubkey()).encode('hex') 66 | print bob.get_ecdh_key(alice.get_pubkey()).encode('hex') 67 | ``` 68 | -------------------------------------------------------------------------------- /pyelliptic/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2010 2 | # Author: Yann GUIBET 3 | # Contact: 4 | 5 | __version__ = '1.3' 6 | 7 | __all__ = [ 8 | 'OpenSSL' 9 | ] 10 | 11 | from .openssl import OpenSSL 12 | -------------------------------------------------------------------------------- /pyelliptic/openssl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright (C) 2011 Yann GUIBET 5 | # See LICENSE for details. 6 | # 7 | # Software slightly changed by Jonathan Warren 8 | # 9 | # Additional changes by Jesper Borgstrup : 10 | # * Added EC_GROUP_get0_generator, EC_GROUP_get_order, 11 | # EC_GROUP_new_by_curve_name, EC_POINT_add, 12 | # i2d_ECPKParameters, EC_POINT_set_affine_coordinates_GF2m, 13 | # EC_KEY_new 14 | 15 | import sys 16 | import ctypes 17 | 18 | OpenSSL = None 19 | 20 | 21 | class CipherName: 22 | def __init__(self, name, pointer, blocksize): 23 | self._name = name 24 | self._pointer = pointer 25 | self._blocksize = blocksize 26 | 27 | def __str__(self): 28 | return "Cipher : " + self._name + " | Blocksize : " + str(self._blocksize) + " | Fonction pointer : " + str(self._pointer) 29 | 30 | def get_pointer(self): 31 | return self._pointer() 32 | 33 | def get_name(self): 34 | return self._name 35 | 36 | def get_blocksize(self): 37 | return self._blocksize 38 | 39 | 40 | class _OpenSSL: 41 | """ 42 | Wrapper for OpenSSL using ctypes 43 | """ 44 | def __init__(self, library): 45 | """ 46 | Build the wrapper 47 | """ 48 | self._lib = ctypes.CDLL(library) 49 | 50 | self.pointer = ctypes.pointer 51 | self.c_int = ctypes.c_int 52 | self.byref = ctypes.byref 53 | self.create_string_buffer = ctypes.create_string_buffer 54 | 55 | self.BN_new = self._lib.BN_new 56 | self.BN_new.restype = ctypes.c_void_p 57 | self.BN_new.argtypes = [] 58 | 59 | self.BN_free = self._lib.BN_free 60 | self.BN_free.restype = None 61 | self.BN_free.argtypes = [ctypes.c_void_p] 62 | 63 | self.BN_num_bits = self._lib.BN_num_bits 64 | self.BN_num_bits.restype = ctypes.c_int 65 | self.BN_num_bits.argtypes = [ctypes.c_void_p] 66 | 67 | self.BN_bn2bin = self._lib.BN_bn2bin 68 | self.BN_bn2bin.restype = ctypes.c_int 69 | self.BN_bn2bin.argtypes = [ctypes.c_void_p, ctypes.c_void_p] 70 | 71 | self.BN_bin2bn = self._lib.BN_bin2bn 72 | self.BN_bin2bn.restype = ctypes.c_void_p 73 | self.BN_bin2bn.argtypes = [ctypes.c_void_p, ctypes.c_int, 74 | ctypes.c_void_p] 75 | 76 | self.EC_GROUP_get0_generator = self._lib.EC_GROUP_get0_generator 77 | self.EC_GROUP_get0_generator.restype = ctypes.c_int 78 | self.EC_GROUP_get0_generator.argtypes = [ctypes.c_void_p] 79 | 80 | self.EC_GROUP_get_order = self._lib.EC_GROUP_get_order 81 | self.EC_GROUP_get_order.restype = ctypes.c_int 82 | self.EC_GROUP_get_order.argtypes = [ctypes.c_void_p, ctypes.c_void_p, 83 | ctypes.c_void_p] 84 | 85 | self.EC_GROUP_new_by_curve_name = self._lib.EC_GROUP_new_by_curve_name 86 | self.EC_GROUP_new_by_curve_name.restype = ctypes.c_void_p 87 | self.EC_GROUP_new_by_curve_name.argtypes = [ctypes.c_int] 88 | 89 | self.EC_KEY_free = self._lib.EC_KEY_free 90 | self.EC_KEY_free.restype = None 91 | self.EC_KEY_free.argtypes = [ctypes.c_void_p] 92 | 93 | self.EC_KEY_new = self._lib.EC_KEY_new 94 | self.EC_KEY_new.restype = ctypes.c_void_p 95 | self.EC_KEY_new.argtypes = [] 96 | 97 | self.EC_KEY_new_by_curve_name = self._lib.EC_KEY_new_by_curve_name 98 | self.EC_KEY_new_by_curve_name.restype = ctypes.c_void_p 99 | self.EC_KEY_new_by_curve_name.argtypes = [ctypes.c_int] 100 | 101 | self.EC_KEY_generate_key = self._lib.EC_KEY_generate_key 102 | self.EC_KEY_generate_key.restype = ctypes.c_int 103 | self.EC_KEY_generate_key.argtypes = [ctypes.c_void_p] 104 | 105 | self.EC_KEY_check_key = self._lib.EC_KEY_check_key 106 | self.EC_KEY_check_key.restype = ctypes.c_int 107 | self.EC_KEY_check_key.argtypes = [ctypes.c_void_p] 108 | 109 | self.EC_KEY_get0_private_key = self._lib.EC_KEY_get0_private_key 110 | self.EC_KEY_get0_private_key.restype = ctypes.c_void_p 111 | self.EC_KEY_get0_private_key.argtypes = [ctypes.c_void_p] 112 | 113 | self.EC_KEY_get0_public_key = self._lib.EC_KEY_get0_public_key 114 | self.EC_KEY_get0_public_key.restype = ctypes.c_void_p 115 | self.EC_KEY_get0_public_key.argtypes = [ctypes.c_void_p] 116 | 117 | self.EC_KEY_get0_group = self._lib.EC_KEY_get0_group 118 | self.EC_KEY_get0_group.restype = ctypes.c_void_p 119 | self.EC_KEY_get0_group.argtypes = [ctypes.c_void_p] 120 | 121 | self.EC_POINT_get_affine_coordinates_GFp = self._lib.EC_POINT_get_affine_coordinates_GFp 122 | self.EC_POINT_get_affine_coordinates_GFp.restype = ctypes.c_int 123 | self.EC_POINT_get_affine_coordinates_GFp.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] 124 | 125 | self.EC_KEY_set_private_key = self._lib.EC_KEY_set_private_key 126 | self.EC_KEY_set_private_key.restype = ctypes.c_int 127 | self.EC_KEY_set_private_key.argtypes = [ctypes.c_void_p, 128 | ctypes.c_void_p] 129 | 130 | self.EC_KEY_set_public_key = self._lib.EC_KEY_set_public_key 131 | self.EC_KEY_set_public_key.restype = ctypes.c_int 132 | self.EC_KEY_set_public_key.argtypes = [ctypes.c_void_p, 133 | ctypes.c_void_p] 134 | 135 | self.EC_KEY_set_group = self._lib.EC_KEY_set_group 136 | self.EC_KEY_set_group.restype = ctypes.c_int 137 | self.EC_KEY_set_group.argtypes = [ctypes.c_void_p, ctypes.c_void_p] 138 | 139 | self.EC_POINT_set_affine_coordinates_GFp = self._lib.EC_POINT_set_affine_coordinates_GFp 140 | self.EC_POINT_set_affine_coordinates_GFp.restype = ctypes.c_int 141 | self.EC_POINT_set_affine_coordinates_GFp.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] 142 | 143 | self.EC_POINT_set_affine_coordinates_GF2m = self._lib.EC_POINT_set_affine_coordinates_GF2m 144 | self.EC_POINT_set_affine_coordinates_GF2m.restype = ctypes.c_int 145 | self.EC_POINT_set_affine_coordinates_GF2m.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] 146 | 147 | self.EC_POINT_new = self._lib.EC_POINT_new 148 | self.EC_POINT_new.restype = ctypes.c_void_p 149 | self.EC_POINT_new.argtypes = [ctypes.c_void_p] 150 | 151 | self.EC_POINT_free = self._lib.EC_POINT_free 152 | self.EC_POINT_free.restype = None 153 | self.EC_POINT_free.argtypes = [ctypes.c_void_p] 154 | 155 | self.BN_CTX_free = self._lib.BN_CTX_free 156 | self.BN_CTX_free.restype = None 157 | self.BN_CTX_free.argtypes = [ctypes.c_void_p] 158 | 159 | self.EC_POINT_mul = self._lib.EC_POINT_mul 160 | self.EC_POINT_mul.restype = None 161 | self.EC_POINT_mul.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] 162 | 163 | self.EC_POINT_add = self._lib.EC_POINT_add 164 | self.EC_POINT_add.resType = None 165 | self.EC_POINT_add.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] 166 | 167 | self.EC_KEY_set_private_key = self._lib.EC_KEY_set_private_key 168 | self.EC_KEY_set_private_key.restype = ctypes.c_int 169 | self.EC_KEY_set_private_key.argtypes = [ctypes.c_void_p, 170 | ctypes.c_void_p] 171 | 172 | self.ECDH_OpenSSL = self._lib.ECDH_OpenSSL 173 | self._lib.ECDH_OpenSSL.restype = ctypes.c_void_p 174 | self._lib.ECDH_OpenSSL.argtypes = [] 175 | 176 | self.BN_CTX_new = self._lib.BN_CTX_new 177 | self._lib.BN_CTX_new.restype = ctypes.c_void_p 178 | self._lib.BN_CTX_new.argtypes = [] 179 | 180 | self.ECDH_set_method = self._lib.ECDH_set_method 181 | self._lib.ECDH_set_method.restype = ctypes.c_int 182 | self._lib.ECDH_set_method.argtypes = [ctypes.c_void_p, ctypes.c_void_p] 183 | 184 | self.ECDH_compute_key = self._lib.ECDH_compute_key 185 | self.ECDH_compute_key.restype = ctypes.c_int 186 | self.ECDH_compute_key.argtypes = [ctypes.c_void_p, 187 | ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p] 188 | 189 | self.EVP_CipherInit_ex = self._lib.EVP_CipherInit_ex 190 | self.EVP_CipherInit_ex.restype = ctypes.c_int 191 | self.EVP_CipherInit_ex.argtypes = [ctypes.c_void_p, 192 | ctypes.c_void_p, ctypes.c_void_p] 193 | 194 | self.EVP_CIPHER_CTX_new = self._lib.EVP_CIPHER_CTX_new 195 | self.EVP_CIPHER_CTX_new.restype = ctypes.c_void_p 196 | self.EVP_CIPHER_CTX_new.argtypes = [] 197 | 198 | # Cipher 199 | self.EVP_aes_128_cfb128 = self._lib.EVP_aes_128_cfb128 200 | self.EVP_aes_128_cfb128.restype = ctypes.c_void_p 201 | self.EVP_aes_128_cfb128.argtypes = [] 202 | 203 | self.EVP_aes_256_cfb128 = self._lib.EVP_aes_256_cfb128 204 | self.EVP_aes_256_cfb128.restype = ctypes.c_void_p 205 | self.EVP_aes_256_cfb128.argtypes = [] 206 | 207 | self.EVP_aes_128_cbc = self._lib.EVP_aes_128_cbc 208 | self.EVP_aes_128_cbc.restype = ctypes.c_void_p 209 | self.EVP_aes_128_cbc.argtypes = [] 210 | 211 | self.EVP_aes_256_cbc = self._lib.EVP_aes_256_cbc 212 | self.EVP_aes_256_cbc.restype = ctypes.c_void_p 213 | self.EVP_aes_256_cbc.argtypes = [] 214 | 215 | #self.EVP_aes_128_ctr = self._lib.EVP_aes_128_ctr 216 | #self.EVP_aes_128_ctr.restype = ctypes.c_void_p 217 | #self.EVP_aes_128_ctr.argtypes = [] 218 | 219 | #self.EVP_aes_256_ctr = self._lib.EVP_aes_256_ctr 220 | #self.EVP_aes_256_ctr.restype = ctypes.c_void_p 221 | #self.EVP_aes_256_ctr.argtypes = [] 222 | 223 | self.EVP_aes_128_ofb = self._lib.EVP_aes_128_ofb 224 | self.EVP_aes_128_ofb.restype = ctypes.c_void_p 225 | self.EVP_aes_128_ofb.argtypes = [] 226 | 227 | self.EVP_aes_256_ofb = self._lib.EVP_aes_256_ofb 228 | self.EVP_aes_256_ofb.restype = ctypes.c_void_p 229 | self.EVP_aes_256_ofb.argtypes = [] 230 | 231 | self.EVP_bf_cbc = self._lib.EVP_bf_cbc 232 | self.EVP_bf_cbc.restype = ctypes.c_void_p 233 | self.EVP_bf_cbc.argtypes = [] 234 | 235 | self.EVP_bf_cfb64 = self._lib.EVP_bf_cfb64 236 | self.EVP_bf_cfb64.restype = ctypes.c_void_p 237 | self.EVP_bf_cfb64.argtypes = [] 238 | 239 | self.EVP_rc4 = self._lib.EVP_rc4 240 | self.EVP_rc4.restype = ctypes.c_void_p 241 | self.EVP_rc4.argtypes = [] 242 | 243 | self.EVP_CIPHER_CTX_cleanup = self._lib.EVP_CIPHER_CTX_cleanup 244 | self.EVP_CIPHER_CTX_cleanup.restype = ctypes.c_int 245 | self.EVP_CIPHER_CTX_cleanup.argtypes = [ctypes.c_void_p] 246 | 247 | self.EVP_CIPHER_CTX_free = self._lib.EVP_CIPHER_CTX_free 248 | self.EVP_CIPHER_CTX_free.restype = None 249 | self.EVP_CIPHER_CTX_free.argtypes = [ctypes.c_void_p] 250 | 251 | self.EVP_CipherUpdate = self._lib.EVP_CipherUpdate 252 | self.EVP_CipherUpdate.restype = ctypes.c_int 253 | self.EVP_CipherUpdate.argtypes = [ctypes.c_void_p, 254 | ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int] 255 | 256 | self.EVP_CipherFinal_ex = self._lib.EVP_CipherFinal_ex 257 | self.EVP_CipherFinal_ex.restype = ctypes.c_int 258 | self.EVP_CipherFinal_ex.argtypes = [ctypes.c_void_p, 259 | ctypes.c_void_p, ctypes.c_void_p] 260 | 261 | self.EVP_DigestInit = self._lib.EVP_DigestInit 262 | self.EVP_DigestInit.restype = ctypes.c_int 263 | self._lib.EVP_DigestInit.argtypes = [ctypes.c_void_p, ctypes.c_void_p] 264 | 265 | self.EVP_DigestUpdate = self._lib.EVP_DigestUpdate 266 | self.EVP_DigestUpdate.restype = ctypes.c_int 267 | self.EVP_DigestUpdate.argtypes = [ctypes.c_void_p, 268 | ctypes.c_void_p, ctypes.c_int] 269 | 270 | self.EVP_DigestFinal = self._lib.EVP_DigestFinal 271 | self.EVP_DigestFinal.restype = ctypes.c_int 272 | self.EVP_DigestFinal.argtypes = [ctypes.c_void_p, 273 | ctypes.c_void_p, ctypes.c_void_p] 274 | 275 | self.EVP_ecdsa = self._lib.EVP_ecdsa 276 | self._lib.EVP_ecdsa.restype = ctypes.c_void_p 277 | self._lib.EVP_ecdsa.argtypes = [] 278 | 279 | self.ECDSA_sign = self._lib.ECDSA_sign 280 | self.ECDSA_sign.restype = ctypes.c_int 281 | self.ECDSA_sign.argtypes = [ctypes.c_int, ctypes.c_void_p, 282 | ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] 283 | 284 | self.ECDSA_verify = self._lib.ECDSA_verify 285 | self.ECDSA_verify.restype = ctypes.c_int 286 | self.ECDSA_verify.argtypes = [ctypes.c_int, ctypes.c_void_p, 287 | ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p] 288 | 289 | self.EVP_MD_CTX_create = self._lib.EVP_MD_CTX_create 290 | self.EVP_MD_CTX_create.restype = ctypes.c_void_p 291 | self.EVP_MD_CTX_create.argtypes = [] 292 | 293 | self.EVP_MD_CTX_init = self._lib.EVP_MD_CTX_init 294 | self.EVP_MD_CTX_init.restype = None 295 | self.EVP_MD_CTX_init.argtypes = [ctypes.c_void_p] 296 | 297 | self.EVP_MD_CTX_destroy = self._lib.EVP_MD_CTX_destroy 298 | self.EVP_MD_CTX_destroy.restype = None 299 | self.EVP_MD_CTX_destroy.argtypes = [ctypes.c_void_p] 300 | 301 | self.RAND_bytes = self._lib.RAND_bytes 302 | self.RAND_bytes.restype = ctypes.c_int 303 | self.RAND_bytes.argtypes = [ctypes.c_void_p, ctypes.c_int] 304 | 305 | 306 | self.EVP_sha256 = self._lib.EVP_sha256 307 | self.EVP_sha256.restype = ctypes.c_void_p 308 | self.EVP_sha256.argtypes = [] 309 | 310 | self.i2o_ECPublicKey = self._lib.i2o_ECPublicKey 311 | self.i2o_ECPublicKey.restype = ctypes.c_void_p 312 | self.i2o_ECPublicKey.argtypes = [ctypes.c_void_p, ctypes.c_void_p] 313 | 314 | self.i2d_ECPKParameters = self._lib.i2d_ECPKParameters 315 | self.i2d_ECPKParameters.restype = ctypes.c_void_p 316 | self.i2d_ECPKParameters.argtypes = [ctypes.c_void_p, ctypes.c_void_p] 317 | 318 | self.EVP_sha512 = self._lib.EVP_sha512 319 | self.EVP_sha512.restype = ctypes.c_void_p 320 | self.EVP_sha512.argtypes = [] 321 | 322 | self.HMAC = self._lib.HMAC 323 | self.HMAC.restype = ctypes.c_void_p 324 | self.HMAC.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, 325 | ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p] 326 | 327 | try: 328 | self.PKCS5_PBKDF2_HMAC = self._lib.PKCS5_PBKDF2_HMAC 329 | except: 330 | # The above is not compatible with all versions of OSX. 331 | self.PKCS5_PBKDF2_HMAC = self._lib.PKCS5_PBKDF2_HMAC_SHA1 332 | 333 | self.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int 334 | self.PKCS5_PBKDF2_HMAC.argtypes = [ctypes.c_void_p, ctypes.c_int, 335 | ctypes.c_void_p, ctypes.c_int, 336 | ctypes.c_int, ctypes.c_void_p, 337 | ctypes.c_int, ctypes.c_void_p] 338 | 339 | self._set_ciphers() 340 | self._set_curves() 341 | 342 | def _set_ciphers(self): 343 | self.cipher_algo = { 344 | 'aes-128-cbc': CipherName('aes-128-cbc', self.EVP_aes_128_cbc, 16), 345 | 'aes-256-cbc': CipherName('aes-256-cbc', self.EVP_aes_256_cbc, 16), 346 | 'aes-128-cfb': CipherName('aes-128-cfb', self.EVP_aes_128_cfb128, 16), 347 | 'aes-256-cfb': CipherName('aes-256-cfb', self.EVP_aes_256_cfb128, 16), 348 | 'aes-128-ofb': CipherName('aes-128-ofb', self._lib.EVP_aes_128_ofb, 16), 349 | 'aes-256-ofb': CipherName('aes-256-ofb', self._lib.EVP_aes_256_ofb, 16), 350 | #'aes-128-ctr': CipherName('aes-128-ctr', self._lib.EVP_aes_128_ctr, 16), 351 | #'aes-256-ctr': CipherName('aes-256-ctr', self._lib.EVP_aes_256_ctr, 16), 352 | 'bf-cfb': CipherName('bf-cfb', self.EVP_bf_cfb64, 8), 353 | 'bf-cbc': CipherName('bf-cbc', self.EVP_bf_cbc, 8), 354 | 'rc4': CipherName('rc4', self.EVP_rc4, 128), # 128 is the initialisation size not block size 355 | } 356 | 357 | def _set_curves(self): 358 | self.curves = { 359 | 'secp112r1': 704, 360 | 'secp112r2': 705, 361 | 'secp128r1': 706, 362 | 'secp128r2': 707, 363 | 'secp160k1': 708, 364 | 'secp160r1': 709, 365 | 'secp160r2': 710, 366 | 'secp192k1': 711, 367 | 'secp224k1': 712, 368 | 'secp224r1': 713, 369 | 'secp256k1': 714, 370 | 'secp384r1': 715, 371 | 'secp521r1': 716, 372 | 'sect113r1': 717, 373 | 'sect113r2': 718, 374 | 'sect131r1': 719, 375 | 'sect131r2': 720, 376 | 'sect163k1': 721, 377 | 'sect163r1': 722, 378 | 'sect163r2': 723, 379 | 'sect193r1': 724, 380 | 'sect193r2': 725, 381 | 'sect233k1': 726, 382 | 'sect233r1': 727, 383 | 'sect239k1': 728, 384 | 'sect283k1': 729, 385 | 'sect283r1': 730, 386 | 'sect409k1': 731, 387 | 'sect409r1': 732, 388 | 'sect571k1': 733, 389 | 'sect571r1': 734, 390 | } 391 | 392 | def BN_num_bytes(self, x): 393 | """ 394 | returns the length of a BN (OpenSSl API) 395 | """ 396 | return int((self.BN_num_bits(x) + 7) / 8) 397 | 398 | def get_cipher(self, name): 399 | """ 400 | returns the OpenSSL cipher instance 401 | """ 402 | if name not in self.cipher_algo: 403 | raise Exception("Unknown cipher") 404 | return self.cipher_algo[name] 405 | 406 | def get_curve(self, name): 407 | """ 408 | returns the id of a elliptic curve 409 | """ 410 | if name not in self.curves: 411 | raise Exception("Unknown curve") 412 | return self.curves[name] 413 | 414 | def get_curve_by_id(self, id): 415 | """ 416 | returns the name of a elliptic curve with his id 417 | """ 418 | res = None 419 | for i in self.curves: 420 | if self.curves[i] == id: 421 | res = i 422 | break 423 | if res is None: 424 | raise Exception("Unknown curve") 425 | return res 426 | 427 | def rand(self, size): 428 | """ 429 | OpenSSL random function 430 | """ 431 | buffer = self.malloc(0, size) 432 | # This pyelliptic library, by default, didn't check the return value of RAND_bytes. It is 433 | # evidently possible that it returned an error and not-actually-random data. However, in 434 | # tests on various operating systems, while generating hundreds of gigabytes of random 435 | # strings of various sizes I could not get an error to occur. Also Bitcoin doesn't check 436 | # the return value of RAND_bytes either. 437 | # Fixed in Bitmessage version 0.4.2 (in source code on 2013-10-13) 438 | while self.RAND_bytes(buffer, size) != 1: 439 | import time 440 | time.sleep(1) 441 | return buffer.raw 442 | 443 | def malloc(self, data, size): 444 | """ 445 | returns a create_string_buffer (ctypes) 446 | """ 447 | buffer = None 448 | if data != 0: 449 | if sys.version_info.major == 3 and isinstance(data, type('')): 450 | data = data.encode() 451 | buffer = self.create_string_buffer(data, size) 452 | else: 453 | buffer = self.create_string_buffer(size) 454 | return buffer 455 | 456 | try: 457 | OpenSSL = _OpenSSL('libcrypto.so') 458 | except: 459 | try: 460 | OpenSSL = _OpenSSL('libeay32.dll') 461 | except: 462 | try: 463 | OpenSSL = _OpenSSL('libcrypto.dylib') 464 | except: 465 | try: 466 | # try homebrew installation 467 | OpenSSL = _OpenSSL('/usr/local/opt/openssl/lib/libcrypto.dylib') 468 | except: 469 | try: 470 | # Load it from an Bitmessage.app on OSX 471 | OpenSSL = _OpenSSL('./../Frameworks/libcrypto.dylib') 472 | except: 473 | try: 474 | from os import path 475 | lib_path = path.join(sys._MEIPASS, "libeay32.dll") 476 | OpenSSL = _OpenSSL(lib_path) 477 | except: 478 | if 'linux' in sys.platform or 'darwin' in sys.platform or 'freebsd' in sys.platform: 479 | try: 480 | from ctypes.util import find_library 481 | OpenSSL = _OpenSSL(find_library('ssl')) 482 | except Exception, err: 483 | sys.stderr.write('(On Linux) Couldn\'t find and load the OpenSSL library. You must install it. If you believe that you already have it installed, this exception information might be of use:\n') 484 | from ctypes.util import find_library 485 | OpenSSL = _OpenSSL(find_library('ssl')) 486 | else: 487 | raise Exception("Couldn't find and load the OpenSSL library. You must install it.") 488 | -------------------------------------------------------------------------------- /sample_lsag.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (C) 2014 Jesper Borgstrup 4 | # ------------------------------------------------------------------- 5 | # Permission is hereby granted, free of charge, to any person 6 | # obtaining a copy of this software and associated documentation 7 | # files (the "Software"), to deal in the Software without restriction, 8 | # including without limitation the rights to use, copy, modify, merge, 9 | # publish, distribute, sublicense, and/or sell copies of the Software, 10 | # and to permit persons to whom the Software is furnished to do so, 11 | # subject to the following conditions: 12 | # 13 | # The above copyright notice and this permission notice shall be 14 | # included in all copies or substantial portions of the Software. 15 | # 16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 18 | # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 20 | # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 21 | # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | # DEALINGS IN THE SOFTWARE. 24 | 25 | import hashlib 26 | import time 27 | from random import randint 28 | 29 | from echelper import ECHelper 30 | from curve import Curve 31 | from keypair import KeyPair 32 | 33 | 34 | CURVE = "secp256k1" 35 | KEY_COUNT = 10000 36 | DEBUG = False 37 | 38 | def sign(curve, keys, signer_index, message="Hello message"): 39 | key_count = len( keys ) 40 | 41 | # Set signer 42 | signer = keys[signer_index] 43 | 44 | # Make room for c_i, s_i, z'_i, and z''_i variables 45 | cs = [0] * key_count 46 | ss = [0] * key_count 47 | z_s = [0] * key_count 48 | z__s = [0] * key_count 49 | 50 | # Retrieve all public keys and their coordinates 51 | public_keys = map( lambda key: key.public_key, keys ) 52 | public_keys_coords = map( lambda point: (point.x, point.y), public_keys ) 53 | 54 | # Step 1 55 | public_keys_hash = curve.hash_to_field( "%s" % public_keys_coords ) 56 | H = H2( curve, public_keys_coords ) 57 | Y_tilde = signer.private_key * H 58 | 59 | # Step 2 60 | u = randint( 0, curve.order ) 61 | pi_plus_1 = (signer_index+1) % key_count 62 | cs[pi_plus_1] = H1( curve, public_keys_hash, Y_tilde, message, 63 | u * curve.G, u * H ) 64 | 65 | # Step 3 66 | for i in range( signer_index+1, key_count ) + range( signer_index ): 67 | ss[i] = randint( 0, curve.order ) 68 | next_i = (i+1) % key_count 69 | z_s[i] = ss[i] * curve.G + cs[i] * public_keys[i] 70 | z__s[i] = ss[i] * H + cs[i] * Y_tilde 71 | cs[next_i] = H1( curve, public_keys_hash, Y_tilde, message, z_s[i], z__s[i] ) 72 | 73 | # Step 4 74 | ss[signer_index] = ( u - signer.private_key * cs[signer_index] ) % curve.order 75 | 76 | if DEBUG: 77 | print "SIGN H: %s" % H 78 | print "SIGN Y_tilde: %s" % Y_tilde 79 | for i in range( len( cs ) ): 80 | print "SIGN c_%d: %d" % ( i, cs[i] ) 81 | print "SIGN s_%d: %d" % ( i, ss[i] ) 82 | if z_s[i] != 0: 83 | print "SIGN Z_%d: %s" % ( i, z_s[i] ) 84 | if z__s[i] != 0: 85 | print "SIGN Z__%d: %s" % ( i, z__s[i] ) 86 | print "-----------------------------------------" 87 | 88 | return ( public_keys, 89 | message, 90 | cs[0], 91 | ss, 92 | Y_tilde 93 | ) 94 | 95 | def verify( curve, public_keys, message, c_0, ss, Y_tilde ): 96 | public_keys_coords = map( lambda point: ( point.x, point.y ) , public_keys ) 97 | 98 | n = len( public_keys ) 99 | 100 | cs = [c_0] + [0] * ( n - 1 ) 101 | z_s = [0] * n 102 | z__s = [0] * n 103 | 104 | # Step 1 105 | public_keys_hash = curve.hash_to_field( "%s" % public_keys_coords ) 106 | H = H2( curve, public_keys_coords ) 107 | for i in range( n ): 108 | z_s[i] = ss[i] * curve.G + cs[i] * public_keys[i] 109 | z__s[i] = ss[i] * H + cs[i] * Y_tilde 110 | if i < n - 1: 111 | cs[i+1] = H1( curve, public_keys_hash, Y_tilde, message, z_s[i], z__s[i] ) 112 | 113 | H1_ver = H1( curve, public_keys_hash, Y_tilde, message, z_s[n-1], z__s[n-1] ) 114 | 115 | if DEBUG: 116 | print "VERIFY H: %s" % H 117 | for i in range( len( cs ) ): 118 | print "VERIFY c_%d: %d" % ( i, cs[i] ) 119 | print "VERIFY s_%d: %d" % ( i, ss[i] ) 120 | print "VERIFY Z_%d: %s" % ( i, z_s[i] ) 121 | print "VERIFY Z__%d: %s" % ( i, z__s[i] ) 122 | print "-----------------------------------------" 123 | 124 | print "VERIFY H1_ver==c_0: (%d == %d)" % ( H1_ver, cs[0] ) 125 | 126 | return cs[0] == H1_ver 127 | 128 | def H2( curve, in_str ): 129 | """ 130 | Hash the input as a string and return the hash as an integer. 131 | """ 132 | return curve.hash_to_point( "H2_salt%s" % in_str ) 133 | 134 | def H1( curve, keys, Y_tilde, message, P1, P2): 135 | """ 136 | The H1 function that hashes a lot of variables 137 | and returns the hash as an integer. 138 | """ 139 | str = "%s,%s,%s,%X,%X,%X,%X" % ( keys, Y_tilde, message, 140 | P1.x, P1.y, P2.x, P2.y) 141 | return curve.hash_to_field( "H1_salt%s" % str ) 142 | 143 | def get_signature_size( signature ): 144 | public_keys, message, c_0, ss, Y_tilde = signature 145 | # Each public key is 64 bytes (32 bytes per coordinate) 146 | size = 64 * len( public_keys ) 147 | size += len( ECHelper.int2bin( c_0 ) ) 148 | size += sum( map( lambda s: len( ECHelper.int2bin( s ) ), ss ) ) 149 | # Y_tilde is also a point, which again requires 64 bytes 150 | size += 64 151 | return size 152 | 153 | def run_test( curve, keys, signer_index ): 154 | signature = sign( curve, keys, signer_index ) 155 | assert verify( curve, *signature ) 156 | return get_signature_size( signature ) 157 | 158 | def run_multiple_tests( curve, keys, signer_index=0, tests=1 ): 159 | t_start = time.time() 160 | size = sum( map( lambda _: run_test( curve, keys, signer_index ), range( tests ) ) ) 161 | t_end = time.time() 162 | t = t_end - t_start 163 | print "Signing and verifying %d messages with %d keys took %.3f seconds (%.3f s/msg, %.3f ms/msg/key)" \ 164 | % ( tests, len( keys ), t, t / tests, 1000 * t / tests / len( keys ) ) 165 | print "The %d signatures were %d bytes in total (%.3f b/test, %.3f b/test/key)" % ( tests, size, float(size) / tests, float(size) / tests / len(keys) ) 166 | return ( len( keys ), tests, t, size ) 167 | 168 | def run(): 169 | curve = Curve( CURVE ) 170 | 171 | # Generate private/public key pairs 172 | print "Generating %d key pairs..." % KEY_COUNT 173 | t = time.time() 174 | key_gen_time = keys = map( lambda _: KeyPair( curve ), range( KEY_COUNT ) ) 175 | print "Generating %d key pairs took %.3f seconds" % ( KEY_COUNT, time.time() - t ) 176 | 177 | results = [] 178 | 179 | for i in [ 2, 3, 5, 10, 20, 30, 50, 100, 200, 300, 500, 1000, 2000, 3000, 5000, 10000]: 180 | results.append( run_multiple_tests( curve, keys[0:i], tests=10 ) ) 181 | 182 | print repr( results ) 183 | 184 | if __name__ == "__main__": 185 | run() --------------------------------------------------------------------------------