Пример #1
0
def create_csr_ec(key, dn, network, csrfilename=None, attributes=None):
    """ from jandd pkiutils adjusted for EC
    """
    certreqInfo = rfc2314.CertificationRequestInfo()
    certreqInfo.setComponentByName('version', rfc2314.Version(0))
    certreqInfo.setComponentByName('subject', _build_dn(dn))
    certreqInfo.setComponentByName('subjectPublicKeyInfo',
                                   _build_subject_publickey_info(key))
    attrpos = certreqInfo.componentType.getPositionByName('attributes')
    attrtype = certreqInfo.componentType.getTypeByPosition(attrpos)
    attr_asn1 = _build_attributes(attributes, attrtype)
    certreqInfo.setComponentByName('attributes', attr_asn1)
    certreq = rfc2314.CertificationRequest()
    certreq.setComponentByName('certificationRequestInfo', certreqInfo)
    sigAlgIdentifier = rfc2314.SignatureAlgorithmIdentifier()
    sigAlgIdentifier.setComponentByName('algorithm',
                                        utility.OID_ecdsaWithSHA256)
    certreq.setComponentByName('signatureAlgorithm', sigAlgIdentifier)
    sig = _build_signature(key, certreqInfo, network)
    certreq.setComponentByName('signature', sig)
    output = pkiutils._der_to_pem(encoder.encode(certreq),
                                  'CERTIFICATE REQUEST')

    if csrfilename:
        with open(csrfilename, 'w') as csrfile:
            csrfile.write(output)
    print "generated certification request:\n\n%s" % output
    return output
def csr_public_key_offset_length(csr):
    pk_der = bytearray(encoder.encode(csr['certificationRequestInfo']['subjectPublicKeyInfo']['subjectPublicKey']))
    pk_info = der_value_offset_length(pk_der)
    # Skip the unused bits field and key compression byte
    pk_der[pk_info['offset']+2] ^= 0xFF

    csr_der = encoder.encode(csr)
    csr_mod = decoder.decode(csr_der, asn1Spec=rfc2314.CertificationRequest())[0]
    csr_mod['certificationRequestInfo']['subjectPublicKeyInfo']['subjectPublicKey'] = decoder.decode(bytes(pk_der))[0]

    return {'offset':diff_offset(csr_der, encoder.encode(csr_mod)), 'length':pk_info['length']-2}
Пример #3
0
 def from_open_file(f):
     try:
         der_content = pem.readPemFromFile(
             f,
             startMarker='-----BEGIN CERTIFICATE REQUEST-----',
             endMarker='-----END CERTIFICATE REQUEST-----')
         csr = decoder.decode(der_content,
                              asn1Spec=rfc2314.CertificationRequest())[0]
         return X509Csr(csr)
     except Exception:
         raise X509CsrError("Could not read X509 certificate from "
                            "PEM data.")
Пример #4
0
    def sign_csr(self, certification_request_info):
        reqinfo = decoder.decode(certification_request_info,
                                 rfc2314.CertificationRequestInfo())[0]
        csr = rfc2314.CertificationRequest()
        csr.setComponentByName('certificationRequestInfo', reqinfo)

        algorithm = rfc2314.SignatureAlgorithmIdentifier()
        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("'%s'H" % signature.encode('hex'))
        csr.setComponentByName('signature', asn1sig)
        return encoder.encode(csr)
