Пример #1
0
    def enable_encryptor_by_pem_file(self, pem_pub_file, curve_name = 'secp256k1', strength = 128):
        if not self.can_encryptor:
            raise Exception("can not enable encryptor after a quest send")
        if curve_name not in ['secp256k1', 'secp256r1', 'secp192r1', 'secp224r1']:
            curve_name = 'secp256k1'
        self.encryptor_curve = ec.SECP256K1()
        if curve_name == 'secp256k1':
            self.encryptor_curve = ec.SECP256K1()
        elif curve_name == 'secp256r1':
            self.encryptor_curve = ec.SECP256R1()
        elif curve_name == 'secp192r1':
            self.encryptor_curve = ec.SECP192R1()
        else:
            self.encryptor_curve = ec.SECP224R1()
        if strength not in [128, 256]:
            strength = 128
        self.encryptor_strength = strength

        pri_key = ec.generate_private_key(self.encryptor_curve, default_backend())
        pub_key = pri_key.public_key()
        peer_pub_key = load_pem_public_key(open(pem_pub_file, 'rb').read(), backend=default_backend()) 
        
        secret = pri_key.exchange(ec.ECDH(), peer_pub_key)
        self.encrypted_iv = hashlib.md5(secret).digest()
        if strength == 128:
            self.encrypted_key = secret[0:16]
        else:
            if len(secret) == 32:
                self.encrypted_key = secret
            else:
                self.encrypted_key = hashlib.sha256(secret).digest()
        self.encrypted_send_pub_key = utils.int_to_bytes(pub_key.public_numbers().x, 32) + utils.int_to_bytes(pub_key.public_numbers().y, 32)
Пример #2
0
    def sanity_check_valid_session(self):
        print('Establishing a valid session, and running sanity checks')
        tube = pwnlib.tubes.remote.remote('127.0.0.1', self.port)
        tube.recvuntil('== proof-of-work: ')
        if tube.recvline().startswith(b'enabled'):
            handle_pow(tube)

        server_hello = read_message(tube, challenge_pb2.ServerHello)
        server_key = proto2key(server_hello.key)

        # Establish a normal session with a valid SECP224 point.
        private_key = ec.generate_private_key(ec.SECP224R1())
        client_hello = challenge_pb2.ClientHello()
        client_hello.key.CopyFrom(key2proto(private_key.public_key()))

        write_message(tube, client_hello)

        shared_key = private_key.exchange(ec.ECDH(), server_key)

        channel = AuthCipher(shared_key, CHANNEL_CIPHER_KDF_INFO,
                             CHANNEL_MAC_KDF_INFO)
        msg = challenge_pb2.SessionMessage()
        msg.encrypted_data.CopyFrom(channel.encrypt(IV, b'hello'))
        write_message(tube, msg)

        # Verify data is echoed back.
        reply = read_message(tube, challenge_pb2.SessionMessage)
        assert (len(reply.encrypted_data.data) > 0)

        # Verify server authenticates message.
        msg.encrypted_data.iv = b'\xff' + IV[1:]
        write_message(tube, msg)

        reply = read_message(tube, challenge_pb2.SessionMessage)
        assert (len(reply.encrypted_data.data) == 0)
Пример #3
0
def savecustcert(request):
    global size
    global value
    global algo
    global check
    global security
    try:
        algo = request.POST['algo']
    except MultiValueDictKeyError:
        algo = 'RSA'
    try:
        security = request.POST['security']
    except MultiValueDictKeyError:
        return HttpResponse('please select a security level from the list')
    check = 'NA'

    if (algo == 'ECC'):
        if (security == 'Level 1'):
            value = ec.SECP192R1()
        elif (security == 'Level 2'):
            value = ec.SECP224R1()
        else:
            value = ec.SECP256R1()
    elif (algo == 'RSA'):
        if (security == 'Level 1'):
            size = 1024
        elif (security == 'Level 2'):
            size = 2048
        else:
            size = 3072

    return HttpResponse('values set')
Пример #4
0
def run_session(port):
  tube = pwnlib.tubes.remote.remote('127.0.0.1', port)
  print(tube.recvuntil('== proof-of-work: '))
  if tube.recvline().startswith(b'enabled'):
      handle_pow()

  server_hello = read_message(tube, challenge_pb2.ServerHello)
  server_key = proto2key(server_hello.key)
  print(server_hello)

  private_key = ec.generate_private_key(ec.SECP224R1())
  client_hello = challenge_pb2.ClientHello()
  client_hello.key.CopyFrom(key2proto(private_key.public_key()))
  print(client_hello)

  write_message(tube, client_hello)

  shared_key = private_key.exchange(ec.ECDH(), server_key)
  print(shared_key)

  channel = AuthCipher(shared_key, CHANNEL_CIPHER_KDF_INFO, CHANNEL_MAC_KDF_INFO)
  msg = challenge_pb2.SessionMessage()
  msg.encrypted_data.CopyFrom(channel.encrypt(IV, b'hello'))
  write_message(tube, msg)
  print('msg:', msg)

  reply = read_message(tube, challenge_pb2.SessionMessage)
  print('reply:', reply)
