예제 #1
0
    def verify(self, s, signature):
        """
        Check the signature of the string s

        :param s: String to check
        :type s: str
        :param signature: the signature to compare
        :type signature: str
        """
        if isinstance(s, text_type):
            s = s.encode('utf8')
        r = False
        try:
            RSAkey = RSA.importKey(self.public)
            signature = long(signature)
            if SIGN_WITH_RSA:
                hashvalue = HashFunc.new(s).digest()
                r = RSAkey.verify(hashvalue, (signature,))
            else:
                hashvalue = HashFunc.new(s)
                pkcs1_15.new(RSAkey).verify(hashvalue, signature)
        except Exception as _e:  # pragma: no cover
            log.error("Failed to verify signature: {0!r}".format(s))
            log.debug("{0!s}".format(traceback.format_exc()))
        return r
예제 #2
0
파일: crypto.py 프로젝트: STRML/privacyidea
 def verify(self, s, signature):
     """
     Check the signature of the string s
     """
     r = False
     try:
         RSAkey = RSA.importKey(self.public)
         signature = long(signature)
         if SIGN_WITH_RSA:
             hashvalue = HashFunc.new(s).digest()
             r = RSAkey.verify(hashvalue, (signature,))
         else:
             hashvalue = HashFunc.new(s)
             pkcs1_15.new(RSAkey).verify(hashvalue, signature)
     except Exception:  # pragma: no cover
         log.error("Failed to verify signature: {0!r}".format(s))
         log.debug("{0!s}".format(traceback.format_exc()))
     return r
예제 #3
0
    def verify_signature(data, signature, public_key):
        """
        SHA-256 is used for verifying digital signature
        public key - public key of the user
        :param data: this is the data for which the signature needs to be calculated
        :param signature: this is the signature value
        :return: returns whether the signature of data and signature passed as a argument is same or not.
                 if same the it will return true or else it will return false.
        """

        #key = RSA.import_key(open('public_key.der').read())
        key = public_key
        message = data.encode()
        h = SHA256.new(message)
        try:
            pkcs1_15.new(key).verify(h, signature)
            return True
        except (ValueError, TypeError):
            return False
예제 #4
0
 def create_signature(self, data):
     signatureobject = pkcs1_15.new(self.my_privatekey)  # hozz létre egy signature objektumot
     hashobject = self.create_hashobject(
         data)  # az adatot töltsd be egy hash objektumba a create_hashobject(data) használatával
     signaturevalue = signatureobject.sign(hashobject)  # készítsd el az aláírás értéket a sign függvénnyel
     print(signaturevalue)
     b64signaturevalue = b64encode(signaturevalue)  # kódold base64 kódolással
     print(b64signaturevalue)
     print(b64signaturevalue.decode())
     return b64signaturevalue.decode()
예제 #5
0
    def test_verify(self, tv):
        self._id = "Wycheproof RSA PKCS$#1 Test #" + str(tv.id)

        hashed_msg = tv.hash_module.new(tv.msg)
        signer = pkcs1_15.new(tv.key)
        try:
            signature = signer.verify(hashed_msg, tv.sig)
        except ValueError, e:
            if tv.warning:
                return
            assert not tv.valid
예제 #6
0
def get_signature(msg: bytes, private: str, passphrase=None):
    """
    Gets the Signature of a given message
    :param msg: Bytes object to sign
    :param private: Private key to use
    :param passphrase: Passphrase for the key
    :return: Bytes object signature
    """
    key = RSA.importKey(private, passphrase)
    dig = SHA256.new(msg)
    return pkcs1_15.new(key).sign(dig)
예제 #7
0
 def __init__(self, public_key:bytes):
     """
     根据提供的public_key初始化PublicCipher.
     @param public_key: 客户公钥
     """
     try:
         self.key = RSA.import_key(public_key)
         self.cipher = PKCS1_OAEP.new(self.key)
         self.verifier = pkcs1_15.new(self.key)
     except(ValueError, TypeError):
         print("导入公钥出错: %s" % public_key)
예제 #8
0
def comprobar_firma(self, file_name, firma):
    fich = open('keys/public.pem', 'rb')
    public_key = RSA.import_key(
        fich.read())  # Obtenemos la clave pública de 'public.pem'.
    fich.close()

    hash = calcularHash(
        self, file_name
    )  # Calculamos el hash del archivo o documento que hemos obtenido.

    try:
        """
        Con la clave pública, obtenemos el hash previamente calculado del archivo (hash del emisor).
        A continuación, comparamos este hash con el que hemos calculado sobre el archivo que hemos recibido (hash del receptor).
        """
        pkcs1_15.new(public_key).verify(hash, firma)
        self.listWidget.addItem("La firma es válida.")

    except (ValueError, TypeError):
        self.listWidget.addItem("La firma no es válida.")