Пример #5
0
def _create_csr(cert, private_key):
    """Creates a CSR with the RENEWAL_CERTIFICATE extension"""

    subject_public_key_info = decoder.decode(
        private_key.public_key().public_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PublicFormat.SubjectPublicKeyInfo),
        asn1Spec=rfc2314.SubjectPublicKeyInfo())[0]

    subject = cert[0]['tbsCertificate']['subject']

    # Microsoft OID: szOID_RENEWAL_CERTIFICATE
    renewal_certificate_type = rfc2314.AttributeType(
        (1, 3, 6, 1, 4, 1, 311, 13, 1))
    renewal_certificate_value = rfc2314.univ.SetOf().setComponents(cert[0])

    renewal_certificate = rfc2314.Attribute()
    renewal_certificate.setComponentByName('type', renewal_certificate_type)
    renewal_certificate.setComponentByName('vals', renewal_certificate_value)

    attributes = rfc2314.Attributes().subtype(implicitTag=rfc2314.tag.Tag(
        rfc2314.tag.tagClassContext, rfc2314.tag.tagFormatConstructed, 0))
    attributes.setComponents(renewal_certificate)

    certification_request_info = rfc2314.CertificationRequestInfo()
    certification_request_info.setComponentByName('version', 0)
    certification_request_info.setComponentByName('subject', subject)
    certification_request_info.setComponentByName('subjectPublicKeyInfo',
                                                  subject_public_key_info)
    certification_request_info.setComponentByName('attributes', attributes)

    raw_signature, signature_algorithm = _sign(
        private_key, encoder.encode(certification_request_info))

    signature = rfc2314.univ.BitString(
        hexValue=binascii.hexlify(raw_signature).decode('ascii'))

    certification_request = rfc2314.CertificationRequest()
    certification_request.setComponentByName('certificationRequestInfo',
                                             certification_request_info)
    certification_request.setComponentByName('signatureAlgorithm',
                                             signature_algorithm)
    certification_request.setComponentByName('signature', signature)

    return encoder.encode(certification_request)
Пример #6
0
    def test_rsa_cert(self):
        """Generates a PKCS#7 renewal request from an rsa certificate"""
        cert, key = _generate_self_signed_cert('rsa')
        csr = pkcs7csr.create_pkcs7csr(cert, key)

        verify_result, raw_inner_csr = _verify_pkcs7_signature(csr)

        inner_csr = x509.load_der_x509_csr(raw_inner_csr, default_backend())

        decoded_inner_csr = decoder.decode(raw_inner_csr, asn1Spec=rfc2314.CertificationRequest())
        encoded_inner_csr = encoder.encode(decoded_inner_csr[0]['certificationRequestInfo']
                                           ['attributes'][0]['vals'][0])

        self.assertEqual(verify_result, 0)
        self.assertEqual(inner_csr.is_signature_valid, True)
        self.assertEqual(
            key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo),
            inner_csr.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo))
        self.assertEqual(cert.public_bytes(Encoding.DER), encoded_inner_csr)
def gen_cert_def_c_device_csr(csr_der):
    # Use the device certificate to create a CSR template
    csr = decoder.decode(csr_der, asn1Spec=rfc2314.CertificationRequest())[0]

    params = {}

    info = csr_public_key_offset_length(csr)
    params['public_key_cert_loc_offset'] = info['offset']
    params['public_key_cert_loc_count']  = info['length']

    info = cert_tbs_offset_length(csr) # cert TBS works for CSR too
    params['tbs_cert_loc_offset'] = info['offset']
    params['tbs_cert_loc_count']  = info['length']

    info = cert_sig_offset_length(csr) # cert sig works for CSR too
    params['signature_cert_loc_offset'] = info['offset']
    params['signature_cert_loc_count']  = info['length']

    params['cert_template'] = bin_to_c_hex(csr_der)

    return string.Template(cert_def_3_device_csr_c).substitute(params)
