Esempio n. 1
0
 def chose_boundary(self):
     boundary = ssl.RAND_bytes(10)
     while True:
         flag = False
         for attachment in self.attachments:
             if attachment.find(boundary) != -1:
                 flag = True
                 break
         if flag:
             boundary = ssl.RAND_bytes(10)
         else:
             break
     return boundary
Esempio n. 2
0
def output_stdout():
    fd = sys.stdout.fileno()
    try:
        while True:
            os.write(fd, ssl.RAND_bytes(block))
    except KeyboardInterrupt:
        pass
Esempio n. 3
0
def main():
    import ssl
    import os
    from lab._bootstrap import connect_db

    cookie_secret = base64.urlsafe_b64encode(ssl.RAND_bytes(32)).decode()

    config = {
        'web_settings': {
            'cookie_secret': cookie_secret
        },
        'server_name': cfg['server_name'],
        'visa_backends': cfg['visa_backends'],
    }

    ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    ssl_ctx.load_cert_chain(cfg['ssl']['cert'], cfg['ssl']['key'])

    connect_db()
    server = InstrumentServer(config=config,
                              port=cfg.get('server_port', DEFAULT_PORT),
                              ssl_options=ssl_ctx)
    try:
        from . import ui
        import sys
        app = ui.QtWidgets.QApplication(sys.argv)
        win = ui.InstruentServerMainWindow(server)
        win.show()
        sys.exit(app.exec_())
    except:
        server.run_for_ever()
Esempio n. 4
0
async def create_consumer(request, consumer, reuse):
    '''
    createConsumer(consumer, reuse)
    create a consumer for test, note that this methods is *ONLY* used for testing. Production consumer can be created using `bbox.py run aiobbox.contrib.consumer.create_consumer <name>`
    '''
    if not testing.test_mode:
        raise ServiceError('access denied')

    if (not isinstance(consumer, str) or not re.match(r'\w+$', consumer)):
        raise ServiceError('invalid consumer')

    cfg = get_sharedconfig()
    coptions = cfg.get('consumers', consumer)
    #if coptions:
    #    raise ServiceError('consumer already exist',
    #                       msg='already exist {}'.format(coptions))
    if coptions and reuse:
        return {'consumer': consumer, 'secret': coptions['secret']}

    coptions = {}
    coptions['secret'] = uuid.uuid4().hex
    coptions['seed'] = ssl.RAND_bytes(256).hex()

    c = get_cluster()
    await c.set_config('consumers', consumer, coptions)

    # TODO: limit the consumer size
    return {'consumer': consumer, 'secret': coptions['secret']}
Esempio n. 5
0
    async def run(self, args):
        consumer = args.consumer
        if not consumer:
            raise Exception('void consumer')

        if not re.match(r'\w+$', consumer):
            raise Exception('invalid consumer')

        cfg = get_sharedconfig()
        coptions = cfg.get('consumers', consumer)
        if coptions:
            print('consumer {} already exist, secret is {}'.format(
                consumer, coptions['secret']))
            return

        coptions = {}
        coptions['secret'] = uuid.uuid4().hex
        coptions['seed'] = ssl.RAND_bytes(256).hex()

        c = get_cluster()
        await c.set_config('consumers', consumer, coptions)

        # TODO: limit the consumer size

        print('secret for', consumer, coptions['secret'])
Esempio n. 6
0
def extract_random_elements_in_list_or_generate_some_random_elements():
    # Use Mersenne Twister Algorithm
    import random
    values = [1, 2, 3, 4, 5, 6]
    print(random.choice(values))
    print(random.choice(values))
    print(random.choice(values))
    print(random.sample(values, 2))
    print(random.sample(values, 3))

    # Disrupt the order of the elements in the sequence
    random.shuffle(values)
    print(values)

    # Generate random int
    print(random.randint(0, 10))

    # Generate floating number in the range of 0 to 1
    print(random.random())

    # To get random number of N
    print(random.getrandbits(200))

    # change init seed
    random.seed()  # Seed based on system time or os.urandom()
    random.seed(12345)  # Seed based on integer given
    random.seed(b'bytedata')  # Seed based on byte data

    # but the random packages should not use the program about Cryptography
    # Use the ssl.RAND_bytes()
    import ssl
    ssl.RAND_bytes()
