File: _int.py

package info (click to toggle)
asn1crypto 0.24.0-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 688 kB
  • sloc: python: 9,275; makefile: 4
file content (159 lines) | stat: -rw-r--r-- 4,618 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# coding: utf-8

"""
Function for calculating the modular inverse. Exports the following items:

 - inverse_mod()

Source code is derived from
http://webpages.charter.net/curryfans/peter/downloads.html, but has been heavily
modified to fit into this projects lint settings. The original project license
is listed below:

Copyright (c) 2014 Peter Pearson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

from __future__ import unicode_literals, division, absolute_import, print_function

import math
import platform

from .util import int_to_bytes, int_from_bytes

# First try to use ctypes with OpenSSL for better performance
try:
    from ._ffi import (
        buffer_from_bytes,
        bytes_from_buffer,
        FFIEngineError,
        LibraryNotFoundError,
        null,
    )

    # Some versions of PyPy have segfault issues, so we just punt on PyPy
    if platform.python_implementation() == 'PyPy':
        raise EnvironmentError()

    try:
        from ._perf._big_num_ctypes import libcrypto

        def inverse_mod(a, p):
            """
            Compute the modular inverse of a (mod p)

            :param a:
                An integer

            :param p:
                An integer

            :return:
                An integer
            """

            ctx = libcrypto.BN_CTX_new()

            a_bytes = int_to_bytes(abs(a))
            p_bytes = int_to_bytes(abs(p))

            a_buf = buffer_from_bytes(a_bytes)
            a_bn = libcrypto.BN_bin2bn(a_buf, len(a_bytes), null())
            if a < 0:
                libcrypto.BN_set_negative(a_bn, 1)

            p_buf = buffer_from_bytes(p_bytes)
            p_bn = libcrypto.BN_bin2bn(p_buf, len(p_bytes), null())
            if p < 0:
                libcrypto.BN_set_negative(p_bn, 1)

            r_bn = libcrypto.BN_mod_inverse(null(), a_bn, p_bn, ctx)
            r_len_bits = libcrypto.BN_num_bits(r_bn)
            r_len = int(math.ceil(r_len_bits / 8))
            r_buf = buffer_from_bytes(r_len)
            libcrypto.BN_bn2bin(r_bn, r_buf)
            r_bytes = bytes_from_buffer(r_buf, r_len)
            result = int_from_bytes(r_bytes)

            libcrypto.BN_free(a_bn)
            libcrypto.BN_free(p_bn)
            libcrypto.BN_free(r_bn)
            libcrypto.BN_CTX_free(ctx)

            return result
    except (LibraryNotFoundError, FFIEngineError):
        raise EnvironmentError()

# If there was an issue using ctypes or OpenSSL, we fall back to pure python
except (EnvironmentError, ImportError):

    def inverse_mod(a, p):
        """
        Compute the modular inverse of a (mod p)

        :param a:
            An integer

        :param p:
            An integer

        :return:
            An integer
        """

        if a < 0 or p <= a:
            a = a % p

        # From Ferguson and Schneier, roughly:

        c, d = a, p
        uc, vc, ud, vd = 1, 0, 0, 1
        while c != 0:
            q, c, d = divmod(d, c) + (c,)
            uc, vc, ud, vd = ud - q * uc, vd - q * vc, uc, vc

        # At this point, d is the GCD, and ud*a+vd*p = d.
        # If d == 1, this means that ud is a inverse.

        assert d == 1
        if ud > 0:
            return ud
        else:
            return ud + p


def fill_width(bytes_, width):
    """
    Ensure a byte string representing a positive integer is a specific width
    (in bytes)

    :param bytes_:
        The integer byte string

    :param width:
        The desired width as an integer

    :return:
        A byte string of the width specified
    """

    while len(bytes_) < width:
        bytes_ = b'\x00' + bytes_
    return bytes_