Пример #8
0
class PKIBody(univ.Choice):
    """
    PKIBody ::= CHOICE {       -- message-specific body elements
         ir       [0]  CertReqMessages,        --Initialization Request
         ip       [1]  CertRepMessage,         --Initialization Response
         cr       [2]  CertReqMessages,        --Certification Request
         cp       [3]  CertRepMessage,         --Certification Response
         p10cr    [4]  CertificationRequest,   --imported from [PKCS10]
         popdecc  [5]  POPODecKeyChallContent, --pop Challenge
         popdecr  [6]  POPODecKeyRespContent,  --pop Response
         kur      [7]  CertReqMessages,        --Key Update Request
         kup      [8]  CertRepMessage,         --Key Update Response
         krr      [9]  CertReqMessages,        --Key Recovery Request
         krp      [10] KeyRecRepContent,       --Key Recovery Response
         rr       [11] RevReqContent,          --Revocation Request
         rp       [12] RevRepContent,          --Revocation Response
         ccr      [13] CertReqMessages,        --Cross-Cert. Request
         ccp      [14] CertRepMessage,         --Cross-Cert. Response
         ckuann   [15] CAKeyUpdAnnContent,     --CA Key Update Ann.
         cann     [16] CertAnnContent,         --Certificate Ann.
         rann     [17] RevAnnContent,          --Revocation Ann.
         crlann   [18] CRLAnnContent,          --CRL Announcement
         pkiconf  [19] PKIConfirmContent,      --Confirmation
         nested   [20] NestedMessageContent,   --Nested Message
         genm     [21] GenMsgContent,          --General Message

    """
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('ir', rfc2511.CertReqMessages().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,0)
            )
        ),
        namedtype.NamedType('ip', CertRepMessage().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,1)
            )
        ),
        namedtype.NamedType('cr', rfc2511.CertReqMessages().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,2)
            )
        ),
        namedtype.NamedType('cp', CertRepMessage().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,3)
            )
        ),
        namedtype.NamedType('p10cr', rfc2314.CertificationRequest().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,4)
            )
        ),
        namedtype.NamedType('popdecc', POPODecKeyChallContent().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,5)
            )
        ),
        namedtype.NamedType('popdecr', POPODecKeyRespContent().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,6)
            )
        ),
        namedtype.NamedType('kur', rfc2511.CertReqMessages().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,7)
            )
        ),
        namedtype.NamedType('kup', CertRepMessage().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,8)
            )
        ),
        namedtype.NamedType('krr', rfc2511.CertReqMessages().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,9)
            )
        ),
        namedtype.NamedType('krp', KeyRecRepContent().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,10)
            )
        ),
        namedtype.NamedType('rr', RevReqContent().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,11)
            )
        ),
        namedtype.NamedType('rp', RevRepContent().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,12)
            )
        ),
        namedtype.NamedType('ccr', rfc2511.CertReqMessages().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,13)
            )
        ),
        namedtype.NamedType('ccp', CertRepMessage().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,14)
            )
        ),
        namedtype.NamedType('ckuann', CAKeyUpdAnnContent().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,15)
            )
        ),
        namedtype.NamedType('cann', CertAnnContent().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,16)
            )
        ),
        namedtype.NamedType('rann', RevAnnContent().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,17)
            )
        ),
        namedtype.NamedType('crlann', CRLAnnContent().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,18)
            )
        ),
        namedtype.NamedType('pkiconf', PKIConfirmContent().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,19)
            )
        ),
        namedtype.NamedType('nested', nestedMessageContent),
#        namedtype.NamedType('nested', NestedMessageContent().subtype(
#            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,20)
#            )
#        ),
        namedtype.NamedType('genm', GenMsgContent().subtype(
            explicitTag=tag.Tag(tag.tagClassContext,tag.tagFormatConstructed,21)
            )
        )
    )
Пример #9
0
 def setUp(self):
     self.asn1Spec = rfc2314.CertificationRequest()
Пример #10
0
def main():
    parser = argparse.ArgumentParser(
        description=
        'utxocsr.py by MiWCryptoCurrency for UTXOC UTXO based certificate signing (to produce PEM encoded).'
    )
    parser.add_argument('-k',
                        '--key',
                        required=True,
                        type=argparse.FileType('r'),
                        help='Private EC Key')
    parser.add_argument('-c',
                        '--csrfilename',
                        required=True,
                        type=argparse.FileType('r'),
                        help='Input CSR Filename')
    parser.add_argument('-f',
                        '--certfilename',
                        required=True,
                        type=argparse.FileType('w'),
                        help='Output UTXOC Filename')
    parser.add_argument('-n',
                        "--network",
                        help='specify network (default: BTC = Bitcoin)',
                        default='BTC',
                        choices=NETWORK_NAMES)
    parser.add_argument('-r',
                        "--redemption",
                        required=False,
                        help='redemption address (to claim after expiry)')

    parser.add_argument(
        '-d',
        "--days",
        required=False,
        help=
        'number of days to hold Bond (certificate validity period). Suggested >365'
    )
    inputkey = ""
    inputcsr = ""
    args = parser.parse_args()
    network = args.network
    days = 365
    if args.days:
        days = args.days
    csrfilename = args.csrfilename
    while True:
        line = args.key.readline().strip()
        if not line: break
        inputkey += line + '\n'
    parsed_key = decoder.decode(utility.read_ec_private_pem(inputkey),
                                asn1Spec=utility.ECPrivateKey())
    secret_exponent = encoding.to_long(256, encoding.byte_to_int,
                                       parsed_key[0][1].asOctets())[0]
    #coin  = Key(secret_exponent=secret_exponent, netcode=network)
    #pubaddr = coin.address(use_uncompressed=False)
    while True:
        line = args.csrfilename.readline().strip()
        if not line: break
        inputcsr += line + '\n'
    parsed_csr = decoder.decode(utility.read_csr_pem(inputcsr),
                                asn1Spec=rfc2314.CertificationRequest())
    tbs = _build_tbs(parsed_csr[0], days, network)
    certificate = rfc2459.Certificate()
    certificate.setComponentByName('tbsCertificate', tbs)
    certificate.setComponentByName('signatureAlgorithm',
                                   _build_ECDSAwithSHA256_signatureAlgorithm())
    certificate.setComponentByName('signatureValue',
                                   _build_signature(parsed_key, tbs, network))
    certder = encoder.encode(certificate)
    certpem = utility.generate_certificate_pem(certder)
    args.certfilename.write(certpem)
    print certpem
    return