예제 #9
0
def post_note():
    data = request.get_json()
    message = (data.get("message")
               if data else "<p>Trying to post a message!</p>")
    host = data.get("host") if data else "mastodon.social"
    toot = data.get("toot") if data else "@Gargron/100254678717223630"
    toot_url = f"https://{host}/{toot}"

    now = datetime.utcnow()
    formatted_now = now.strftime("%a, %d %b %Y %H:%M:%S GMT")
    activity = {
        "@context": "https://www.w3.org/ns/activitystreams",
        "id": f"https://{actor.domain}/create-test-note",
        "type": "Create",
        "actor": actor.ap_id,
        "object": {
            "id": f"https://{actor.domain}/note-message",
            "type": "Note",
            "published": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
            "attributedTo": actor.ap_id,
            "inReplyTo": toot_url,
            "content": message,
            "to": "https://www.w3.org/ns/activitystreams#Public",
        },
    }

    signed_string = (
        f"(request-target): post /inbox\nhost: {host}\ndate: {formatted_now}")
    key = RSA.import_key(actor.private_key)
    key_signer = pkcs1_15.new(key)
    encoded_string = signed_string.encode("utf-8")
    h = SHA256.new(encoded_string)
    signature = base64.b64encode(key_signer.sign(h))
    header = (f'keyId="{actor.ap_id}",headers="(request-target) host date",'
              f'signature="' + signature.decode() + '"')

    resp = requests.post(
        f"https://{host}/inbox",
        data=json.dumps(activity),
        headers={
            "Host": host,
            "Date": formatted_now,
            "Signature": header,
            "Content-Type": "application/ld+json",
        },
    )
    if resp.status_code >= 400:
        print(resp.text)
        response = {"status": "error"}
    else:
        response = {"status": "created"}
    code = resp.status_code

    return jsonify(response), code
예제 #10
0
 def verify(cls, message, sign, pubkey):
     """ 验证签名
         https://legrandin.github.io/pycryptodome/Doc/3.2/Crypto.Signature.pkcs1_15-module.html
     """
     from Crypto.Signature import pkcs1_15
     from Crypto.Hash import SHA256
     from Crypto.PublicKey import RSA
     res = False
     sign = base64.b64decode(sign)
     # print('sign', type(sign), sign)
     try:
         key = RSA.importKey(pubkey)
         h = SHA256.new(message.encode('utf8'))
         pkcs1_15.new(key).verify(h, sign)
         res = True
     except (ValueError, TypeError) as e:
         raise e
     except Exception as e:
         raise e
     return res
def verify(key, signature, msg):
    try:
        verifier = pkcs1_15.new(RSA.import_key(key))
        msg = bytes(msg, encoding='utf-8')
        hash = SHA256.new(msg)
        verifier.verify(hash, signature)
        print('Signature is valid')
        return True
    except (ValueError, TypeError):
        print('Signature is not valid')
        return False
예제 #12
0
 def __init__(self, private_key:bytes):
     """
     根据提供的private_key初始化PrivateCipher.
     @param private_key: 私钥输入。
     """
     try:
         self.key = RSA.import_key(private_key)
         self.cipher = PKCS1_OAEP.new(self.key)
         self.signer = pkcs1_15.new(self.key)
     except(ValueError, TypeError):
         print("导入私钥出错: %s" % private_key)
예제 #13
0
def digital_sign(message, sender_priv_key_file):
    try:
        # Getting key from the file where it's stored
        key = RSA.import_key(open(sender_priv_key_file).read())
        # Hashing the data with SHA256
        h = SHA256.new(message)
        # Signature
        signature = pkcs1_15.new(key).sign(h)
        return signature
    except:
        raise ValueError("ERROR: Unable to sign the message")