Пример #5
0
class Curve(Enum):
    P224 = ec.SECP224R1()
    P256 = ec.SECP256R1()
    P384 = ec.SECP384R1()
    P521 = ec.SECP521R1()

    @staticmethod
    def from_label(label: int):
        label = bytes([label])
        if Curve.P224.value == label:
            return Curve.P224.name
        elif Curve.P256.value == label:
            return Curve.P256.name
        elif Curve.P384.value == label:
            return Curve.P384.name
        elif Curve.P521.value == label:
            return Curve.P521.name
        else:
            raise SDKException(ErrorCode.unknown_asymmetric_key_type)

    @staticmethod
    def from_str_curve(str_curve: str):
        if not isinstance(str_curve, str):
            raise SDKException(ErrorCode.require_str_params)
        if str_curve == 'P224':
            return Curve.P224
        elif str_curve == 'P256':
            return Curve.P256
        elif str_curve == 'P384':
            return Curve.P384
        elif str_curve == 'P521':
            return Curve.P521
        else:
            raise SDKException(ErrorCode.unknown_asymmetric_key_type)
Пример #6
0
def get_key_type_from_ec_curve(curve_name):
    """
    Give an EC curve name, return the matching key_type.

    :param: curve_name
    :return: key_type
    """

    _CURVE_TYPES = {
        ec.SECP192R1().name: "ECCPRIME192V1",
        ec.SECP256R1().name: "ECCPRIME256V1",
        ec.SECP224R1().name: "ECCSECP224R1",
        ec.SECP384R1().name: "ECCSECP384R1",
        ec.SECP521R1().name: "ECCSECP521R1",
        ec.SECP256K1().name: "ECCSECP256K1",
        ec.SECT163K1().name: "ECCSECT163K1",
        ec.SECT233K1().name: "ECCSECT233K1",
        ec.SECT283K1().name: "ECCSECT283K1",
        ec.SECT409K1().name: "ECCSECT409K1",
        ec.SECT571K1().name: "ECCSECT571K1",
        ec.SECT163R2().name: "ECCSECT163R2",
        ec.SECT233R1().name: "ECCSECT233R1",
        ec.SECT283R1().name: "ECCSECT283R1",
        ec.SECT409R1().name: "ECCSECT409R1",
        ec.SECT571R1().name: "ECCSECT571R2",
    }

    if curve_name in _CURVE_TYPES.keys():
        return _CURVE_TYPES[curve_name]
    else:
        return None
Пример #7
0
def proto2key(key):
  assert(isinstance(key, challenge_pb2.EcdhKey))
  assert(key.curve == challenge_pb2.EcdhKey.CurveID.SECP224R1)
  curve = ec.SECP224R1()
  x = int.from_bytes(key.public.x, 'big')
  y = int.from_bytes(key.public.y, 'big')
  public = ec.EllipticCurvePublicNumbers(x, y, curve)
  return ec.EllipticCurvePublicKey.from_encoded_point(curve, public.encode_point())
Пример #8
0
    def build_csr(self):
        if not self.private_key:
            if self.key_type == KeyTypes.RSA:
                self.private_key = rsa.generate_private_key(
                    public_exponent=65537,
                    key_size=self.key_length,
                    backend=default_backend())
            elif self.key_type == KeyTypes.ECDSA:
                if self.key_curve == "P521":
                    curve = ec.SECP521R1()
                elif self.key_curve == "P384":
                    curve = ec.SECP384R1()
                elif self.key_curve == "P256":
                    curve = ec.SECP256R1()
                elif self.key_curve == "P224":
                    curve = ec.SECP224R1()
                else:
                    curve = ec.SECP521R1()
                self.private_key = ec.generate_private_key(
                    curve, default_backend())
            else:
                raise ClientBadData
            self.public_key_from_private()

        csr_builder = x509.CertificateSigningRequestBuilder()
        subject = [
            x509.NameAttribute(
                NameOID.COMMON_NAME,
                self.common_name,
            )
        ]
        csr_builder = csr_builder.subject_name(x509.Name(subject))

        alt_names = []
        if self.ip_addresses:
            for ip in self.ip_addresses:
                alt_names.append(x509.IPAddress(ipaddress.IPv4Address(ip)))

        if self.san_dns:
            for ns in self.san_dns:
                alt_names.append(x509.DNSName(ns))

        if self.email_addresses:
            for mail in self.email_addresses:
                alt_names.append(x509.RFC822Name(mail))

        csr_builder = csr_builder.add_extension(
            x509.SubjectAlternativeName(alt_names),
            critical=False,
        )

        csr_builder = csr_builder.sign(self.private_key, hashes.SHA256(),
                                       default_backend())
        self.csr = csr_builder.public_bytes(
            serialization.Encoding.PEM).decode()
        return
Пример #9
0
def generate_private_key(key_type):
    """
    Generates a new private key based on key_type.

    Valid key types: RSA2048, RSA4096', 'ECCPRIME192V1', 'ECCPRIME256V1', 'ECCSECP192R1',
        'ECCSECP224R1', 'ECCSECP256R1', 'ECCSECP384R1', 'ECCSECP521R1', 'ECCSECP256K1',
        'ECCSECT163K1', 'ECCSECT233K1', 'ECCSECT283K1', 'ECCSECT409K1', 'ECCSECT571K1',
        'ECCSECT163R2', 'ECCSECT233R1', 'ECCSECT283R1', 'ECCSECT409R1', 'ECCSECT571R2'

    :param key_type:
    :return:
    """

    _CURVE_TYPES = {
        "ECCPRIME192V1": ec.SECP192R1(),
        "ECCPRIME256V1": ec.SECP256R1(),

        "ECCSECP192R1": ec.SECP192R1(),
        "ECCSECP224R1": ec.SECP224R1(),
        "ECCSECP256R1": ec.SECP256R1(),
        "ECCSECP384R1": ec.SECP384R1(),
        "ECCSECP521R1": ec.SECP521R1(),
        "ECCSECP256K1": ec.SECP256K1(),

        "ECCSECT163K1": ec.SECT163K1(),
        "ECCSECT233K1": ec.SECT233K1(),
        "ECCSECT283K1": ec.SECT283K1(),
        "ECCSECT409K1": ec.SECT409K1(),
        "ECCSECT571K1": ec.SECT571K1(),

        "ECCSECT163R2": ec.SECT163R2(),
        "ECCSECT233R1": ec.SECT233R1(),
        "ECCSECT283R1": ec.SECT283R1(),
        "ECCSECT409R1": ec.SECT409R1(),
        "ECCSECT571R2": ec.SECT571R1(),
    }

    if key_type not in CERTIFICATE_KEY_TYPES:
        raise Exception("Invalid key type: {key_type}. Supported key types: {choices}".format(
            key_type=key_type,
            choices=",".join(CERTIFICATE_KEY_TYPES)
        ))

    if 'RSA' in key_type:
        key_size = int(key_type[3:])
        return rsa.generate_private_key(
            public_exponent=65537,
            key_size=key_size,
            backend=default_backend()
        )
    elif 'ECC' in key_type:
        return ec.generate_private_key(
            curve=_CURVE_TYPES[key_type],
            backend=default_backend()
        )
