예제 #1
0
 def from_RSA(klass, keyobj):
     return {
         'algorithm': 'RSA',
         'modulus': b64encode(str(keyobj.e)),
         'exponent': b64encode(str(keyobj.n)),
         'keyid': datetime.now().isoformat(),
     }
예제 #2
0
 def from_ECDSA(klass, keyobj):
     point = keyobj.pubkey.point
     curve = 'P-%s' % keyobj.curve.name[4:7] # e.g. NIST256p, we only want the 256
     return {
         'algorithm': 'ECDSA',
         'curve': curve,
         'x': b64encode(str(point.x())),
         'y': b64encode(str(point.y())),
         'keyid': datetime.now().isoformat(),
     }
예제 #3
0
 def displaySignature(self, sig):
     if sig == "None":
         self.ui.signatureTextEdt.setText("Signature refused by the user")
         return
     from utils import b64encode
     self.ui.signatureTextEdt.setText(b64encode(sig))
     self.ui.copyBtn.setVisible(True)
     self.ui.saveBtn.setVisible(True)
     # verify sig
     ok = ecdsa_verify_addr(self.ui.messageTextEdt.toPlainText(), b64encode(sig), self.currAddress)
     if not ok:
         mess = "Signature doesn't verify."
         myPopUp_sb(self.main_wnd, QMessageBox.Warning, 'SPMT - no signature', mess)
예제 #4
0
    def download(self, url):
        try:
            print 'downloading {}'.format(url)
            if url in self.cache:
                return True
            name = utils.b64encode(url)
            req = urllib2.Request(url)
            req.add_header(
                'User-Agent',
                'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36'
            )
            req.add_header('Accept-encoding', 'gzip')
            response = urllib2.urlopen(req, timeout=100)
            if response.info().get('Content-Encoding') == 'gzip':
                buf = StringIO(response.read())
                f = gzip.GzipFile(fileobj=buf)
                link = f.read()
            else:
                link = response.read()
            response.close()

            with open(os.path.join(self.dir, name), 'wb') as output:
                output.write(link)
            #urllib.urlretrieve(url, os.path.join(self.dir, name))
            if os.path.isfile(os.path.join(self.dir, name)):
                print 'downloaded {}'.format(url)
                self.add(url, os.path.join(self.dir, name))
                return True
            print 'Failed to download {}'.format(url)
            return False
        except:
            traceback.print_exc(file=sys.stdout)
            return False
예제 #5
0
 def append(self, callback, args=(), kwargs={}, params={}, key=None):
     name = callback.__name__
     if not callback in self.views.values():
         raise ValueError(u'%s is not defined.' % callback)
     count = len(self.stack)  # + 1
     token = utils.token_encode(name, args, kwargs, count)
     if self.mask_key:
         token = utils.encrypt_by_key(token, self.mask_key)
     token = utils.b64encode(token)
     self.stack.append((token, params))
     if key:
         self.relation[key] = count
예제 #6
0
 def finalizeStartMessage_end(self, text):
     # decode message
     ret = self.caller.rpcClient.decodemasternodebroadcast(text)
     # find masternode in list and check
     for mnode in self.mnode_list:
         ip_addr = mnode.ip + ":" + mnode.port
         if ret['addr'] == ip_addr:
             # check ping signature
             ping_sig = b64encode(text[638:768])
             self.assertEqual(ret['lastPing'].get('vchSig'), ping_sig)
             # check nLastDsq
             self.assertEqual(ret['nLastDsq'], 0)
             # check protocol version
             pv = self.rpcClient.getProtocolVersion()
             self.assertEqual(ret['protocolVersion'], pv)
             # check masternode pubkey1
             self.assertEqual(ret['pubkey'], mnode['collateral'].get('address'))
             # check masternode pubkey2
             pk2 = pubkey_to_address(privkey_to_pubkey(mnode.mnPrivKey))
             self.assertEqual(ret['pubkey2'], pk2)
             # check masternode signature
             node_sig = b64encode(text[320:450])
             self.assertEqual(ret['vchSig'], node_sig)
예제 #7
0
    def signMess(self, path, message):
        from utils import b64encode
        # Ledger doesn't accept characters other that ascii printable:
        # https://ledgerhq.github.io/btchip-doc/bitcoin-technical.html#_sign_message
        message = message.encode('ascii', 'ignore')
        self.device.chip.signMessagePrepare(path, message)
        signature = self.device.chip.signMessageSign(None)
        if signature is not None:
            if len(signature) > 4:
                rLength = signature[3]
                r = signature[4:4 + rLength]
                if len(signature) > 4 + rLength + 1:
                    sLength = signature[4 + rLength + 1]
                    if len(signature) > 4 + rLength + 2:
                        s = signature[4 + rLength + 2:]
                        if rLength == 33:
                            r = r[1:]
                        if sLength == 33:
                            s = s[1:]

                        work = bytes(chr(27 + 4 + (signature[0] & 0x01)),
                                     "utf-8") + r + s
                        print("Message signed")
                        sig1 = work.hex()
                    else:
                        print(
                            'client.signMessageSign() returned invalid response (code 3): '
                            + signature.hex())
                        sig1 = "None"
                else:
                    print(
                        'client.signMessageSign() returned invalid response (code 2): '
                        + signature.hex())
                    sig1 = "None"
            else:
                print(
                    'client.signMessageSign() returned invalid response (code 1): '
                    + signature.hex())
                sig1 = "None"
        else:
            print("Signature refused by the user")
            sig1 = "None"

        return b64encode(sig1)
예제 #8
0
    def handle(request_content, formatter):
        receipt_id = request_content['receipt_id']
        try:
            filename = lite.DbDataGetter.get_field(tables.get_table_name(TableType.RECEIPTS),
                                                   'name',
                                                   receipt_id)

            table_name = tables.get_table_name(TableType.EXTRACTED_RECEIPTS_TEXTS_TABLE)
            extracted_receipt_text = lite.DbDataGetter.get_field(table_name,
                                                                 'txt',
                                                                 receipt_id,
                                                                 'receipt_id')

            filename = 'data/received_images/' + filename
            file_message_content = image.prepare_image_for_message(filename)
            response_content = {
                'file': file_message_content,
                'text': utils.b64encode(extracted_receipt_text)
            }
            return formatter.format(ResponseErrorCode.OK, response_content)

        except lite.NotFoundInDbException:
            return formatter.format(ResponseErrorCode.RECEIPT_ID_NOT_FOUND,
                                    {'receipt_id': receipt_id})
예제 #9
0
from utils import b64encode, jencode

import json
import base64

if __name__ == "__main__":
    G = PairingGroup('SS512')

    g = input("g: ")
    g = G.random(G1) if g == "" else G.deserialize(base64.b64decode(g))
    skey = G.random(ZR)
    pkey = g**skey
    m = G.random(ZR)

    pk = {"g": g, "pk": pkey}
    sk = {"g": g, "pk": pkey, "sk": skey}
    mg = {"m": m}

    print("Generated credentials: {}".format(
        json.dumps(b64encode(sk), indent=4)))

    with open("cred.pk", "w+") as f:
        f.write(jencode(pk))

    with open("cred.sk", "w+") as f:
        f.write(jencode(sk))

    with open("msg.mg", "w+") as f:
        f.write(jencode(mg))
예제 #10
0
파일: aes.py 프로젝트: stryku/hb
 def encrypt(self, raw):
     raw = self._pad(raw)
     iv = Random.new().read(AES.block_size)
     cipher = AES.new(self.key, AES.MODE_CBC, iv)
     return utils.b64encode(iv + cipher.encrypt(raw))