Esempio n. 7
0
def randomdata(count=10000):
    data = []
    for i in range(count):
        r = random.randint(8, 64)
        text = binascii.b2a_hex(ssl.RAND_bytes(r)).decode()
        data.append((r, text))

    return data
Esempio n. 8
0
def padding(addr: bytes, padding_length: int) -> bytes:
    addr_length = len(addr)
    if addr_length >= padding_length:
        raise ValueError('padding length over limitation')
    payload = bytearray(b'')
    payload.append(addr_length)
    payload.extend(addr)
    pads = ssl.RAND_bytes(padding_length - addr_length - 1)
    payload.extend(pads)
    return payload
Esempio n. 9
0
def get_retid():
    global gr_idmap
    global ret_idmap

    gr = greenlet.getcurrent()
    grid = id(gr)
    retid = SHA512.new(uuid.uuid1().bytes + ssl.RAND_bytes(64)).hexdigest()

    gr_idmap[grid].add(retid)
    ret_idmap[retid] = gr

    return retid
Esempio n. 10
0
def reset(size=11):
    if ssl is not None and sys.version_info[:2] >= (3, 3):
        sessionId = ssl.RAND_bytes(size)
    else:
        try:
            sessionId = os.urandom(size)
        except NotImplementedError:
            sessionId = ""
            while len(sessionId) < size:
                sessionId += str(random.random())[2:] # Skip leading "0."
            sessionId = sessionId[:size].encode("utf-8")
    _private[_sessionIDkey] = sessionId
    return sessionId
Esempio n. 11
0
def speed():
    try:
        start = time.time()
        data_sum = 0
        while True:

            ssl.RAND_bytes(block)

            data_sum += 1

            end = time.time()
            interval = end - start
            if interval >= 1:
                print(round(data_sum / interval, 2), "MB", "interval time: ",
                      round(interval, 3), "秒")
                data_sum = 0
                start = time.time()

    except KeyboardInterrupt:
        pass
Esempio n. 12
0
def get_soaringspot_auth_string(client_id, secret):
    import hashlib
    import hmac
    import ssl
    import random
    import base64

    nonce = base64.b64encode(ssl.RAND_bytes(random.randint(
        12, 30))).decode('utf-8')
    created = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")

    data = nonce + created + client_id
    signature = base64.b64encode(
        hmac.new(secret.encode('utf-8'),
                 msg=data.encode('utf-8'),
                 digestmod=hashlib.sha256).digest()).decode('utf-8')
    auth_string = 'http://api.soaringspot.com/v1/hmac/v1 ClientID="{0}", Signature="{1}", Nonce="{2}", Created="{3}"' \
        .format(client_id, signature, nonce, created)

    return auth_string
Esempio n. 13
0
def get_set_secret():
    global WAITTIME
    global PORT
    global SECRET
    if cfg.exists():
        with open(cfg) as f:
            data = json.load(f)

        SECRET = data["secret"]
        PORT = data["port"]
        WAITTIME = data["waittime"]

    else:
        SECRET = binascii.b2a_hex(ssl.RAND_bytes(16)).decode()
        with open(cfg, "w") as f:
            json.dump({
                "waittime": WAITTIME,
                "port": PORT,
                "secret": SECRET
            },
                      f,
                      ensure_ascii=False,
                      indent=4)
    def sendfile(self, dst_link, filepath):
        def _callback(err):
            if self._ret_sendfile(filekey, err) and err != None:
                with Auth.change_current_iden(self._idendesc, self._auth):
                    self.call(dst_link + 'imc/', 'abort_sendfile', 65536,
                              filekey, err)

        filekey = SHA512.new(uuid.uuid1().bytes +
                             ssl.RAND_bytes(64)).hexdigest()
        filesize = os.stat(filepath).st_size

        fileresult = FileResult(filekey)

        self._info_filekeymap[filekey] = {
            'filesize':
            filesize,
            'filepath':
            filepath,
            'fileresult':
            fileresult,
            'timer':
            self._ioloop.add_timeout(
                datetime.timedelta(days=1),
                lambda: self._ret_sendfile(filekey, 'Etimeout')),
            'callback':
            tornado.stack_context.wrap(_callback)
        }

        with Auth.change_current_iden(self._idendesc, self._auth):
            stat, ret = self.call(dst_link + 'imc/', 'pend_recvfile', 65536,
                                  self._link, filekey, filesize)

        if stat == False:
            self._ret_sendfile(filekey, 'Enoexist')

        return fileresult
