import time
import subprocess
import base64
import json
from django.db import models
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
# pip install pycryptodome
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256

from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token


def verify_sign(pub_key, signature, data):
    '''
    Verifies with a public key from whom the data came that it was indeed
    signed by their private key

    Params
        public_key: string of rsa public key
        signature:  base64 encoded signature to be verified
        data:       plain text data from which signature is derived from
    
    Return
        Boolean:    True if the signature is valid; False otherwise.
    '''
    rsakey = RSA.importKey(pub_key)
    signer = pkcs1_15.new(rsakey)
    digest = SHA256.new()
    # Assumes the data is base64 encoded to begin with
    digest.update(data.encode('utf-8'))

    try:
        signer.verify(digest, base64.b64decode(signature))
        return True
    except (ValueError, TypeError):
        return False
import time
import subprocess
import base64
import json
from django.db import models
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
# pip install pycryptodome
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256

from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token


def verify_sign(pub_key, signature, data):
    '''
    Verifies with a public key from whom the data came that it was indeed
    signed by their private key

    Params
        public_key: string of rsa public key
        signature:  base64 encoded signature to be verified
        data:       plain text data from which signature is derived from
    
    Return
        Boolean:    True if the signature is valid; False otherwise.
    '''
    rsakey = RSA.importKey(pub_key)
    signer = pkcs1_15.new(rsakey)
    digest = SHA256.new()
    # Assumes the data is base64 encoded to begin with
    digest.update(data.encode('utf-8'))

    try:
        signer.verify(digest, base64.b64decode(signature))
        return True
    except (ValueError, TypeError):
        return False
# pip install pycryptodome Verifies with a public key from whom the data came that it was indeed     signed by their private key      Params         public_key: string of rsa public key         signature:  base64 encoded signature to be verified         data:       plain text data from which signature is derived from          Return         Boolean:    True if the signature is valid; False otherwise. # Assumes the data is base64 encoded to begin with