def pkcs11_to_crypto_key(self, pkcs11_public_key: pkcs11.KeyType) -> PublicKey: """ Convert a `pkcs11` public key to a `cryptography` public key. :param pkcs11.KeyType pkcs11_public_key: A `pkcs11` format public key. :return: A `cryptography` format public key. :rtype: :class:`PublicKey` """ if self.pkcs11_key_type == pkcs11.KeyType.RSA: der_public_key = encode_rsa_public_key(pkcs11_public_key) elif self.pkcs11_key_type == pkcs11.KeyType.DSA: y = int.from_bytes(pkcs11_public_key[pkcs11.Attribute.VALUE], byteorder="big") g = int.from_bytes(pkcs11_public_key[pkcs11.Attribute.BASE], byteorder="big") p = int.from_bytes(pkcs11_public_key[pkcs11.Attribute.PRIME], byteorder="big") q = int.from_bytes(pkcs11_public_key[pkcs11.Attribute.SUBPRIME], byteorder="big") der_public_key = DSA.construct( (y, g, p, q)).export_key(format="DER") elif self.pkcs11_key_type == pkcs11.KeyType.EC: der_public_key = encode_ec_public_key(pkcs11_public_key) else: raise TypeError(f"Key type for {pkcs11_public_key} not supported") return load_der_public_key(der_public_key)
def test_self_sign_certificate(self): # Warning: proof of concept code only! pub, priv = self.session.generate_keypair(KeyType.RSA, 1024) tbs = TbsCertificate({ 'version': 'v1', 'serial_number': 1, 'issuer': Name.build({ 'common_name': 'Test Certificate', }), 'subject': Name.build({ 'common_name': 'Test Certificate', }), 'signature': { 'algorithm': 'sha1_rsa', 'parameters': None, }, 'validity': { 'not_before': Time({ 'utc_time': datetime.datetime(2017, 1, 1, 0, 0), }), 'not_after': Time({ 'utc_time': datetime.datetime(2038, 12, 31, 23, 59), }), }, 'subject_public_key_info': { 'algorithm': { 'algorithm': 'rsa', 'parameters': None, }, 'public_key': RSAPublicKey.load(encode_rsa_public_key(pub)), } }) # Sign the TBS Certificate value = priv.sign(tbs.dump(), mechanism=Mechanism.SHA1_RSA_PKCS) cert = Certificate({ 'tbs_certificate': tbs, 'signature_algorithm': { 'algorithm': 'sha1_rsa', 'parameters': None, }, 'signature_value': value, }) # Pipe our certificate to OpenSSL to verify it with subprocess.Popen((OPENSSL, 'verify'), stdin=subprocess.PIPE, stdout=subprocess.DEVNULL) as proc: proc.stdin.write(pem.armor('CERTIFICATE', cert.dump())) proc.stdin.close() self.assertEqual(proc.wait(), 0)
def main(): token = get_tokens()[0] session = token.open() print(token.label, file=sys.stderr) pubkey = get_auth_pubkey(session) der = encode_rsa_public_key(pubkey) rsa = RSA.importKey(der) print(pubkey.label, file=sys.stderr) print(rsa.export_key('OpenSSH').decode()) session.close()
def test_terrible_hybrid_file_encryption_app(self): # Proof of concept code only! import io from oscrypto.asymmetric import load_public_key, rsa_pkcs1v15_encrypt from oscrypto.symmetric import ( aes_cbc_pkcs7_encrypt, aes_cbc_pkcs7_decrypt, ) # A key we generated earlier self.session.generate_keypair(KeyType.RSA, 1024) pub = self.session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PUBLIC_KEY) pub = load_public_key(encode_rsa_public_key(pub)) key = self.session.generate_random(256) iv = self.session.generate_random(128) source = b'This is my amazing file' with io.BytesIO() as dest: # Write a 128-byte header containing our key and our IV # strictly speaking we don't need to keep the IV secure but # we may as well. # # FIXME: Because this is RSA 1.5, we should fill the rest of the # frame with nonsense self.assertEqual(dest.write(rsa_pkcs1v15_encrypt(pub, key + iv)), 128) _, ciphertext = aes_cbc_pkcs7_encrypt(key, source, iv) dest.write(ciphertext) # Time passes dest.seek(0) # Look up our private key priv = self.session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PRIVATE_KEY) # Read the header header = dest.read(priv.key_length // 8) header = priv.decrypt(header, mechanism=Mechanism.RSA_PKCS) # The first 32 bytes is our key key, header = header[:32], header[32:] # The next 16 bytes is the IV iv = header[:16] # We can ignore the rest plaintext = aes_cbc_pkcs7_decrypt(key, dest.read(), iv) self.assertEqual(source, plaintext)
def test_sign_csr(self): # Warning: proof of concept code only! pub, priv = self.session.generate_keypair(KeyType.RSA, 1024) info = CertificationRequestInfo({ 'version': 0, 'subject': Name.build({ 'common_name': 'Test Certificate', }), 'subject_pk_info': { 'algorithm': { 'algorithm': 'rsa', 'parameters': None, }, 'public_key': RSAPublicKey.load(encode_rsa_public_key(pub)), }, }) # Sign the CSR Info value = priv.sign(info.dump(), mechanism=Mechanism.SHA1_RSA_PKCS) csr = CertificationRequest({ 'certification_request_info': info, 'signature_algorithm': { 'algorithm': 'sha1_rsa', 'parameters': None, }, 'signature': value, }) # Pipe our CSR to OpenSSL to verify it with subprocess.Popen((OPENSSL, 'req', '-inform', 'der', '-noout', '-verify'), stdin=subprocess.PIPE, stdout=subprocess.DEVNULL) as proc: proc.stdin.write(csr.dump()) proc.stdin.close() self.assertEqual(proc.wait(), 0)
def test_rsa(self): # A key we generated earlier self.session.generate_keypair(KeyType.RSA, 1024) pub = self.session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PUBLIC_KEY) pub = encode_rsa_public_key(pub) from oscrypto.asymmetric import load_public_key, rsa_pkcs1v15_encrypt pub = load_public_key(pub) crypttext = rsa_pkcs1v15_encrypt(pub, b'Data to encrypt') priv = self.session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PRIVATE_KEY) plaintext = priv.decrypt(crypttext, mechanism=Mechanism.RSA_PKCS) self.assertEqual(plaintext, b'Data to encrypt')
def getPublicKeyCC(self): with self.token.open(user_pin = str(self.user_pin)) as session: pub = session.get_key(pkcs11.constants.ObjectClass.PUBLIC_KEY, pkcs11.KeyType.RSA, "CITIZEN AUTHENTICATION CERTIFICATE") pem = encode_rsa_public_key(pub) return pem
def import_public_key(key): return RSA.importKey(encode_rsa_public_key(key))
from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 tolab = ('Test') upin = ('654321') lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label= tolab) # Open a session on our token session = token.open(rw=True, user_pin= upin) #print(session) # Extract public key key = session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PUBLIC_KEY) key = RSA.importKey(encode_rsa_public_key(key)) # Encryption on the local machine cipher = PKCS1_v1_5.new(key) class ThreadedServer(object): def __init__(self, host, port): self.host = ('localhost') self.port = (1500) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.host, self.port)) print ('Starting up on', self.host, self.port) def listen(self): self.sock.listen(10)
with token.open(user_pin='1234') as session: pub, priv = session.generate_keypair(KeyType.RSA, 2048) info = CertificationRequestInfo({ 'version': 0, 'subject': Name.build({ 'common_name': cn, }), 'subject_pk_info': { 'algorithm': { 'algorithm': 'rsa', 'parameters': None, }, 'public_key': RSAPublicKey.load(encode_rsa_public_key(pub)), }, }) # Sign the CSR Info value = priv.sign(info.dump(), mechanism=Mechanism.SHA1_RSA_PKCS) csr = CertificationRequest({ 'certification_request_info': info, 'signature_algorithm': { 'algorithm': 'sha1_rsa', 'parameters': None, }, 'signature': value, }) certpem = pem.armor('CERTIFICATE REQUEST', csr.dump()).decode()