Пример #10
0
 def test_for_curve(self):
     self.assertEqual(ALGORITHM.for_curve(ec.SECP224R1()), ALGORITHM.EC_P224)
     self.assertEqual(ALGORITHM.for_curve(ec.SECP256R1()), ALGORITHM.EC_P256)
     self.assertEqual(ALGORITHM.for_curve(ec.SECP384R1()), ALGORITHM.EC_P384)
     self.assertEqual(ALGORITHM.for_curve(ec.SECP521R1()), ALGORITHM.EC_P521)
     self.assertEqual(ALGORITHM.for_curve(ec.SECP256K1()), ALGORITHM.EC_K256)
     self.assertEqual(ALGORITHM.for_curve(BRAINPOOLP256R1()),
                      ALGORITHM.EC_BP256)
     self.assertEqual(ALGORITHM.for_curve(BRAINPOOLP384R1()),
                      ALGORITHM.EC_BP384)
     self.assertEqual(ALGORITHM.for_curve(BRAINPOOLP512R1()),
                      ALGORITHM.EC_BP512)
Пример #11
0
def _curve_from_curve_id(cid: int) -> EllipticCurve:
    if cid == TPM_ECC_NIST_P192:
        return crypto_ec.SECP192R1()
    if cid == TPM_ECC_NIST_P224:
        return crypto_ec.SECP224R1()
    if cid == TPM_ECC_NIST_P256:
        return crypto_ec.SECP256R1()
    if cid == TPM_ECC_NIST_P384:
        return crypto_ec.SECP384R1()
    if cid == TPM_ECC_NIST_P521:
        return crypto_ec.SECP521R1()

    raise ValueError(f"Invalid curve id {cid} requested")
Пример #12
0
    def to_curve(self):
        if self == TpmEccCurve.NONE:
            raise ValueError("No such curve")
        elif self == TpmEccCurve.NIST_P192:
            return ec.SECP192R1()
        elif self == TpmEccCurve.NIST_P224:
            return ec.SECP224R1()
        elif self == TpmEccCurve.NIST_P256:
            return ec.SECP256R1()
        elif self == TpmEccCurve.NIST_P384:
            return ec.SECP384R1()
        elif self == TpmEccCurve.NIST_P521:
            return ec.SECP521R1()

        raise ValueError("curve is not supported", self)
Пример #13
0
class Curve(Enum):
    P224 = ec.SECP224R1()
    P256 = ec.SECP256R1()
    P384 = ec.SECP384R1()
    P521 = ec.SECP521R1()

    @staticmethod
    def from_label(label: int):
        label = bytes([label])
        if Curve.P224.value == label:
            return Curve.P224.name
        elif Curve.P256.value == label:
            return Curve.P256.name
        elif Curve.P384.value == label:
            return Curve.P384.name
        elif Curve.P521.value == label:
            return Curve.P521.name
Пример #14
0
 def generateSignature(self, pri_key, msg):
     if self.__scheme == SignatureScheme.SHA224withECDSA:
         private_key = ec.derive_private_key(int(pri_key, 16),
                                             ec.SECP224R1(),
                                             default_backend())
         signature = private_key.sign(msg, ec.ECDSA(hashes.SHA224()))
     elif self.__scheme == SignatureScheme.SHA256withECDSA:
         private_key = ec.derive_private_key(int(pri_key, 16),
                                             ec.SECP256R1(),
                                             default_backend())
         signature = private_key.sign(msg, ec.ECDSA(hashes.SHA256()))
     elif self.__scheme == SignatureScheme.SHA384withECDSA:
         private_key = ec.derive_private_key(int(pri_key, 16),
                                             ec.SECP384R1(),
                                             default_backend())
         signature = private_key.sign(msg, ec.ECDSA(hashes.SHA384()))
     return signature
Пример #15
0
class Curve(Enum):
    P224 = ec.SECP224R1()
    P256 = ec.SECP256R1()
    P384 = ec.SECP384R1()
    P521 = ec.SECP521R1()

    @staticmethod
    def from_label(label: int) -> str:
        if label == 1:
            return Curve.P224.name
        elif label == 2:
            return Curve.P256.name
        elif label == 3:
            return Curve.P384.name
        elif label == 4:
            return Curve.P521.name
        else:
            raise SDKException(ErrorCode.unknown_curve_label)
