-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprimitives.py
67 lines (52 loc) · 1.81 KB
/
primitives.py
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
import random
from Crypto.Cipher import AES as AES_C
from Crypto.PublicKey import RSA
def random_string(length):
"""
Function to generate a random string of ``length`` bytes.
:param length: length of string to generate in bytes
:return: Random string of size length.
"""
if length < 0: return None
return ''.join(chr(random.randrange(256)) for _ in range(length))
def random_string_bits(bits):
"""
Generates a string of ``floor(bits/8)`` size.
:param bits: How long string should be in bits.
:return: Random string of bit length ``floor(bits/8)``.
"""
return random_string((bits / 8))
def AES(k, m):
"""
Encrypts m with AES in ECB mode.
:param k: can be 16, 24 or 32 bytes long
:param m: should be multiple of 128 bits long
:return: cipher text
"""
cipher = AES_C.new(k)
return cipher.encrypt(bytes(m))
def AES_I(k, m):
"""
Decrypts m with AES in ECB mode.
:param k: can be 16, 24 or 32 bytes long
:param m: should be multiple of 128 bits long
:return: plaintext
"""
cipher = AES_C.new(k)
return cipher.decrypt(bytes(m))
def rsa_keygen(len):
"""
RSA keygen algorithm returns a dictionary containing values for
(n, e, d, p, q).
:param len: Length of key in bytes that you would like to generate. Must
be a multiple of 32 bytes and greater than 128 bytes.
:return: A dictionary containing the standard RSA key components
(n - modulo, e - encryption exponent, d - decryption exponent,
p - first factor of n, q - second factor of n).
"""
r = RSA.generate(len * 8)
return {'n': getattr(r.key, 'n'),
'e': getattr(r.key, 'e'),
'd': getattr(r.key, 'd'),
'p': getattr(r.key, 'p'),
'q': getattr(r.key, 'q')}