예제 #14
0
def handshake(client_socket):
    confirmation_bytes = get_random_bytes(16)
    username = client_socket.recv(1024).decode('utf-8')
    hashed_bytes = SHA256.new(confirmation_bytes)

    client_socket.send(confirmation_bytes)
    confirmation_data = client_socket.recv(1024)

    public_key = read_public_key(username)
    try:
        pkcs1_15.new(public_key).verify(hashed_bytes, confirmation_data)
        rsa_cipher = PKCS1_OAEP.new(public_key)
        client_socket.sent("Welcome".encode('utf-8'))
        encrypted_session_key = rsa_cipher.encrypt(SESSION_KEY)
        client_socket.send(encrypted_session_key)
        connected_clients.append((client_socket, username))
        return True
    except (ValueError, TypeError):
        client_socket.send('Identity could not be confirmed. Connection terminated.'.encode('uff-8'))
    return False
예제 #15
0
    def sign_bson_data(self, data_bson):
        # generate hash
        hash = SHA384.new()
        hash.update(data_bson)

        # Sign with pvt key
        signer = pkcs1_15.new(self.priv_key)
        signature = signer.sign(hash)
        signature = base58.b58encode(signature).decode("utf-8")

        return signature
예제 #16
0
def verify_signature():
    with open("Подпись.txt", 'rb') as f:
        sign = f.read()
    f.close()

    with open("Ключ.pem", 'rb') as f:
        key_data = f.read()
        pubkey = RSA.import_key(key_data)

    # Получаете хэш файла
    file_hash = SHA256.new()
    with open("Отчет.docx", "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            file_hash.update(chunk)
    # Отличающийся хэш не должен проходить проверку
    try:
        pkcs1_15.new(pubkey).verify(file_hash, sign)
        return "Проверка пройдена успешно"
    except ValueError:
        return "Файл не прошел проверку"
예제 #17
0
def verification(message, sign, public_key):
    ## 署名の検証
    """
    verify(msg_hash, signature)
        Parameters
            msg_hash (hash object)
            signature  (byte string) 
        return: Nothing

        Raises: ValueError –if the signature is not valid.
    """

    h2 = SHA256.new(message.encode())
    try:
        pkcs1_15.new(public_key).verify(h2, sign)
        verified = "The signature is valid."
    except ValueError:
        verified = "The signature is not valid."

    return verified
예제 #18
0
def sign_message(message, name):
    try:
        m = message
        h = SHA256.new(m)
        path = os.path.join("Dictionary", name)
        path = os.path.join(path, name + '_private_key.pem')
        key = RSA.import_key(open(path).read())
        signature = pkcs1_15.new(key).sign(h)
        return signature
    except FileNotFoundError as fnf:
        print(fnf)
예제 #19
0
def rsa_sign(private_key, message, charset):
    try:
        private_key = add_start_end(private_key,
                                    "-----BEGIN PRIVATE KEY-----\n",
                                    "\n-----END PRIVATE KEY-----")
        msg = message.encode(charset)
        private_key = RSA.importKey(private_key)
        hash_obj = SHA1.new(msg)
        signature = pkcs1_15.new(private_key).sign(hash_obj)
        return True, base64.b64encode(signature).decode(charset)
    except Exception as ex:
        return False, str(ex)
예제 #20
0
def comprobar_firma(firma, mensaje, ID_origen, token):

    print("Verificando firma...")

    clave_auxiliar = users.buscar_clave_publica(ID_origen, token)

    if clave_auxiliar == None:
        print("ERROR buscando clave")
        return None

    clave_publica = RSA.import_key(clave_auxiliar)

    try:
        pkcs1_15.new(clave_publica).verify(SHA256.new(mensaje), firma)
    except (ValueError, TypeError):
        print("ERROR verificando firma")
        return False

    print("OK, firma comprobada")

    return True
    def signMsg(msg, private_key):
        """Signs a message with a private key"""
        try:
            print(f"[*] Signing message")
            signer = pkcs1_15.new(private_key)  # Instantiate a new signer object using the senders private key
            hashed_msg = SHA256.new(msg)
            signature = signer.sign(hashed_msg)
            return signature

        except ValueError as error:
            print(f"[-] Error: {error}")
            return False
예제 #22
0
    def build_authorization_header(self):
        """Build authorization headers."""
        if len(self.required_authorization_headers) > 0:
            self.authorization_parameters['headers'] = '{}'.format(' '.join([
                header.lower()
                for header in self.required_authorization_headers
            ]))
        self.build_signing_string()
        signing_bytestring = self.signing_string.encode(self.encoding)
        if self.signing_algorithm == 'RSA':
            signer = RSA.import_key(self.private_key_string)
            if self.hashing_algorithm == 'SHA256':
                hash_obj = SHA256.new(signing_bytestring)
            elif self.hashing_algorithm == 'SHA512':
                hash_obj = SHA512.new(signing_bytestring)
            else:
                raise Exception("Invalid key type")
            signature = pkcs1_15.new(signer).sign(hash_obj)
        else:
            private_key, public_key = PEMEncoder.decode_private_key(
                self.private_key_string)
            if self.hashing_algorithm == 'SHA256':
                hash_function = hashlib.sha256
            elif self.hashing_algorithm == 'SHA512':
                hash_function = hashlib.sha512
            else:
                raise Exception("Invalid key type")

            if self.signing_algorithm.lower() == 'p256':
                r, s = ecdsa.sign(signing_bytestring,
                                  private_key,
                                  curve=curve.P256,
                                  hashfunc=hash_function)
            else:
                raise Exception("Invalid key type")
            signature = DEREncoder.encode_signature(r, s)
        base64_signature = base64.b64encode(signature).decode(self.encoding)
        self.authorization_parameters['signature'] = '{}'.format(
            base64_signature)
        authorization_rows = []
        for key, value in self.authorization_parameters.items():
            if isinstance(value, str):
                authorization_rows.append('{}="{}"'.format(key, value))
            elif isinstance(value, int) or isinstance(value, float):
                authorization_rows.append('{}={}'.format(key, value))
            elif isinstance(value, bool):
                if value is True:
                    authorization_rows.append('{}=true')
                else:
                    authorization_rows.append('{}=false')
        authorization_header = 'Signature {}'.format(
            ','.join(authorization_rows))
        self.headers['Authorization'] = authorization_header
예제 #23
0
def generate_certificate(s_public_key):
    """
    Generate the certificate.
        -Sign the message (ID_S + ID_CA + PK_S) using CA private key.
    """
    message = info.ID_Server.encode('utf-8') + info.ID_CA.encode(
        'utf-8') + s_public_key.export_key()
    # Compute SHA256 hash of message.
    digest = SHA256.new(message)
    # Create the certificate by signing the hash (digest) using the CA private key.
    certificate = pkcs1_15.new(ca_private_key).sign(digest)
    return certificate
예제 #24
0
    def verify_msg(self, hash_msg, msg):
        pubKey = RSA.importKey(open("server_public_key.pem", "rb").read())

        verifier = pkcs1_15.new(pubKey)
        hash_verify = SHA384.new()
        hash_verify.update(msg)
        try:
            verifier.verify(hash_verify, hash_msg)
        except ValueError:
            return False
        else:
            return True
예제 #25
0
def main():
    source = input("Enter file name: ")
    data = readFromFile(source)

    privateKey = RSA.generate(2048)
    publicKey = privateKey.publickey()

    hashed = SHA256.new(data)
    signature = pkcs1_15.new(privateKey).sign(hashed)

    writeToFile(signature, source + ".pem")

    signature = readFromFile(source + ".pem")
    data = readFromFile(source)

    hashed = SHA256.new(data)
    try:
        pkcs1_15.new(publicKey).verify(hashed, signature)
        print("VALID signature")
    except (ValueError, TypeError):
        print("INVALID signature")
예제 #26
0
 def sign(self, data):
     """
     Signs a piece of data using the stored key
     :param data: bytes
         Data to be signed
     :return: bytes
         Signature of the data
     """
     hash_obj = SHA384.new(data)
     signer = pkcs1_15.new(self.key)
     signature = signer.sign(hash_obj)
     return signature
예제 #27
0
    def encrypt(self, request):
        self.template_name = 'app/encryption.html'
        parser_classes = [FileUploadParser]

        if request.method == 'GET':
            serializer = self.get_serializer_class()
            return Response({'serializer': serializer(context={'request': request}), 'action': self.action})

        # plaintext from user
        data = request.data['content'].encode('utf-8')
        # did user request a signature
        signed = request.data['signed']

        # public key of the recipient to encrypt this message with
        # can access anyone's public key via a reference to their private key
        # this protect's the private key while also simplifying the database schema by
        # one model
        recipient_public_key = PrivateKey.objects.get(pk=request.data['recipient_private_key']) \
                                                 .get_public_key()
        public_key = RSA.import_key(recipient_public_key)

        # randomly-generate session key for encryption
        session_key = get_random_bytes(16)

        # private key of the _sender_ to sign this message with
        # signing with the sender's private key means that
        # the reciever can verify the signature with the signer's public key
        signing_key = PrivateKey.objects.get(pk=request.data['signing_key']).content
        private_key = RSA.import_key(signing_key)

        # hash of plaintext for signature
        hash_ = SHA256.new(data)
        signature = pkcs1_15.new(private_key).sign(hash_)

        ciper_rrsa = PKCS1_OAEP.new(public_key)
        enc_session_key = ciper_rrsa.encrypt(session_key)

        cipher_aes = AES.new(session_key, AES.MODE_EAX)
        ciphertext, tag = cipher_aes.encrypt_and_digest(data)

        # 'w+b' mode by default
        file_out = TemporaryFile()

        # [print('{} : {}'.format(x, len(x))) for x in (enc_session_key, cipher_aes.nonce, tag, signature, ciphertext)]

        if signed:
            [ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, signature, ciphertext) ]
        else:
            [ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ]

        file_out.seek(0)

        return FileResponse(file_out, as_attachment=True)
