File: crypto.py

package info (click to toggle)
python-braintree 3.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,376 kB
  • ctags: 1,998
  • sloc: python: 13,634; makefile: 73; sh: 8
file content (41 lines) | stat: -rw-r--r-- 1,287 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
import hashlib
import hmac
import sys

if sys.version_info[0] == 2:
    text_type = unicode
else:
    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 == None or right == 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