Пример #16
0
 def generateSignature(self, pri_key, msg: bytes):
     if self.__scheme == SignatureScheme.SHA224withECDSA:
         private_key = ec.derive_private_key(int(pri_key, 16),
                                             ec.SECP224R1(),
                                             default_backend())
         signature = private_key.sign(msg, ec.ECDSA(hashes.SHA224()))
     elif self.__scheme == SignatureScheme.SHA256withECDSA:
         private_key = ec.derive_private_key(int(pri_key, 16),
                                             ec.SECP256R1(),
                                             default_backend())
         signature = private_key.sign(msg, ec.ECDSA(hashes.SHA256()))
     elif self.__scheme == SignatureScheme.SHA384withECDSA:
         private_key = ec.derive_private_key(int(pri_key, 16),
                                             ec.SECP384R1(),
                                             default_backend())
         signature = private_key.sign(msg, ec.ECDSA(hashes.SHA384()))
     else:
         raise RuntimeError
     sign = SignatureHandler.dsa_der_to_plain(signature)
     return sign
Пример #17
0
 def generate_signature(self, pri_key: str, msg: bytes) -> str:
     if self.__scheme == SignatureScheme.SHA224withECDSA:
         private_key = ec.derive_private_key(int(pri_key, 16),
                                             ec.SECP224R1(),
                                             default_backend())
         signature = private_key.sign(msg, ec.ECDSA(hashes.SHA224()))
     elif self.__scheme == SignatureScheme.SHA256withECDSA:
         private_key = ec.derive_private_key(int(pri_key, 16),
                                             ec.SECP256R1(),
                                             default_backend())
         signature = private_key.sign(msg, ec.ECDSA(hashes.SHA256()))
     elif self.__scheme == SignatureScheme.SHA384withECDSA:
         private_key = ec.derive_private_key(int(pri_key, 16),
                                             ec.SECP384R1(),
                                             default_backend())
         signature = private_key.sign(msg, ec.ECDSA(hashes.SHA384()))
     else:
         raise SDKException(
             ErrorCode.other_error('Invalid signature scheme.'))
     sign = SignatureHandler.dsa_der_to_plain(signature)
     return sign
Пример #18
0
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID
import datetime
import uuid
from time import time, process_time

print('check')
value = ec.SECP224R1()
time1 = process_time()
one_day = datetime.timedelta(1, 0, 0)
pr_key = rsa.generate_private_key(public_exponent=65537,
                                  key_size=2048,
                                  backend=default_backend())
time2 = process_time()

tt_keygen = time2 - time1

pub_key = pr_key.public_key()
builder = x509.CertificateBuilder()
builder = builder.subject_name(
    x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u'CA certificate'),
    ]))
builder = builder.issuer_name(
    x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u'Self signed'),
    ]))
Пример #19
0
else:
    from Cryptodome.PublicKey import DSA
    from Cryptodome.PublicKey import RSA

RSA_WEAK = 1024
RSA_OK = 2048
RSA_STRONG = 3076

DSA_WEAK = 1024
DSA_OK = 2048
DSA_STRONG = 3076

BIG = 10000

EC_WEAK = ec.SECT163K1()  # has key size of 163
EC_OK = ec.SECP224R1()
EC_STRONG = ec.SECP384R1()
EC_BIG = ec.SECT571R1()

dsa_gen_key = dsa.generate_private_key
ec_gen_key = ec.generate_private_key
rsa_gen_key = rsa.generate_private_key

# Strong and OK keys.

dsa_gen_key(key_size=DSA_OK)
dsa_gen_key(key_size=DSA_STRONG)
dsa_gen_key(key_size=BIG)
ec_gen_key(curve=EC_OK)
ec_gen_key(curve=EC_STRONG)
ec_gen_key(curve=EC_BIG)
Пример #20
0
            csr = csr_add_extension.sign(private_key, hashes.SHA256(),
                                         default_backend())
        else:
            csr = csr_add_extension.sign(private_key, hashes.SHA1(),
                                         default_backend())
        return {
            'error': True,
            'csr': csr.public_bytes(serialization.Encoding.PEM),
            'priv_key': key
        }
    elif mysf == 'ECDSA':
        if myqd == 'P192':
            private_key = ec.generate_private_key(curve=ec.SECP192R1(),
                                                  backend=default_backend())
        elif myqd == 'P224':
            private_key = ec.generate_private_key(curve=ec.SECP224R1(),
                                                  backend=default_backend())
        elif myqd == 'P256':
            private_key = ec.generate_private_key(curve=ec.SECP256R1(),
                                                  backend=default_backend())
        elif myqd == 'P384':
            private_key = ec.generate_private_key(curve=ec.SECP384R1(),
                                                  backend=default_backend())
        elif myqd == 'P521':
            private_key = ec.generate_private_key(curve=ec.SECP521R1(),
                                                  backend=default_backend())
        else:
            private_key = ec.generate_private_key(curve=ec.SECP256R1(),
                                                  backend=default_backend())

        if key_pass:
Пример #21
0
from time import process_time_ns

from cryptography.hazmat.primitives.asymmetric import ec

# Recommended curves from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
CURVE_MAP = {
    'P-192': ec.SECP192R1(),
    'P-224': ec.SECP224R1(),
    'P-256': ec.SECP256R1(),
    'P-384': ec.SECP384R1()
}


def current_milli_time():
    return process_time_ns()
Пример #22
0
 def generate_public_key(self, source):
     if source not in self.key_cache or "public_key" not in self.key_cache[source]:
         self.key_cache[source] = {}
         new_private_key = ec.generate_private_key(ec.SECP224R1(), default_backend())
         self.key_cache[source]["public_key"] = new_private_key.public_key()
         self.key_cache[source]["private_key"] = new_private_key
Пример #23
0
 def test_secp224r1_derive_ecdh(self):
     self.secp_derive_ecdh(ec.SECP224R1())