예제 #28
0
def check_prc_sig(in_path):
    signature = bytearray()

    h = SHA1.new()

    with open(in_path, 'r') as f:
        lines = f.readlines()

        for line in lines:
            if line.startswith('##!sig '):
                signature.extend(bytes.fromhex(line[7:]))
            else:
                h.update(line.encode('utf-8'))

    try:
        pkey = RSA.import_key(prc_key)
        pkcs1_15.new(pkey).verify(h, signature)
    except (ValueError, TypeError):
        return False

    return True
예제 #29
0
 def verify_signature(self, sender, message, signature):
     key = RSA.import_key(base64.b64decode(sender))
     cipher = pkcs1_15.new(key)
     h = SHA256.new()
     h.update(f"{message}".encode("utf8"))
     try:
         cipher.verify(h, base64.b64decode(signature))
         print("verified")
         return True
     except (ValueError, TypeError) as err:
         print(err)
         return False
예제 #30
0
def my_verify(data, signature, pubKey):
    key = RSA.importKey(pubKey)
    # print(pubKey)
    h = SHA256.new(data)
    verifier = pkcs1_15.new(key)
    print('cc')
    try:
        verifier.verify(h, base64.standard_b64decode(signature))
        return True
    except Exception as e:
        print(e)
    return False
예제 #31
0
 def verify_signature(self, data, b64signaturevalue, rsapublickey):
     verifyobject = pkcs1_15.new(
         rsapublickey)  # hozz létre egy verify objektumot
     hashobject = self.create_hashobject(
         data
     )  # az adatot töltsd be egy hash objektumba a create_hashobject(data) használatával
     signaturevalue = b64decode(b64signaturevalue.encode(
     ))  # dekódold base64 kódolással az aláírás értéket
     signatureerror = verifyobject.verify(
         hashobject, signaturevalue)  # ellenőrizd az aláírást
     validsignature = not signatureerror  # értéke: True, ha az aláírás érvényes
     return validsignature
