Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _save_pkcs1_der(self):
'''Saves the public key in PKCS#1 DER format.
@returns: the DER-encoded public key.
'''
from pyasn1.codec.der import encoder
from rsa.asn1 import AsnPubKey
# Create the ASN object
asn_key = AsnPubKey()
asn_key.setComponentByName('modulus', self.n)
asn_key.setComponentByName('publicExponent', self.e)
return encoder.encode(asn_key)
def rsa_public_key_pkcs1_to_pkcs8(pkcs1_key):
"""Convert a PKCS1-encoded RSA private key to PKCS8."""
algorithm = RsaAlgorithmIdentifier()
algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID
pkcs8_key = PublicKeyInfo()
pkcs8_key["algorithm"] = algorithm
pkcs8_key["publicKey"] = univ.BitString.fromOctetString(pkcs1_key)
return encoder.encode(pkcs8_key)
server_public_key = self._get_subject_public_key(server_certificate)
log.debug("Starting Authentication process")
version = 6
context, auth_step, out_token = get_auth_context(self.hostname,
self.username,
self.password,
self.auth_mechanism)
while not context.complete:
nego_token = NegoToken()
nego_token['negoToken'] = out_token
ts_request = TSRequest()
ts_request['negoTokens'].append(nego_token)
ts_request_token = encoder.encode(ts_request)
log.debug("Step 2. Authenticate, returning token: %s"
% binascii.hexlify(ts_request_token))
in_token = yield self.wrap(ts_request_token), \
"Step 2. Authenticate"
in_token = self.unwrap(in_token)
log.debug("Step 3. Authenticate, received token: %s"
% binascii.hexlify(in_token))
ts_request = decoder.decode(in_token, asn1Spec=TSRequest())[0]
ts_request.check_error_code()
version = int(ts_request['version'])
out_token = \
auth_step.send(bytes(ts_request['negoTokens'][0]['negoToken']))
version = min(version, TSRequest.CLIENT_VERSION)
log.debug("Starting public key verification process at version %d"
def ssh_gss_oids(self, mode="client"):
"""
This method returns a single OID, because we only support the
Kerberos V5 mechanism.
:param str mode: Client for client mode and server for server mode
:return: A byte sequence containing the number of supported
OIDs, the length of the OID and the actual OID encoded with
DER
:note: In server mode we just return the OID length and the DER encoded
OID.
"""
OIDs = self._make_uint32(1)
krb5_OID = encoder.encode(ObjectIdentifier(self._krb5_mech))
OID_len = self._make_uint32(len(krb5_OID))
if mode == "server":
return OID_len + krb5_OID
return OIDs + OID_len + krb5_OID
Args:
seq: pyasn1_modules.rfc2459.Extensions
Returns:
dict containing these keys if present in input sequence = {
'key_usage': tuple of X509V3_KEY_USAGE_BIT_FIELDS items,
'may_act_as_ca': bool,
'subject_alt_name': str,
}
Raises:
CertificateParseError: the certificate isn't constructed
as expected way and cannot be parsed
CertificateValueError: error in a value in the certificate
"""
# convert to pyasn1.type.univ.Sequence
seq = der_decoder.decode(der_encoder.encode(seq))[0]
output = {}
cert_key_usage = []
for i in xrange(len(seq)):
oid, values = seq[i][0], seq[i][1:]
if oid == OID_X509V3_BASIC_CONSTRAINTS:
# NOTE(user):
# this doesn't seem to be formed the way the RFC describes.
# there's a dangling extra boolean in the beginning of the
# sequence, or I'm not understanding the RFC. also, the
# sequence itself is not readily available, rather it's DER-encoded
# in an OctetString.
#
# consider the following real-world examples I've sampled:
#
def get_certificate(self, filename):
"""
Return a certificate object by giving the name in the apk file
"""
pkcs7message = self.get_file(filename)
message, _ = decode(pkcs7message)
cert = encode(message[1][3])
# Remove the first identifier
# byte 0 == identifier, skip
# byte 1 == length. If byte1 & 0x80 > 1, we have long format
# The length of to read bytes is then coded
# in byte1 & 0x7F
cert = cert[2 + (cert[1] & 0x7F) if cert[1] & 0x80 > 1 else 2:]
certificate = x509.load_der_x509_certificate(cert, default_backend())
return certificate
def _save_pkcs1_der(self) -> bytes:
"""Saves the public key in PKCS#1 DER format.
:returns: the DER-encoded public key.
:rtype: bytes
"""
from pyasn1.codec.der import encoder
from rsa.asn1 import AsnPubKey
# Create the ASN object
asn_key = AsnPubKey()
asn_key.setComponentByName('modulus', self.n)
asn_key.setComponentByName('publicExponent', self.e)
return encoder.encode(asn_key)
def getKerberosTGT(clientName, password, domain, lmhash, nthash, aesKey='', kdcHost=None, requestPAC=True):
asReq = AS_REQ()
domain = domain.upper()
serverName = Principal('krbtgt/%s'%domain, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
pacRequest = KERB_PA_PAC_REQUEST()
pacRequest['include-pac'] = requestPAC
encodedPacRequest = encoder.encode(pacRequest)
asReq['pvno'] = 5
asReq['msg-type'] = int(constants.ApplicationTagNumbers.AS_REQ.value)
asReq['padata'] = noValue
asReq['padata'][0] = noValue
asReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value)
asReq['padata'][0]['padata-value'] = encodedPacRequest
reqBody = seq_set(asReq, 'req-body')
opts = list()
opts.append( constants.KDCOptions.forwardable.value )
opts.append( constants.KDCOptions.renewable.value )
opts.append( constants.KDCOptions.proxiable.value )
reqBody['kdc-options'] = constants.encodeFlags(opts)
authtime = time()
endtime = authtime + 60*5
encTGSRepPart['authtime'] = epoch2gt(authtime);
encTGSRepPart['starttime'] = epoch2gt(authtime);
encTGSRepPart['endtime'] = str(req['req-body']['till'])
encTGSRepPart['renew-till'] = str(req['req-body']['till'])
encTGSRepPart['srealm'] = realm
encTGSRepPart['sname'] = None
encTGSRepPart['sname']['name-type'] = str(req['req-body']['sname']['name-type'])
encTGSRepPart['sname']['name-string'] = None
for i in range(len(req['req-body']['sname']['name-string'])):
encTGSRepPart['sname']['name-string'][i] = str(req['req-body']['sname']['name-string'][i])
rep['enc-part']['cipher'] = encrypt(KRBTGT_KEY[0], KRBTGT_KEY[1], 8, encode(encTGSRepPart))
return encode(rep)
algorithm.setComponentByName(
'algorithm', univ.ObjectIdentifier(
'1.2.840.113549.1.1.11')) # sha256WithRSAEncryption
csr.setComponentByName('signatureAlgorithm', algorithm)
signature = self.key().sign(
certification_request_info,
padding.PKCS1v15(),
hashes.SHA256()
)
asn1sig = univ.BitString("'{sig}'H".format(
sig=codecs.encode(signature, 'hex')
.decode('ascii'))
)
csr.setComponentByName('signature', asn1sig)
return encoder.encode(csr)