Пример #24
0
    def test_secp224r1_ecdsa_sign_truncated(self):
        self.require_version((2, 1, 0), 'Automatic digest truncation')

        self.secp_ecdsa_sign(ec.SECP224R1(), hashes.SHA256())
        self.secp_ecdsa_sign(ec.SECP224R1(), hashes.SHA384())
        self.secp_ecdsa_sign(ec.SECP224R1(), hashes.SHA512())
Пример #25
0
 def test_secp224r1_ecdsa_sign(self):
     self.secp_ecdsa_sign(ec.SECP224R1(), hashes.SHA1())
     self.secp_ecdsa_sign(ec.SECP224R1(), hashes.SHA256(), length=28)
     self.secp_ecdsa_sign(ec.SECP224R1(), hashes.SHA384(), length=28)
     self.secp_ecdsa_sign(ec.SECP224R1(), hashes.SHA512(), length=28)
Пример #26
0
def pub_priv_creater(mysf, myqd, key_pass):
    if mysf == 'RSA':
        private_key = rsa.generate_private_key(public_exponent=65537,
                                               key_size=int(myqd),
                                               backend=default_backend())
        if key_pass:
            key = private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.BestAvailableEncryption(
                    key_pass),
            )
        else:
            key = private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.NoEncryption(),
            )
        public_key = private_key.public_key().public_bytes(
            serialization.Encoding.PEM,
            serialization.PublicFormat.SubjectPublicKeyInfo)
        return {'error': True, 'pub_key': public_key, 'priv_key': key}
    elif mysf == 'DSA':
        private_key = dsa.generate_private_key(key_size=int(myqd),
                                               backend=default_backend())
        if key_pass:
            key = private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.BestAvailableEncryption(
                    key_pass),
            )
        else:
            key = private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.NoEncryption(),
            )
        public_key = private_key.public_key().public_bytes(
            serialization.Encoding.PEM,
            serialization.PublicFormat.SubjectPublicKeyInfo)
        return {'error': True, 'pub_key': public_key, 'priv_key': key}
    elif mysf == 'ECDSA':
        if myqd == 'P192':
            private_key = ec.generate_private_key(curve=ec.SECP192R1(),
                                                  backend=default_backend())
        elif myqd == 'P224':
            private_key = ec.generate_private_key(curve=ec.SECP224R1(),
                                                  backend=default_backend())
        elif myqd == 'P256':
            private_key = ec.generate_private_key(curve=ec.SECP256R1(),
                                                  backend=default_backend())
        elif myqd == 'P384':
            private_key = ec.generate_private_key(curve=ec.SECP384R1(),
                                                  backend=default_backend())
        elif myqd == 'P521':
            private_key = ec.generate_private_key(curve=ec.SECP521R1(),
                                                  backend=default_backend())
        else:
            private_key = ec.generate_private_key(curve=ec.SECP256R1(),
                                                  backend=default_backend())

        if key_pass:
            key = private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.BestAvailableEncryption(
                    key_pass),
            )
        else:
            key = private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.NoEncryption(),
            )
        public_key = private_key.public_key().public_bytes(
            serialization.Encoding.PEM,
            serialization.PublicFormat.SubjectPublicKeyInfo)
        return {'error': True, 'pub_key': public_key, 'priv_key': key}
    else:
        return {'error': False, 'pub_key': u'选择加密算法错误!'}
Пример #27
0
from __future__ import absolute_import, division, print_function

import binascii

import pytest

from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.backends.interfaces import EllipticCurveBackend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec

from ..hazmat.primitives.test_ec import _skip_exchange_algorithm_unsupported

