File: crypto.py

package info (click to toggle)
python-braintree 4.31.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,576 kB
  • sloc: python: 28,946; makefile: 9; sh: 8
file content (38 lines) | stat: -rw-r--r-- 1,224 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
import hashlib
import hmac
import sys

text_type = str

class Crypto:
    @staticmethod
    def sha1_hmac_hash(secret_key, content):
        if isinstance(secret_key, text_type):
            secret_key = secret_key.encode('ascii')
        if isinstance(content, text_type):
            content = content.encode('ascii')
        return hmac.new(hashlib.sha1(secret_key).digest(), content, hashlib.sha1).hexdigest()

    @staticmethod
    def sha256_hmac_hash(secret_key, content):
        if isinstance(secret_key, text_type):
            secret_key = secret_key.encode('ascii')
        if isinstance(content, text_type):
            content = content.encode('ascii')
        return hmac.new(hashlib.sha256(secret_key).digest(), content, hashlib.sha256).hexdigest()

    @staticmethod
    def secure_compare(left, right):
        if left is None or right is None:
            return False

        left_bytes = [ord(char) for char in left]
        right_bytes = [ord(char) for char in right]

        if len(left_bytes) != len(right_bytes):
            return False

        result = 0
        for left_byte, right_byte in zip(left_bytes, right_bytes):
            result |= left_byte ^ right_byte
        return result == 0