Esempio n. 15
0
def main(datasize):

    with open("test.dd", "wb") as f:
        for i in range(datasize):
            f.write(ssl.RAND_bytes(block))
            f.flush()
Esempio n. 16
0
def get_key_enc() -> Tuple[str, str]:
    key = "".join((f"{i:02X}" for i in ssl.RAND_bytes(16)))
    return key, encrypt_key(key)
Esempio n. 17
0
def encrypt_key(key: str, salt: str = None) -> str:
    if salt is None:
        salt = "".join(f"{i:02X}" for i in ssl.RAND_bytes(16))
    return hashlib.sha512(key.encode('utf-8') + salt.encode('utf8')).hexdigest() + "::" + salt
Esempio n. 18
0
 def ssl8():
     try:
         return ssl.RAND_bytes(8)
     except:
         return ""  # Do not block - return nothing
Esempio n. 19
0
def generate_random_password():
    return ssl.RAND_bytes(20).hex()
Esempio n. 20
0
d = datetime(2016, 5, 12)
print(d)  # 2016-05-12 00:00:00
print(d + c)  # 2016-05-15 04:00:00

# 11 随机选择 random ssl.RAND_bytes()密码中的随机生产方法
values = [23, 45, '345', 'saf']
print(random.choice(values))  # one
print(random.sample(values, 2))  # [23, 'saf']随机个数
print(values)
random.shuffle(values)  # 随机打乱 like php shuffle函数
print(values)

print(random.randint(2, 4))  # [2, 4]之间
print(random.random())  # 0~1
print(ssl.RAND_bytes(2))

# 10 矩阵与线性代数 np.matrix
m = np.matrix([[1, 2, 3], [-3, -5, -7], [9, 8, 7]])
print(m)

# 9 大型数组计算 numpy
x = [1, 2, 3, 4]
y = [5, 6, 7, 8, 9]
print(x * 2)  # [1, 2, 3, 4, 1, 2, 3, 4]
print(x + y)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

ax = np.array([1, 2, 3, 4])
ay = np.array([5, 6, 7, 8])
print(ax * 2)  # [2 4 6 8]
print(ay + ax)  # 位数需一致 [ 6  8 10 12]
print(det(m), eigvals(m))

# 随机选择 random模块
import random
a = [1, 2, 3, 4, 5, 6, 7, 8]
print("1st:", random.choice(a))
print("2nd:", random.choice(a))
print("1st:", random.sample(a, 2))
print("2nd:", random.sample(a, 3))
random.shuffle(a)
print("shuffle:", a)
# random模块使用 Mersenne Twister 算法计算生成随机数(类似C语言中的伪随机数),但是可以通过提供不同的种子来达到生成随机数的目的。
random.seed(1234)
print(random.randint(0, 13))
import ssl
print(ssl.RAND_bytes(10))  # 密码学中会用到的随机生成方法

