CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/data/meterpreter/python/met_rsa.py
Views: 11780
1
import sys
2
import math
3
import random
4
import binascii as ba
5
import os
6
from struct import unpack as u
7
from struct import pack
8
is2 = sys.version_info[0] < 3
9
10
11
def bt(b):
12
if is2:
13
return b
14
return ord(b)
15
16
17
def b2i(b):
18
return int(ba.b2a_hex(b), 16)
19
20
21
def i2b(i):
22
h = '%x' % i
23
if len(h) % 2 == 1:
24
h = '0' + h
25
if not is2:
26
h = h.encode('utf-8')
27
return ba.a2b_hex(h)
28
29
30
def rs(a, o):
31
if a[o] == bt(pack('B', 0x81)):
32
return (u('B', a[o + 1])[0], 2 + o)
33
elif a[o] == bt(pack('B', 0x82)):
34
return (u('>H', a[o + 1:o + 3])[0], 3 + o)
35
36
37
def ri(b, o):
38
i, o = rs(b, o)
39
return (b[o:o + i], o + i)
40
41
42
def b2me(b):
43
if b[0] != bt(pack('B', 0x30)):
44
return (None, None)
45
_, o = rs(b, 1)
46
if b[o] != bt(pack('B', 2)):
47
return (None, None)
48
(m, o) = ri(b, o + 1)
49
if b[o] != bt(pack('B', 2)):
50
return (None, None)
51
e = b[o + 2:]
52
return (b2i(m), b2i(e))
53
54
55
def der2me(d):
56
if d[0] != bt(pack('B', 0x30)):
57
return (None, None)
58
_, o = rs(d, 1)
59
while o < len(d):
60
if d[o] == bt(pack('B', 0x30)):
61
o += u('B', d[o + 1:o + 2])[0]
62
elif d[o] == bt(pack('B', 0x05)):
63
o += 2
64
elif d[o] == bt(pack('B', 0x03)):
65
_, o = rs(d, o + 1)
66
return b2me(d[o + 1:])
67
else:
68
return (None, None)
69
70
71
def rsa_enc(der, msg):
72
m, e = der2me(der)
73
h = pack('BB', 0, 2)
74
d = pack('B', 0)
75
l = 256 - len(h) - len(msg) - len(d)
76
p = os.urandom(512).replace(pack('B', 0), pack(''))
77
return i2b(pow(b2i(h + p[:l] + d + msg), e, m))
78
79