_CURVES = {
    "secp224r1": ec.SECP224R1(),
    "secp256r1": ec.SECP256R1(),
    "secp384r1": ec.SECP384R1(),
    "secp521r1": ec.SECP521R1(),
    "secp256k1": ec.SECP256K1(),
    "brainpoolP224r1": None,
    "brainpoolP256r1": ec.BrainpoolP256R1(),
    "brainpoolP320r1": None,
    "brainpoolP384r1": ec.BrainpoolP384R1(),
    "brainpoolP512r1": ec.BrainpoolP512R1(),
    "brainpoolP224t1": None,
    "brainpoolP256t1": None,
    "brainpoolP320t1": None,
    "brainpoolP384t1": None,
    "brainpoolP512t1": None,
}
Пример #28
0
class SSHKey:  # pylint:disable=too-many-instance-attributes
    """Represents a single SSH keypair.

    ssh_key = SSHKey(key_data, strict=True)
    ssh_key.parse()

    strict=True (default) only allows keys ssh-keygen generates. Setting strict mode to false allows
    all keys OpenSSH actually accepts, including highly insecure ones. For example, OpenSSH accepts
    512-bit DSA keys and 64-bit RSA keys which are highly insecure."""

    DSA_MIN_LENGTH_STRICT = 1024
    DSA_MAX_LENGTH_STRICT = 1024
    DSA_MIN_LENGTH_LOOSE = 1
    DSA_MAX_LENGTH_LOOSE = 3072

    DSA_N_LENGTH = 160

    ECDSA_CURVE_DATA = {
        b"nistp256": (ec.SECP256R1(), hashes.SHA256()),
        b"nistp192": (ec.SECP192R1(), hashes.SHA256()),
        b"nistp224": (ec.SECP224R1(), hashes.SHA256()),
        b"nistp384": (ec.SECP384R1(), hashes.SHA384()),
        b"nistp521": (ec.SECP521R1(), hashes.SHA512())
    }

    RSA_MIN_LENGTH_STRICT = 1024
    RSA_MAX_LENGTH_STRICT = 16384
    RSA_MIN_LENGTH_LOOSE = 768
    RSA_MAX_LENGTH_LOOSE = 16384

    # Valid as of OpenSSH_8.3
    # argument name, value is mandatory. Options are case-insensitive, but this list must be in lowercase.
    OPTIONS_SPEC = [
        ("agent-forwarding", False),
        ("cert-authority", False),
        ("command", True),
        ("environment", True),
        ("expiry-time", True),
        ("from", True),
        ("no-agent-forwarding", False),
        ("no-port-forwarding", False),
        ("no-pty", False),
        ("no-user-rc", False),
        ("no-x11-forwarding", False),
        ("permitlisten", True),
        ("permitopen", True),
        ("port-forwarding", False),
        ("principals", True),
        ("pty", False),
        ("no-touch-required", False),
        ("restrict", False),
        ("tunnel", True),
        ("user-rc", False),
        ("x11-forwarding", False),
    ]
    OPTION_NAME_RE = re.compile("^[A-Za-z0-9-]+$")

    INT_LEN = 4

    FIELDS = [
        "rsa", "dsa", "ecdsa", "bits", "comment", "options", "options_raw",
        "key_type"
    ]

    def __init__(self, keydata=None, **kwargs):
        self.keydata = keydata
        self._decoded_key = None
        self.rsa = None
        self.dsa = None
        self.ecdsa = None
        self.bits = None
        self.comment = None
        self.options = None
        self.options_raw = None
        self.key_type = None
        self.strict_mode = bool(kwargs.get("strict", True))
        self.skip_option_parsing = bool(
            kwargs.get("skip_option_parsing", False))
        self.disallow_options = bool(kwargs.get("disallow_options", False))
        if keydata:
            try:
                self.parse(keydata)
            except (InvalidKeyError, NotImplementedError):
                pass

    def __str__(self):
        return f"Key type: {self.key_type.decode()}, bits: {self.bits}, options: {self.options}"

    def reset(self):
        """Reset all data fields."""
        for field in self.FIELDS:
            setattr(self, field, None)

    @property
    def key(self):
        """Base64 encoded key"""
        return base64.b64encode(self._decoded_key)

    def hash(self):
        """Calculate md5 fingerprint.

        Deprecated, use .hash_md5() instead."""
        warnings.warn(
            "hash() is deprecated. Use hash_md5(), hash_sha256() or hash_sha512() instead."
        )
        return self.hash_md5().replace(b"MD5:", b"")

    def hash_md5(self):
        """Calculate md5 fingerprint.

        Shamelessly copied from http://stackoverflow.com/questions/6682815/deriving-an-ssh-fingerprint-from-a-public-key-in-python

        For specification, see RFC4716, section 4."""
        fp_plain = hashlib.md5(self._decoded_key).hexdigest()
        return "MD5:" + ':'.join(
            a + b for a, b in zip(fp_plain[::2], fp_plain[1::2]))

    def hash_sha256(self):
        """Calculate sha256 fingerprint."""
        fp_plain = hashlib.sha256(self._decoded_key).digest()
        return (b"SHA256:" +
                base64.b64encode(fp_plain).replace(b"=", b"")).decode("utf-8")

    def hash_sha512(self):
        """Calculates sha512 fingerprint."""
        fp_plain = hashlib.sha512(self._decoded_key).digest()
        return (b"SHA512:" +
                base64.b64encode(fp_plain).replace(b"=", b"")).decode("utf-8")

    def _unpack_by_int(self, data, current_position):
        """Returns a tuple with (location of next data field, contents of requested data field)."""
        # Unpack length of data field
        try:
            requested_data_length = struct.unpack(
                '>I',
                data[current_position:current_position + self.INT_LEN])[0]
        except struct.error as ex:
            raise MalformedDataError(
                f"Unable to unpack {self.INT_LEN} bytes from the data") from ex

        # Move pointer to the beginning of the data field
        current_position += self.INT_LEN
        remaining_data_length = len(data[current_position:])

        if remaining_data_length < requested_data_length:
            raise MalformedDataError(
                f"Requested {requested_data_length} bytes, but only {remaining_data_length} bytes available."
            )

        next_data = data[current_position:current_position +
                         requested_data_length]
        # Move pointer to the end of the data field
        current_position += requested_data_length
        return current_position, next_data

    @classmethod
    def _parse_long(cls, data):
        """Calculate two's complement."""
        if sys.version < '3':
            # this does not exist in python 3 - undefined-variable disabled to make pylint happier.
            ret = long(0)  # pylint:disable=undefined-variable
            for byte in data:
                ret = (ret << 8) + ord(byte)
        else:
            ret = 0
            for byte in data:
                ret = (ret << 8) + byte
        return ret

    def _split_key(self, data):
        options_raw = None
        # Terribly inefficient way to remove options, but hey, it works.
        if not data.startswith("ssh-") and not data.startswith(
                "ecdsa-") and not data.startswith("sk-"):
            quote_open = False
            for i, character in enumerate(data):
                if character == '"':  # only double quotes are allowed, no need to care about single quotes
                    quote_open = not quote_open
                if quote_open:
                    continue
                if character == " ":
                    # Data begins after the first space
                    options_raw = data[:i]
                    data = data[i + 1:]
                    break
            else:
                raise MalformedDataError(
                    "Couldn't find beginning of the key data")
        key_parts = data.strip().split(None, 2)
        if len(key_parts) < 2:  # Key type and content are mandatory fields.
            raise InvalidKeyError(
                "Unexpected key format: at least type and base64 encoded value is required"
            )
        if len(key_parts) == 3:
            self.comment = key_parts[2]
            key_parts = key_parts[0:2]
        if options_raw:
            # Populate and parse options field.
            self.options_raw = options_raw
            if not self.skip_option_parsing:
                self.options = self.parse_options(self.options_raw)
        else:
            # Set empty defaults for fields
            self.options_raw = None
            self.options = {}
        return key_parts

    @classmethod
    def decode_key(cls, pubkey_content):
        """Decode base64 coded part of the key."""
        try:
            decoded_key = base64.b64decode(pubkey_content.encode("ascii"))
        except (TypeError, binascii.Error) as ex:
            raise MalformedDataError("Unable to decode the key") from ex
        return decoded_key

    @classmethod
    def _bits_in_number(cls, number):
        return len(format(number, "b"))

    def parse_options(self, options):
        """Parses ssh options string."""
        quote_open = False
        parsed_options = {}

        def parse_add_single_option(opt):
            """Parses and validates a single option, and adds it to parsed_options field."""
            if "=" in opt:
                opt_name, opt_value = opt.split("=", 1)
                opt_value = opt_value.replace('"', '')
            else:
                opt_name = opt
                opt_value = True
            if " " in opt_name or not self.OPTION_NAME_RE.match(opt_name):
                raise InvalidOptionNameError(
                    f"{opt_name} is not a valid option name.")
            if self.strict_mode:
                for valid_opt_name, value_required in self.OPTIONS_SPEC:
                    if opt_name.lower() == valid_opt_name:
                        if value_required and opt_value is True:
                            raise MissingMandatoryOptionValueError(
                                f"{opt_name} is missing a mandatory value.")
                        break
                else:
                    raise UnknownOptionNameError(
                        f"{opt_name} is an unrecognized option name.")
            if opt_name not in parsed_options:
                parsed_options[opt_name] = []
            parsed_options[opt_name].append(opt_value)

        start_of_current_opt = 0
        i = 1  # Need to be set for empty options strings
        for i, character in enumerate(options):
            if character == '"':  # only double quotes are allowed, no need to care about single quotes
                quote_open = not quote_open
            if quote_open:
                continue
            if character == ",":
                opt = options[start_of_current_opt:i]
                parse_add_single_option(opt)
                start_of_current_opt = i + 1
                # Data begins after the first space
        if start_of_current_opt + 1 != i:
            opt = options[start_of_current_opt:]
            parse_add_single_option(opt)
        if quote_open:
            raise InvalidOptionsError("Unbalanced quotes.")
        return parsed_options

    def _process_ssh_rsa(self, data):
        """Parses ssh-rsa public keys."""
        current_position, raw_e = self._unpack_by_int(data, 0)
        current_position, raw_n = self._unpack_by_int(data, current_position)

        unpacked_e = self._parse_long(raw_e)
        unpacked_n = self._parse_long(raw_n)

        self.rsa = RSAPublicNumbers(unpacked_e,
                                    unpacked_n).public_key(default_backend())
        self.bits = self.rsa.key_size

        if self.strict_mode:
            min_length = self.RSA_MIN_LENGTH_STRICT
            max_length = self.RSA_MAX_LENGTH_STRICT
        else:
            min_length = self.RSA_MIN_LENGTH_LOOSE
            max_length = self.RSA_MAX_LENGTH_LOOSE
        if self.bits < min_length:
            raise TooShortKeyError(
                f"{self.key_type.decode()} key data can not be shorter than {min_length} bits (was {self.bits})"
            )
        if self.bits > max_length:
            raise TooLongKeyError(
                f"{self.key_type.decode()} key data can not be longer than {max_length} bits (was {self.bits})"
            )
        return current_position

    def _process_ssh_dss(self, data):
        """Parses ssh-dsa public keys."""
        data_fields = {}
        current_position = 0
        for item in ("p", "q", "g", "y"):
            current_position, value = self._unpack_by_int(
                data, current_position)
            data_fields[item] = self._parse_long(value)

        q_bits = self._bits_in_number(data_fields["q"])
        p_bits = self._bits_in_number(data_fields["p"])
        if q_bits != self.DSA_N_LENGTH:
            raise InvalidKeyError(
                f"Incorrect DSA key parameters: bits(p)={self.bits}, q={q_bits}"
            )
        if self.strict_mode:
            min_length = self.DSA_MIN_LENGTH_STRICT
            max_length = self.DSA_MAX_LENGTH_STRICT
        else:
            min_length = self.DSA_MIN_LENGTH_LOOSE
            max_length = self.DSA_MAX_LENGTH_LOOSE
        if p_bits < min_length:
            raise TooShortKeyError(
                f"{self.key_type.decode()} key can not be shorter than {min_length} bits (was {p_bits})"
            )
        if p_bits > max_length:
            raise TooLongKeyError(
                f"{self.key_type.decode()} key data can not be longer than {max_length} bits (was {p_bits})"
            )

        dsa_parameters = DSAParameterNumbers(data_fields["p"],
                                             data_fields["q"],
                                             data_fields["g"])
        self.dsa = DSAPublicNumbers(
            data_fields["y"], dsa_parameters).public_key(default_backend())
        self.bits = self.dsa.key_size

        return current_position

    def _process_ecdsa_sha(self, data):
        """Parses ecdsa-sha public keys."""
        current_position, curve_information = self._unpack_by_int(data, 0)
        if curve_information not in self.ECDSA_CURVE_DATA:
            raise NotImplementedError(
                f"Invalid curve type: {curve_information}")
        curve, hash_algorithm = self.ECDSA_CURVE_DATA[curve_information]

        current_position, key_data = self._unpack_by_int(
            data, current_position)
        try:
            ecdsa_pubkey = ec.EllipticCurvePublicKey.from_encoded_point(
                curve, key_data)
        except ValueError as ex:
            raise InvalidKeyError("Invalid ecdsa key") from ex
        self.bits = curve.key_size
        self.ecdsa = _ECVerifyingKey(ecdsa_pubkey, hash_algorithm)
        return current_position

    def _process_ed25519(self, data):
        """Parses ed25519 keys.

        There is no (apparent) way to validate ed25519 keys. This only
        checks data length (256 bits), but does not try to validate
        the key in any way."""

        current_position, verifying_key = self._unpack_by_int(data, 0)
        verifying_key_length = len(verifying_key) * 8
        verifying_key = self._parse_long(verifying_key)

        if verifying_key < 0:
            raise InvalidKeyError("ed25519 verifying key must be >0.")

        self.bits = verifying_key_length
        if self.bits != 256:
            raise InvalidKeyLengthError(
                f"ed25519 keys must be 256 bits (was {self.bits} bits)")
        return current_position

    def _validate_application_string(self, application):
        """Validates Application string.

        Has to be an URL starting with "ssh:". See ssh-keygen(1)."""

        try:
            parsed_url = urlparse(application)
        except ValueError as err:
            raise InvalidKeyError(f"Application string: {err}") from err
        if parsed_url.scheme != b"ssh":
            raise InvalidKeyError('Application string must begin with "ssh:"')

    def _process_sk_ecdsa_sha(self, data):
        """Parses sk_ecdsa-sha public keys."""
        current_position = self._process_ecdsa_sha(data)
        current_position, application = self._unpack_by_int(
            data, current_position)
        self._validate_application_string(application)
        return current_position

    def _process_sk_ed25519(self, data):
        """Parses sk_ed25519 public keys."""
        current_position = self._process_ed25519(data)
        current_position, application = self._unpack_by_int(
            data, current_position)
        self._validate_application_string(application)
        return current_position

    def _process_key(self, data):
        if self.key_type == b"ssh-rsa":
            return self._process_ssh_rsa(data)
        if self.key_type == b"ssh-dss":
            return self._process_ssh_dss(data)
        if self.key_type.strip().startswith(b"ecdsa-sha"):
            return self._process_ecdsa_sha(data)
        if self.key_type == b"ssh-ed25519":
            return self._process_ed25519(data)
        if self.key_type.strip().startswith(b"sk-ecdsa-sha"):
            return self._process_sk_ecdsa_sha(data)
        if self.key_type.strip().startswith(b"sk-ssh-ed25519"):
            return self._process_sk_ed25519(data)
        raise NotImplementedError(
            f"Invalid key type: {self.key_type.decode()}")

    def parse(self, keydata=None):
        """Validates SSH public key.

        Throws exception for invalid keys. Otherwise returns None.

        Populates key_type, bits and bits fields.

        For rsa keys, see field "rsa" for raw public key data.
        For dsa keys, see field "dsa".
        For ecdsa keys, see field "ecdsa"."""
        if keydata is None:
            if self.keydata is None:
                raise ValueError(
                    "Key data must be supplied either in constructor or to parse()"
                )
            keydata = self.keydata
        else:
            self.reset()
            self.keydata = keydata

        if keydata.startswith("---- BEGIN SSH2 PUBLIC KEY ----"):
            # SSH2 key format
            key_type = None  # There is no redundant key-type field - skip comparing plain-text and encoded data.
            pubkey_content = "".join([
                line for line in keydata.split("\n")
                if ":" not in line and "----" not in line
            ])
        else:
            key_parts = self._split_key(keydata)
            key_type = key_parts[0]
            pubkey_content = key_parts[1]

        self._decoded_key = self.decode_key(pubkey_content)

        # Check key type
        current_position, unpacked_key_type = self._unpack_by_int(
            self._decoded_key, 0)
        if key_type is not None and key_type != unpacked_key_type.decode():
            raise InvalidTypeError(
                f"Keytype mismatch: {key_type} != {unpacked_key_type.decode()}"
            )

        self.key_type = unpacked_key_type

        key_data_length = self._process_key(
            self._decoded_key[current_position:])
        current_position = current_position + key_data_length

        if current_position != len(self._decoded_key):
            raise MalformedDataError(
                f"Leftover data: {len(self._decoded_key) - current_position} bytes"
            )

        if self.disallow_options and self.options:
            raise InvalidOptionsError("Options are disallowed.")
