<commit_before>"""
Test the admin-create-key tool
"""

import os
import sys
import unittest
import subprocess
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
import json
import tempfile

# Allow unittests to be run from within the project base.
if os.path.exists("src"):
    sys.path.append("src")
if os.path.exists("../src"):
    sys.path.append("../src")

from scitokens.utils import long_from_bytes

class TestKeyCreate(unittest.TestCase):

    to_delete = []

    def setUp(self):
        os.environ['PYTHONPATH'] = ":".join(sys.path)

    @staticmethod
    def _test_private(key):
        return serialization.load_pem_private_key(
            key,
            password=<PASSWORD>,
            backend=default_backend()
        )

    @staticmethod
    def _test_public(key):
        return serialization.load_pem_public_key(
            key,
            backend=default_backend()
        )

    @staticmethod
    def _test_public_jwk(key):
        """
        Attempt to read in the key into a key object
        """
        keys = json.loads(key)
        public_key_numbers = rsa.RSAPublicNumbers(
            long_from_bytes(keys['keys'][0]['e']),
            long_from_bytes(keys['keys'][0]['n'])
        )
        return public_key_numbers.public_key(default_backend())

    @staticmethod
    def _test_private_jwk(key):
        """
        Attempt to read in the key into a private key object
        """
        keys = json.loads(key)
        public_key_numbers = rsa.RSAPublicNumbers(
            long_from_bytes(keys['keys'][0]['e']),
            long_from_bytes(keys['keys'][0]['n'])
        )
        private_key_numbers = rsa.RSAPrivateNumbers(
            long_from_bytes(keys['keys'][0]['p']),
            long_from_bytes(keys['keys'][0]['q']),
            long_from_bytes(keys['keys'][0]['d']),
            long_from_bytes(keys['keys'][0]['dp']),
            long_from_bytes(keys['keys'][0]['dq']),
            long_from_bytes(keys['keys'][0]['qi']),
            public_key_numbers
            
        )
        return private_key_numbers.private_key(default_backend())
        
        
    def _run_command(self, command):
        command_run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        (stdout, stderr) = command_run.communicate()
        if command_run.returncode != 0:
            print(stdout)
            print(stderr)
            self.assertEqual(command_run.returncode, 0)
        return stdout


    def test_create(self):
        """
        Test the key creation
        """
        command = "python tools/scitokens-admin-create-key --create-keys --pem-private"
        output = self._run_command(command)
        private_key = self._test_private(output)
        self.assertIsNotNone(private_key)

        # Test public key
        command = "python tools/scitokens-admin-create-key --create-keys --pem-public"<commit_msg>Fixing some codacy issues<commit_after>"""
Test the admin-create-key tool
"""

import os
import sys
import unittest
import subprocess
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
import json
import tempfile

# Allow unittests to be run from within the project base.
if os.path.exists("src"):
    sys.path.append("src")
if os.path.exists("../src"):
    sys.path.append("../src")

from scitokens.utils import long_from_bytes

class TestKeyCreate(unittest.TestCase):
    """
    Test the admin-create-key tool
    """

    to_delete = []

    def setUp(self):
        os.environ['PYTHONPATH'] = ":".join(sys.path)

    @staticmethod
    def _test_private(key):
        return serialization.load_pem_private_key(
            key,
            password=<PASSWORD>,
            backend=default_backend()
        )

    @staticmethod
    def _test_public(key):
        return serialization.load_pem_public_key(
            key,
            backend=default_backend()
        )

    @staticmethod
    def _test_public_jwk(key):
        """
        Attempt to read in the key into a key object
        """
        keys = json.loads(key)
        public_key_numbers = rsa.RSAPublicNumbers(
            long_from_bytes(keys['keys'][0]['e']),
            long_from_bytes(keys['keys'][0]['n'])
        )
        return public_key_numbers.public_key(default_backend())

    @staticmethod
    def _test_private_jwk(key):
        """
        Attempt to read in the key into a private key object
        """
        keys = json.loads(key)
        public_key_numbers = rsa.RSAPublicNumbers(
            long_from_bytes(keys['keys'][0]['e']),
            long_from_bytes(keys['keys'][0]['n'])
        )
        private_key_numbers = rsa.RSAPrivateNumbers(
            long_from_bytes(keys['keys'][0]['p']),
            long_from_bytes(keys['keys'][0]['q']),
            long_from_bytes(keys['keys'][0]['d']),
            long_from_bytes(keys['keys'][0]['dp']),
            long_from_bytes(keys['keys'][0]['dq']),
            long_from_bytes(keys['keys'][0]['qi']),
            public_key_numbers
        )
        return private_key_numbers.private_key(default_backend())
        
        
    def _run_command(self, command):
        command_run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        (stdout, stderr) = command_run.communicate()
        if command_run.returncode != 0:
            print(stdout)
            print(stderr)
            self.assertEqual(command_run.returncode, 0)
        return stdout


    def test_create(self):
        """
        Test the key creation
        """
        command = "python tools/scitokens-admin-create-key --create-keys --pem-private"
        output = self._run_command(command)
        private_key = self._test_private(output)
        self.assertIsNotNone(private_key)

        # Test public key
        command = "python tools/scitokens-admin-create-key --create-keys --pem-public"
{'fraction_non_alphanumeric': 0.12005233889434086, 'fraction_numerical': 0.003925417075564278, 'mean_word_length': 2.5204375359815776, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4416201', 'n_tokens_mistral': 1880, 'n_tokens_neox': 1851, 'n_words': 340}