Пример #11
0
# Copyright (c) 2005-2017, Ilya Etingof <*****@*****.**>
# License: http://pyasn1.sf.net/license.html
#
# Read ASN.1/PEM X.509 certificate requests (PKCS#10 format) on stdin, 
# parse each into plain text, then build substrate from it
#
from pyasn1.codec.der import decoder, encoder
from pyasn1_modules import rfc2314, pem
import sys

if len(sys.argv) != 1:
    print("""Usage:
$ cat certificateRequest.pem | %s""" % sys.argv[0])
    sys.exit(-1)

certType = rfc2314.CertificationRequest()

certCnt = 0

while True:
    idx, substrate = pem.readPemBlocksFromFile(
        sys.stdin, ('-----BEGIN CERTIFICATE REQUEST-----',
                    '-----END CERTIFICATE REQUEST-----')
    )
    if not substrate:
        break

    cert, rest = decoder.decode(substrate, asn1Spec=certType)

    if rest:
        substrate = substrate[:-len(rest)]
Пример #12
0
class PKIBody(univ.Choice):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType(
            'ir',
            rfc2511.CertReqMessages().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 0))),
        namedtype.NamedType(
            'ip',
            CertRepMessage().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 1))),
        namedtype.NamedType(
            'cr',
            rfc2511.CertReqMessages().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 2))),
        namedtype.NamedType(
            'cp',
            CertRepMessage().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 3))),
        namedtype.NamedType(
            'p10cr',
            rfc2314.CertificationRequest().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 4))),
        namedtype.NamedType(
            'popdecc',
            POPODecKeyChallContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 5))),
        namedtype.NamedType(
            'popdecr',
            POPODecKeyRespContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 6))),
        namedtype.NamedType(
            'kur',
            rfc2511.CertReqMessages().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 7))),
        namedtype.NamedType(
            'kup',
            CertRepMessage().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 8))),
        namedtype.NamedType(
            'krr',
            rfc2511.CertReqMessages().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 9))),
        namedtype.NamedType(
            'krp',
            KeyRecRepContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 10))),
        namedtype.NamedType(
            'rr',
            RevReqContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 11))),
        namedtype.NamedType(
            'rp',
            RevRepContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 12))),
        namedtype.NamedType(
            'ccr',
            rfc2511.CertReqMessages().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 13))),
        namedtype.NamedType(
            'ccp',
            CertRepMessage().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 14))),
        namedtype.NamedType(
            'ckuann',
            CAKeyUpdAnnContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 15))),
        namedtype.NamedType(
            'cann',
            CertAnnContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 16))),
        namedtype.NamedType(
            'rann',
            RevAnnContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 17))),
        namedtype.NamedType(
            'crlann',
            CRLAnnContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 18))),
        namedtype.NamedType(
            'pkiconf',
            PKIConfirmContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 19))),
        namedtype.NamedType('nested', nestedMessageContent),
        namedtype.NamedType(
            'genm',
            GenMsgContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 21))),
        namedtype.NamedType(
            'gen',
            GenRepContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 22))),
        namedtype.NamedType(
            'error',
            ErrorMsgContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 23))),
        namedtype.NamedType(
            'certConf',
            CertConfirmContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 24))),
        namedtype.NamedType(
            'pollReq',
            PollReqContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 25))),
        namedtype.NamedType(
            'pollRep',
            PollRepContent().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 26))))
Пример #13
0
 def __init__(self, csr=None):
     if csr is None:
         self._csr = rfc2314.CertificationRequest()
     else:
         self._csr = csr