Пример #29
0
class Curve(Enum):
    P224 = ec.SECP224R1()
    P256 = ec.SECP256R1()
    P384 = ec.SECP384R1()
    P521 = ec.SECP521R1()
Пример #30
0
     elif qmsf == 'SHA224':
         csr=csr_add_extension.sign(private_key,hashes.SHA224(),default_backend())
     elif qmsf == 'SHA256':
         csr=csr_add_extension.sign(private_key,hashes.SHA256(),default_backend())
     else:
         csr=csr_add_extension.sign(private_key,hashes.SHA1(),default_backend())
     return {'error':True,'csr':csr.public_bytes(serialization.Encoding.PEM),'priv_key':key}
 elif mysf =='ECDSA':
     if myqd == 'P192':
         private_key=ec.generate_private_key(
             curve=ec.SECP192R1(),
             backend=default_backend()
         )
     elif myqd == 'P224':
         private_key=ec.generate_private_key(
             curve=ec.SECP224R1(),
             backend=default_backend()
         )
     elif myqd == 'P256':
         private_key=ec.generate_private_key(
             curve=ec.SECP256R1(),
             backend=default_backend()
         )
     elif myqd == 'P384':
         private_key=ec.generate_private_key(
             curve=ec.SECP384R1(),
             backend=default_backend()
         )
     elif myqd == 'P521':
         private_key=ec.generate_private_key(
             curve=ec.SECP521R1(),