# 基本的日期和时间的转换
# 为了执行不同时间单位的转换和计算,需要使用datetime模块。为了表示一个时间块,可以创建一个timedelta实例。
from datetime import timedelta, datetime
a = timedelta(days=2, hours=10)
b = timedelta(days=1)
a_t = datetime(2018, 12, 1)
b_t = datetime(2017, 10, 12)
print(a + b, a.total_seconds() / 3600, a_t - b_t, a_t + a)
# 为了执行更加附加的日期操作,可以使用 dateutil 模块
from dateutil.relativedelta import relativedelta
print(a_t + relativedelta(months=1))
print(relativedelta(a_t, b_t))

# 字符串转化为日期
Esempio n. 22
0
# To get random-bits expressed as an integer, use random.getrandbits().

print(random.getrandbits(200))
"""The random module computes random numbers using the Mersenne Twister
algorithm. It's a deterministic algorithm, but you can alter the initial
seed by using the random.seed() function"""

print(random.seed())  # Seed based on system time or os.urandom()
print(random.seed(12345))  # Seed based on integer given
print(random.seed(b'bytedata'))  # Seed based on byte data
"""Functions in random() shouldn't be used in cryptography, use ssl
modules instead"""

import ssl

print(ssl.RAND_bytes(1))
print(ssl.RAND_bytes(5))

# 3.12 Converting Days to Seconds, & Other Basic Time Conversions

from datetime import timedelta

a = timedelta(days=2, hours=6)
b = timedelta(hours=4.5)
c = a + b

print(c.days)
print(c.seconds)
print(c.seconds / 3600)
print(c.total_seconds() / 3600)
"""If you need specific dates & times, create datetime instances &
Esempio n. 23
0
# To take a sampling of N items where selected items are removed from further
# consideration, use random.sample().
print(random.sample(values, 2))

# To shuffle items in a sequence in place, use random.shuffle().
random.shuffle(values)
print(values)

# To produce random integers, use random.randint().
print(random.randint(0, 10))

# To produce uniform floating-point values in the range 0 to 1, use
# random.random().
print(random.random())

# To get N random-bits expressed as an integer, use random.getrandbits().
print(random.getrandbits(200))

# The random module computes random numbers using the Mersenne Twister
# algorithm. This is a deterministic algorithm, but you can alter the initial
# seed by using the random.seed() function.
random.seed()
random.seed(12345)
random.seed(b'bytedata')

# Functions in random() should not be used in programs related to cryptography.
# If you need such functionality, consider using functions in the ssl module
# instead.
ssl.RAND_bytes(12345)
Esempio n. 24
0
 def create_ssl_key(filename, path):
     """创建*.key文件"""
     ssl_key = ssl.RAND_bytes(16)
     with open(os.path.join(path, filename + ".key"), "wb") as w:
         w.write(ssl_key)
Esempio n. 25
0
print(random.random())
print(random.random())
print(random.random())
print()

# N random bits expressed as an integer
print(random.getrandbits(1))
print(random.getrandbits(1))
print(random.getrandbits(1))
print(random.getrandbits(1))
print(random.getrandbits(5))
print(random.getrandbits(50))
print()

# python uses Mersenne Twister algorithm for randoms, which is deterministic. However, the initial seed can be changed
random.seed()               # set seed based on system time or os.urandom()
random.seed(12345)          # seed based on provided integer
random.seed(b'bytedata')    # seed from byte data
print()

# random.uniform() produces uniformly distributed numbers
print(random.uniform(0, 10))
print()

# note: the random module should not be used for cryptography since it's not truly random. For cryptographic purposes
# consider using the ssl module instead
x = ssl.RAND_bytes(5)
print(x)
print(int.from_bytes(x, 'little'))
print(int.from_bytes(x, 'big'))
Esempio n. 26
0
def randomize_ssl_after_fork():
    ssl.RAND_add(ssl.RAND_bytes(10), 0.0)
Esempio n. 27
0
 def new_id(self):
     self.sessionid = str(uuid.UUID(bytes=ssl.RAND_bytes(16)))
     return self.sessionid
Esempio n. 28
0
 def update_event(self, inp=-1):
     self.set_output_val(0, ssl.RAND_bytes(self.input(0)))