예제 #32
0
파일: crypto.py 프로젝트: Leejunhee17/CS443
def sign(sk, msg):
    '''
    sign string msg with corresponding secret key (RsaKey object) in pycryptodome library
    return hex value of signature with RSA pkcs1 v1.5
    '''
    msgToUTF = msg.encode("UTF-8")
#     print(msgToUTF)
    msgHash = SHA512.new(msgToUTF)
#     print(msgHash)
    sig = pkcs1_15.new(sk).sign(msgHash).hex()
#     print(sig)
    return sig
예제 #33
0
 def test_verify(self, tv):
     self._id = "Wycheproof RSA PKCS$#1 Test #" + str(tv.id)
     
     hashed_msg = tv.hash_module.new(tv.msg)
     signer = pkcs1_15.new(tv.key)
     try:
         signature = signer.verify(hashed_msg, tv.sig)
     except ValueError as e:
         if tv.warning:
             return
         assert not tv.valid
     else:
         assert tv.valid
         self.warn(tv)
예제 #34
0
파일: crypto.py 프로젝트: STRML/privacyidea
    def sign(self, s):
        """
        Create a signature of the string s

        :return: The signature of the string
        :rtype: long
        """
        RSAkey = RSA.importKey(self.private)
        if SIGN_WITH_RSA:
            hashvalue = HashFunc.new(s).digest()
            signature = RSAkey.sign(hashvalue, 1)
        else:
            hashvalue = HashFunc.new(s)
            signature = pkcs1_15.new(RSAkey).sign(hashvalue)
        s_signature = str(signature[0])
        return s_signature
예제 #35
0
    def runTest(self):

        key = RSA.generate(1024)
        signer = pkcs1_15.new(key)
        hash_names = ("MD2", "MD4", "MD5", "RIPEMD160", "SHA1",
                      "SHA224", "SHA256", "SHA384", "SHA512",
                      "SHA3_224", "SHA3_256", "SHA3_384", "SHA3_512")

        for name in hash_names:
            hashed = load_hash_by_name(name).new(b("Test"))
            signer.sign(hashed)

        from Crypto.Hash import BLAKE2b, BLAKE2s
        for hash_size in (20, 32, 48, 64):
            hashed_b = BLAKE2b.new(digest_bytes=hash_size, data=b("Test"))
            signer.sign(hashed_b)
        for hash_size in (16, 20, 28, 32):
            hashed_s = BLAKE2s.new(digest_bytes=hash_size, data=b("Test"))
            signer.sign(hashed_s)
예제 #36
0
    def sign(self, s):
        """
        Create a signature of the string s

        :param s: String to sign
        :type s: str
        :return: The signature of the string
        :rtype: long
        """
        if isinstance(s, text_type):
            s = s.encode('utf8')
        RSAkey = RSA.importKey(self.private)
        if SIGN_WITH_RSA:
            hashvalue = HashFunc.new(s).digest()
            signature = RSAkey.sign(hashvalue, 1)
        else:
            hashvalue = HashFunc.new(s)
            signature = pkcs1_15.new(RSAkey).sign(hashvalue)
        s_signature = str(signature[0])
        return s_signature
예제 #37
0
 def test_can_sign(self):
     test_public_key = RSA.generate(1024).publickey()
     verifier = pkcs1_15.new(test_public_key)
     self.assertEqual(verifier.can_sign(), False)
예제 #38
0
 def verify_negative(self, hashmod, message, public_key, signature):
     hashed = hashmod.new(message)
     verifier = pkcs1_15.new(public_key)
     self.assertRaises(ValueError, verifier.verify, hashed, signature)
예제 #39
0
 def verify_positive(self, hashmod, message, public_key, signature):
     hashed = hashmod.new(message)
     pkcs1_15.new(public_key).verify(hashed, signature)
예제 #40
0
 def runTest(self):
     verifier = pkcs1_15.new(RSA.importKey(self.rsakey))
     hashed = SHA1.new(self.msg)
     verifier.verify(hashed, self.signature)
예제 #41
0
 def test_can_sign(self):
     test_private_key = RSA.generate(1024)
     signer = pkcs1_15.new(test_private_key)
     self.assertEqual(signer.can_sign(), True)
예제 #42
0
def new(rsa_key):
    pkcs1 = pkcs1_15.new(rsa_key)
    pkcs1._verify = pkcs1.verify
    pkcs1.verify = types.MethodType(_pycrypto_verify, pkcs1)
    return pkcs1
예제 #43
0
                                 { 'shaalg' : lambda x: x,
                                   'd' : lambda x: int(x),
                                   'result' : lambda x: x })


for count, tv in enumerate(test_vectors_verify):
    if isinstance(tv, basestring):
        continue
    if hasattr(tv, "n"):
        modulus = tv.n
        continue

    hash_module = load_hash_by_name(tv.shaalg.upper())
    hash_obj = hash_module.new(tv.msg)
    public_key = RSA.construct([bytes_to_long(x) for x in modulus, tv.e])
    verifier = pkcs1_15.new(public_key)

    def positive_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s):
        verifier.verify(hash_obj, signature)

    def negative_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s):
        self.assertRaises(ValueError, verifier.verify, hash_obj, signature)

    if tv.result == 'f':
        setattr(FIPS_PKCS1_Verify_Tests, "test_negative_%d" % count, negative_test)
    else:
        setattr(FIPS_PKCS1_Verify_Tests, "test_positive_%d" % count, positive_test)


class FIPS_PKCS1_Sign_Tests(unittest.TestCase):
예제 #44
0
 def _test_sign(self, hashmod, message, private_key, signature):
     hashed = hashmod.new(message)
     signature2 = pkcs1_15.new(private_key).sign(hashed)
     self.assertEqual(signature, signature2)
예제 #45
0
 def Sign(self, data):
     h = SHA256.new(data)
     return pkcs1_15.new(self.rsa_key).sign(h)