def from_string(cls, key, key_id=None):
        """Construct an Signer instance from a private key in PEM format.

        Args:
            key (str): Private key in PEM format.
            key_id (str): An optional key id used to identify the private key.

        Returns:
            google.auth.crypt.Signer: The constructed signer.

        Raises:
            ValueError: If the key cannot be parsed as PKCS#1 or PKCS#8 in
                PEM format.
        """
        key = _helpers.from_bytes(key)  # PEM expects str in Python 3
        marker_id, key_bytes = pem.readPemBlocksFromFile(
            six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER)

        # Key is in pkcs1 format.
        if marker_id == 0:
            private_key = rsa.key.PrivateKey.load_pkcs1(
                key_bytes, format='DER')
        # Key is in pkcs8.
        elif marker_id == 1:
            key_info, remaining = decoder.decode(
                key_bytes, asn1Spec=_PKCS8_SPEC)
            if remaining != b'':
                raise ValueError('Unused bytes', remaining)
            private_key_info = key_info.getComponentByName('privateKey')
            private_key = rsa.key.PrivateKey.load_pkcs1(
                private_key_info.asOctets(), format='DER')
        else:
            raise ValueError('No key could be detected.')

        return cls(private_key, key_id=key_id)
def keypair_extract_raw_pubkey(keypair):
    """Extract a public key and its algorithm from a keypair.

    Input may be a string or file object, with keypair represented in either
    PKCS8-wrapped or X9.62 format (but only PEM encoded for now -- no DER).
    """
    if isinstance(keypair, str):
        keypair = StringIO(keypair)

    _, der_string = readPemBlocksFromFile(
        keypair, ('-----BEGIN PRIVATE KEY-----', '-----END PRIVATE KEY-----'),
        ('-----BEGIN EC PRIVATE KEY-----', '-----END EC PRIVATE KEY-----'))

    pubkey, key_algo = _pkcs8_extract_pubkey(der_string)

    if pubkey is None:
        pubkey, key_algo = _x9_62_extract_pubkey(der_string)

    if pubkey is not None and not _is_bootrom_supported_raw_ecc_pubkey(pubkey):
        pubkey = None

    if pubkey is not None and key_algo is not None:
        return bit_tuple_to_bytes(pubkey), algo_oid_to_name(key_algo)
    else:
        return None, None
def get_cert_from_adobe(adobe_cert):
    f = open(adobe_cert, 'r')
    buf = f.read()
    buffer_base = base64.b64encode(buf)
    f.close()

    f = open(adobe_cert + '.pem', 'w')
    f.write('-----BEGIN PKCS7-----\n')
    f.write(buffer_base)
    f.write('\n-----END PKCS7-----\n')
    f.close()

    f = open(adobe_cert + '.pem', 'r')
    _, substrate = pem.readPemBlocksFromFile(
        f, ('-----BEGIN PKCS7-----', '-----END PKCS7-----'))
    f.close()

    os.remove(adobe_cert + '.pem')
    assert substrate, 'bad PKCS7 data on input'
    contentInfo, rest = decoder.decode(substrate,
                                       asn1Spec=rfc2315.ContentInfo())

    if rest:
        substrate = substrate[:-len(rest)]

    assert encoder.encode(contentInfo, defMode=False) == substrate or \
           encoder.encode(contentInfo, defMode=True) == substrate, \
           're-encode fails'

    contentType = contentInfo.getComponentByName('contentType')

    content, _ = decoder.decode(contentInfo.getComponentByName('content'),
                                asn1Spec=contentInfoMap[contentType])

    return content.getComponentByName('certificates').getComponentByPosition(0)
def print_cert(cert_file):
    f = open(cert_file, 'r')
    buf = f.read()
    buffer_base = base64.b64encode(buf)
    f.close()

    f = open(cert_file + '.pem', 'w')
    f.write('-----BEGIN PKCS7-----\n')
    f.write(buffer_base)
    f.write('\n-----END PKCS7-----\n')
    f.close()

    f = open(cert_file + '.pem', 'r')

    _, substrate = pem.readPemBlocksFromFile(
        f, ('-----BEGIN PKCS7-----', '-----END PKCS7-----'))

    f.close()
    os.remove(cert_file + '.pem')

    assert substrate, 'bad PKCS7 data on input'

    contentInfo, rest = decoder.decode(substrate,
                                       asn1Spec=rfc2315.ContentInfo())

    if rest: substrate = substrate[:-len(rest)]

    buf = contentInfo.getComponentByName('content')

    contentType = contentInfo.getComponentByName('contentType')
    content, _ = decoder.decode(contentInfo.getComponentByName('content'),
                                asn1Spec=contentInfoMap[contentType])

    print content.prettyPrint()
    def from_string(cls, key, password='******'):
        """Construct an RsaSigner instance from a string.

        Args:
            key: string, private key in PEM format.
            password: string, password for private key file. Unused for PEM
                      files.

        Returns:
            RsaSigner instance.

        Raises:
            ValueError if the key cannot be parsed as PKCS#1 or PKCS#8 in
            PEM format.
        """
        key = _from_bytes(key)  # pem expects str in Py3
        marker_id, key_bytes = pem.readPemBlocksFromFile(
            six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER)

        if marker_id == 0:
            pkey = rsa.key.PrivateKey.load_pkcs1(key_bytes,
                                                 format='DER')
        elif marker_id == 1:
            key_info, remaining = decoder.decode(
                key_bytes, asn1Spec=_PKCS8_SPEC)
            if remaining != b'':
                raise ValueError('Unused bytes', remaining)
            pkey_info = key_info.getComponentByName('privateKey')
            pkey = rsa.key.PrivateKey.load_pkcs1(pkey_info.asOctets(),
                                                 format='DER')
        else:
            raise ValueError('No key could be detected.')

        return cls(pkey)
    def from_string(cls, key, key_id=None):
        """Construct an Signer instance from a private key in PEM format.

        Args:
            key (str): Private key in PEM format.
            key_id (str): An optional key id used to identify the private key.

        Returns:
            google.auth.crypt.Signer: The constructed signer.

        Raises:
            ValueError: If the key cannot be parsed as PKCS#1 or PKCS#8 in
                PEM format.
        """
        key = _helpers.from_bytes(key)  # PEM expects str in Python 3
        marker_id, key_bytes = pem.readPemBlocksFromFile(
            six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER
        )

        # Key is in pkcs1 format.
        if marker_id == 0:
            private_key = rsa.key.PrivateKey.load_pkcs1(key_bytes, format="DER")
        # Key is in pkcs8.
        elif marker_id == 1:
            key_info, remaining = decoder.decode(key_bytes, asn1Spec=_PKCS8_SPEC)
            if remaining != b"":
                raise ValueError("Unused bytes", remaining)
            private_key_info = key_info.getComponentByName("privateKey")
            private_key = rsa.key.PrivateKey.load_pkcs1(
                private_key_info.asOctets(), format="DER"
            )
        else:
            raise ValueError("No key could be detected.")

        return cls(private_key, key_id=key_id)
def get_cert_from_adobe(adobe_cert):
    f = open(adobe_cert, 'r')
    buf = f.read()
    buffer_base = base64.b64encode(buf)
    f.close()
    
    f = open(adobe_cert + '.pem', 'w')
    f.write('-----BEGIN PKCS7-----\n')
    f.write(buffer_base)
    f.write('\n-----END PKCS7-----\n')
    f.close()
    
    f = open(adobe_cert + '.pem', 'r')
    _, substrate = pem.readPemBlocksFromFile(f, ('-----BEGIN PKCS7-----', '-----END PKCS7-----') )
    f.close()
    
    os.remove(adobe_cert + '.pem')
    assert substrate, 'bad PKCS7 data on input'
    contentInfo, rest = decoder.decode(substrate, asn1Spec=rfc2315.ContentInfo())
    
    if rest:
        substrate = substrate[:-len(rest)]
   
    assert encoder.encode(contentInfo, defMode=False) == substrate or \
           encoder.encode(contentInfo, defMode=True) == substrate, \
           're-encode fails'
    
    contentType = contentInfo.getComponentByName('contentType')
    
    content, _ = decoder.decode(
        contentInfo.getComponentByName('content'),
        asn1Spec=contentInfoMap[contentType]
        )
    
    return content.getComponentByName('certificates').getComponentByPosition(0)
def print_cert(cert_file):
    f = open(cert_file, 'r')
    buf = f.read()
    buffer_base = base64.b64encode(buf)
    f.close()
    
    f = open(cert_file + '.pem', 'w')
    f.write('-----BEGIN PKCS7-----\n')
    f.write(buffer_base)
    f.write('\n-----END PKCS7-----\n')
    f.close()
    
    f = open(cert_file + '.pem', 'r')
    
    _, substrate = pem.readPemBlocksFromFile(f, ('-----BEGIN PKCS7-----', '-----END PKCS7-----'))
    
    f.close()
    os.remove(cert_file + '.pem')
    
    assert substrate, 'bad PKCS7 data on input'
            
    contentInfo, rest = decoder.decode(substrate, asn1Spec=rfc2315.ContentInfo())
    
    if rest: substrate = substrate[:-len(rest)]
    
    buf = contentInfo.getComponentByName('content')
    
    contentType = contentInfo.getComponentByName('contentType')
    content, _ = decoder.decode(
        contentInfo.getComponentByName('content'),
        asn1Spec=contentInfoMap[contentType]
        )
    
    print content.prettyPrint()
Exemple #9
0
    def from_string(cls, key, password='******'):
        """Construct an RsaSigner instance from a string.

        Args:
            key: string, private key in PEM format.
            password: string, password for private key file. Unused for PEM
                      files.

        Returns:
            RsaSigner instance.

        Raises:
            ValueError if the key cannot be parsed as PKCS#1 or PKCS#8 in
            PEM format.
        """
        key = _helpers._from_bytes(key)  # pem expects str in Py3
        marker_id, key_bytes = pem.readPemBlocksFromFile(
            six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER)

        if marker_id == 0:
            pkey = rsa.key.PrivateKey.load_pkcs1(key_bytes,
                                                 format='DER')
        elif marker_id == 1:
            key_info, remaining = decoder.decode(
                key_bytes, asn1Spec=_PKCS8_SPEC)
            if remaining != b'':
                raise ValueError('Unused bytes', remaining)
            pkey_info = key_info.getComponentByName('privateKey')
            pkey = rsa.key.PrivateKey.load_pkcs1(pkey_info.asOctets(),
                                                 format='DER')
        else:
            raise ValueError('No key could be detected.')

        return cls(pkey)
    def test_from_string_pkcs8_extra_bytes(self):
        key_bytes = PKCS8_KEY_BYTES
        _, pem_bytes = pem.readPemBlocksFromFile(
            six.StringIO(_helpers.from_bytes(key_bytes)), crypt._PKCS8_MARKER)

        with mock.patch('pyasn1.codec.der.decoder.decode') as mock_decode:
            key_info, remaining = None, 'extra'
            mock_decode.return_value = (key_info, remaining)
            with pytest.raises(ValueError):
                crypt.Signer.from_string(key_bytes)
            # Verify mock was called.
            mock_decode.assert_called_once_with(pem_bytes,
                                                asn1Spec=crypt._PKCS8_SPEC)
    def test_from_string_pkcs8_extra_bytes(self):
        key_bytes = self._load_pkcs8_key_bytes()
        _, pem_bytes = pem.readPemBlocksFromFile(
            six.StringIO(_from_bytes(key_bytes)),
            _pure_python_crypt._PKCS8_MARKER)

        with mock.patch('pyasn1.codec.der.decoder.decode') as mock_decode:
            key_info, remaining = None, 'extra'
            mock_decode.return_value = (key_info, remaining)
            with self.assertRaises(ValueError):
                RsaSigner.from_string(key_bytes)
            # Verify mock was called.
            mock_decode.assert_called_once_with(
                pem_bytes, asn1Spec=_pure_python_crypt._PKCS8_SPEC)
def new_rsa():
        file_name = raw_input("get an rsa  name\n")
        file = open(file_name,"r")
        buffer = file.read()
        buffer_base = base64.b64encode(buffer)
        file.close()
        
        file = open(file_name + ".pem","w")
        file.write('-----BEGIN PKCS7-----\n')
        file.write(buffer_base)
        file.write('\n-----END PKCS7-----\n')
        file.close()
        
        file = open(file_name + ".pem","r")
        
        idx, substrate = pem.readPemBlocksFromFile(
            file, ('-----BEGIN PKCS7-----', '-----END PKCS7-----')
            )
        
        file.close()
        assert substrate, 'bad PKCS7 data on input'
                
        contentInfo, rest = decoder.decode(substrate, asn1Spec=rfc2315.ContentInfo())
        
        if rest: substrate = substrate[:-len(rest)]
        
        #/home/retme/Desktop/xx/SIGN.RSA
        
        #print contentInfo
            #ContentInfo
        #print(contentInfo.prettyPrint())
        buf =   contentInfo.getComponentByName('content')
        
        f = open("./decode.rsa","w")
        f.write(str(buf))
        f.close()
        
        file = open("./encode.rsa","r")
        buffer = file.read()
        file.close()
        
        contentInfo.setComponentByName('content',buffer)
        
        ret = encoder.encode(contentInfo, defMode=True)
        
        file = open("./final.rsa","w")
        file.write(str(ret));
        file.close()
        
        print_rsa("./final.rsa")
Exemple #13
0
    def test_from_string_pkcs8_extra_bytes(self):
        key_bytes = self._load_pkcs8_key_bytes()
        _, pem_bytes = pem.readPemBlocksFromFile(
            six.StringIO(_from_bytes(key_bytes)),
            _pure_python_crypt._PKCS8_MARKER)

        with mock.patch('pyasn1.codec.der.decoder.decode') as mock_decode:
            key_info, remaining = None, 'extra'
            mock_decode.return_value = (key_info, remaining)
            with self.assertRaises(ValueError):
                RsaSigner.from_string(key_bytes)
            # Verify mock was called.
            mock_decode.assert_called_once_with(
                pem_bytes, asn1Spec=_pure_python_crypt._PKCS8_SPEC)
    def test_from_string_pkcs8_extra_bytes(self):
        key_bytes = PKCS8_KEY_BYTES
        _, pem_bytes = pem.readPemBlocksFromFile(
            six.StringIO(_helpers.from_bytes(key_bytes)),
            _python_rsa._PKCS8_MARKER)

        key_info, remaining = None, 'extra'
        decode_patch = mock.patch('pyasn1.codec.der.decoder.decode',
                                  return_value=(key_info, remaining),
                                  autospec=True)

        with decode_patch as decode:
            with pytest.raises(ValueError):
                _python_rsa.RSASigner.from_string(key_bytes)
            # Verify mock was called.
            decode.assert_called_once_with(pem_bytes,
                                           asn1Spec=_python_rsa._PKCS8_SPEC)
Exemple #15
0
 def __init__(self, filename):
     # Проверяем на DER
     file1 = open(filename, "rb")
     substrate = file1.read()
     file1.close()
     b0 = substrate[0]
     b1 = substrate[1]
     # Проверка наличия последовательности 0x30, длина сертификата не может быть меньше 127 байт
     if b0 == 48 and b1 > 128:
         self.cert_format = 'DER'
     else:
         self.cert_format = 'PEM'
         file1 = open(filename, "r")
         idx, substrate = pem.readPemBlocksFromFile(
             file1,
             ('-----BEGIN CERTIFICATE-----', '-----END CERTIFICATE-----'))
     file1.close()
     try:
         self.cert_full, rest = decoder.decode(
             substrate, asn1Spec=rfc2459.Certificate())
         self.cert = self.cert_full["tbsCertificate"]
     except:
         self.cert_format = ''
Exemple #16
0
        response0.getComponentByName('thisUpdate')
    )


if len(sys.argv) != 2:
    print("""Usage:
$ cat CACertificate.pem userCertificate.pem | %s <ocsp-responder-url>""" % sys.argv[0])
    sys.exit(-1)
else:
    ocspUrl = sys.argv[1]

# Parse CA and user certificates

issuerCert, _ = decoder.decode(
    pem.readPemBlocksFromFile(
        sys.stdin, ('-----BEGIN CERTIFICATE-----', '-----END CERTIFICATE-----')
    )[1],
    asn1Spec=rfc2459.Certificate()
)
# noinspection PyRedeclaration
userCert, _ = decoder.decode(
    pem.readPemBlocksFromFile(
        sys.stdin, ('-----BEGIN CERTIFICATE-----', '-----END CERTIFICATE-----')
    )[1],
    asn1Spec=rfc2459.Certificate()
)

# Build OCSP request

ocspReq = mkOcspRequest(issuerCert, userCert)
Exemple #17
0
#!/usr/bin/python
#
# Read ASN.1/PEM PKCS#7 on stdin, parse it into plain text,
# then build substrate from it
#
from pyasn1_modules import rfc2315, pem
from pyasn1.codec.der import encoder, decoder
import sys
    
if len(sys.argv) != 1:
    print("""Usage:
$ cat pkcs7Certificate.pem | %s""" % sys.argv[0])
    sys.exit(-1)
    
idx, substrate = pem.readPemBlocksFromFile(
    sys.stdin, ('-----BEGIN PKCS7-----', '-----END PKCS7-----')
    )

assert substrate, 'bad PKCS7 data on input'
        
contentInfo, rest = decoder.decode(substrate, asn1Spec=rfc2315.ContentInfo())

if rest: substrate = substrate[:-len(rest)]
    
print(contentInfo.prettyPrint())

assert encoder.encode(contentInfo) == substrate, 're-encode fails'

contentType = contentInfo.getComponentByName('contentType')

contentInfoMap = {
def print_rsa(file_name):
        file = open(file_name,"r")
        buffer = file.read()
        buffer_base = base64.b64encode(buffer)
        file.close()
        
        file = open(file_name + ".pem","w")
        file.write('-----BEGIN PKCS7-----\n')
        file.write(buffer_base)
        file.write('\n-----END PKCS7-----\n')
        file.close()
        
        file = open(file_name + ".pem","r")
        
        idx, substrate = pem.readPemBlocksFromFile(
            file, ('-----BEGIN PKCS7-----', '-----END PKCS7-----')
            )
        
        file.close()
        assert substrate, 'bad PKCS7 data on input'
                
        contentInfo, rest = decoder.decode(substrate, asn1Spec=rfc2315.ContentInfo())
        
        if rest: substrate = substrate[:-len(rest)]
        
        #/home/retme/Desktop/xx/SIGN.RSA
        
        #print contentInfo
            #ContentInfo
        print(contentInfo.prettyPrint())
        buf =   contentInfo.getComponentByName('content')

        assert encoder.encode(contentInfo, defMode=False) == substrate or \
               encoder.encode(contentInfo, defMode=True) == substrate, \
               're-encode fails'
        
        contentType = contentInfo.getComponentByName('contentType')
        
        #print contentInfo
        #certificates = contentInfo.getComponentByName('certificates')
        
        #certificates.prettyPrint()
        #print certificates
        contentInfoMap = {
            (1, 2, 840, 113549, 1, 7, 1): rfc2315.Data(),
            (1, 2, 840, 113549, 1, 7, 2): rfc2315.SignedData(),
            (1, 2, 840, 113549, 1, 7, 3): rfc2315.EnvelopedData(),
            (1, 2, 840, 113549, 1, 7, 4): rfc2315.SignedAndEnvelopedData(),
            (1, 2, 840, 113549, 1, 7, 5): rfc2315.DigestedData(),
            (1, 2, 840, 113549, 1, 7, 6): rfc2315.EncryptedData()
            }
        
        content, _ = decoder.decode(
            contentInfo.getComponentByName('content'),
            asn1Spec=contentInfoMap[contentType]
            )
        
        
        #content.getComponentByName('certificates').setComponentByPosition(1)
        #print content.getComponentByName('certificates').getComponentByPosition(0).getComponentByName('certificate').getComponentByName('tbsCertificate').getComponentByName('serialNumber')
        
        
        
        #print content
        print(content.prettyPrint())        
Exemple #19
0
from pyasn1.codec.der import encoder

from pyasn1_modules import pem
from pyasn1_modules import rfc2459

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

asn1Spec = rfc2459.CertificateList()

cnt = 0

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

    key, rest = decoder.decode(substrate, asn1Spec=asn1Spec)

    if rest:
        substrate = substrate[:-len(rest)]

    print(key.prettyPrint())

    assert encoder.encode(key) == substrate, 'pkcs8 recode fails'

    cnt += 1

print('*** %s CRL(s) re/serialized' % cnt)
Exemple #20
0
            response0.getComponentByName('certStatus').getName(),
            response0.getComponentByName('thisUpdate'))


if len(sys.argv) != 2:
    print("""Usage:
$ cat CACertificate.pem userCertificate.pem | %s <ocsp-responder-url>""" %
          sys.argv[0])
    sys.exit(-1)
else:
    ocspUrl = sys.argv[1]

# Parse CA and user certificates

issuerCert, _ = decoder.decode(pem.readPemBlocksFromFile(
    sys.stdin,
    ('-----BEGIN CERTIFICATE-----', '-----END CERTIFICATE-----'))[1],
                               asn1Spec=rfc2459.Certificate())
# noinspection PyRedeclaration
userCert, _ = decoder.decode(pem.readPemBlocksFromFile(
    sys.stdin,
    ('-----BEGIN CERTIFICATE-----', '-----END CERTIFICATE-----'))[1],
                             asn1Spec=rfc2459.Certificate())

# Build OCSP request

ocspReq = mkOcspRequest(issuerCert, userCert)

# Use HTTP POST to get response (see Appendix A of RFC 2560)
# In case you need proxies, set the http_proxy env variable
Exemple #21
0
from pyasn1_modules import rfc5280, pem
import sys

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

certType = rfc5280.Certificate()

certCnt = 0

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

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

    if rest:
        substrate = substrate[:-len(rest)]

    print(cert.prettyPrint())

    assert encoder.encode(cert) == substrate, 'cert recode fails'

    certCnt += 1
Exemple #22
0
#
import sys

from pyasn1.codec.der import decoder
from pyasn1.codec.der import encoder

from pyasn1_modules import pem
from pyasn1_modules import rfc2315

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

idx, substrate = pem.readPemBlocksFromFile(
    sys.stdin, ('-----BEGIN PKCS7-----', '-----END PKCS7-----')
)

assert substrate, 'bad PKCS7 data on input'

contentInfo, rest = decoder.decode(substrate, asn1Spec=rfc2315.ContentInfo())

if rest:
    substrate = substrate[:-len(rest)]

print(contentInfo.prettyPrint())

assert encoder.encode(contentInfo) == substrate, 're-encode fails'

contentType = contentInfo.getComponentByName('contentType')
Exemple #23
0
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)]
        
    print(cert.prettyPrint())

    assert encoder.encode(cert) == substrate, 'cert recode fails'
        
    certCnt += 1
    
print('*** %s PEM certificate request(s) de/serialized' % certCnt)
Exemple #24
0
#
from pyasn1.codec.der import decoder, encoder
from pyasn1_modules import rfc5208, pem
import sys

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

cnt = 0

while 1:
    idx, substrate = pem.readPemBlocksFromFile(
        sys.stdin,
        ('-----BEGIN PRIVATE KEY-----', '-----END PRIVATE KEY-----'),
        ('-----BEGIN ENCRYPTED PRIVATE KEY-----',
         '-----END ENCRYPTED PRIVATE KEY-----'))
    if not substrate:
        break

    if idx == 0:
        asn1Spec = rfc5208.PrivateKeyInfo()
    elif idx == 1:
        asn1Spec = rfc5208.EncryptedPrivateKeyInfo()
    else:
        break

    key, rest = decoder.decode(substrate, asn1Spec=asn1Spec)

    if rest: substrate = substrate[:-len(rest)]
Exemple #25
0
    async def get_signed_url(  # pylint: disable=too-many-locals
            self,
            expiration: int,
            headers: Optional[Dict[str, str]] = None,
            query_params: Optional[Dict[str, Any]] = None,
            http_method: str = 'GET',
            token: Optional[Token] = None) -> str:
        """
        Create a temporary access URL for Storage Blob accessible by anyone
        with the link.

        Adapted from Google Documentation:
        https://cloud.google.com/storage/docs/access-control/signing-urls-manually#python-sample
        """
        if expiration > 604800:
            raise ValueError("expiration time can't be longer than 604800 "
                             'seconds (7 days)')

        quoted_name = quote(self.name, safe=b'/~')
        canonical_uri = f'/{quoted_name}'

        datetime_now = datetime.datetime.utcnow()
        request_timestamp = datetime_now.strftime('%Y%m%dT%H%M%SZ')
        datestamp = datetime_now.strftime('%Y%m%d')

        # TODO: support for GCE_METADATA and AUTHORIZED_USER tokens. It should
        # be possible via API, but seems to not be working for us in some
        # cases.
        #
        # https://cloud.google.com/iam/docs/reference/credentials/rest/v1/
        # projects.serviceAccounts/signBlob
        token = token or self.bucket.storage.token
        client_email = token.service_data.get('client_email')
        private_key = token.service_data.get('private_key')
        if not client_email or not private_key:
            raise KeyError('Blob signing is only suported for tokens with '
                           'explicit client_email and private_key data; '
                           'please check your token points to a JSON service '
                           'account file')

        credential_scope = f'{datestamp}/auto/storage/goog4_request'
        credential = f'{client_email}/{credential_scope}'

        headers = headers or {}
        headers['host'] = f'{self.bucket.name}.{HOST}'

        ordered_headers = collections.OrderedDict(sorted(headers.items()))
        canonical_headers = ''.join(f'{str(k).lower()}:{str(v).lower()}\n'
                                    for k, v in ordered_headers.items())

        signed_headers = ';'.join(f'{str(k).lower()}'
                                  for k in ordered_headers.keys())

        query_params = query_params or {}
        query_params['X-Goog-Algorithm'] = 'GOOG4-RSA-SHA256'
        query_params['X-Goog-Credential'] = credential
        query_params['X-Goog-Date'] = request_timestamp
        query_params['X-Goog-Expires'] = expiration
        query_params['X-Goog-SignedHeaders'] = signed_headers

        ordered_query_params = collections.OrderedDict(
            sorted(query_params.items()))

        canonical_query_str = '&'.join(
            f'{quote(str(k), safe="")}={quote(str(v), safe="")}'
            for k, v in ordered_query_params.items())

        canonical_req = '\n'.join([
            http_method, canonical_uri, canonical_query_str, canonical_headers,
            signed_headers, 'UNSIGNED-PAYLOAD'
        ])
        canonical_req_hash = hashlib.sha256(canonical_req.encode()).hexdigest()

        str_to_sign = '\n'.join([
            'GOOG4-RSA-SHA256', request_timestamp, credential_scope,
            canonical_req_hash
        ])

        # N.B. see the ``PemKind`` enum
        marker_id, key_bytes = pem.readPemBlocksFromFile(
            io.StringIO(private_key), PKCS1_MARKER, PKCS8_MARKER)
        if marker_id == PemKind.INVALID.value:
            raise ValueError('private key is invalid or unsupported')

        if marker_id == PemKind.PKCS8.value:
            # convert from pkcs8 to pkcs1
            key_info, remaining = decoder.decode(key_bytes,
                                                 asn1Spec=PKCS8_SPEC)
            if remaining != b'':
                raise ValueError('could not read PKCS8 key: found extra bytes',
                                 remaining)

            private_key_info = key_info.getComponentByName('privateKey')
            key_bytes = private_key_info.asOctets()

        key = rsa.key.PrivateKey.load_pkcs1(key_bytes, format='DER')
        signed_blob = rsa.pkcs1.sign(str_to_sign.encode(), key, 'SHA-256')

        signature = binascii.hexlify(signed_blob).decode()

        return (f'https://{self.bucket.name}.{HOST}{canonical_uri}?'
                f'{canonical_query_str}&X-Goog-Signature={signature}')
Exemple #26
0
#
from pyasn1_modules import rfc2459, rfc2437, pem
from pyasn1.codec.der import encoder, decoder
import sys

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

cnt = 0

while True:
    idx, substrate = pem.readPemBlocksFromFile(
        sys.stdin,
        ('-----BEGIN RSA PRIVATE KEY-----', '-----END RSA PRIVATE KEY-----'),
        ('-----BEGIN DSA PRIVATE KEY-----', '-----END DSA PRIVATE KEY-----')
    )
    if not substrate:
        break

    if idx == 0:
        asn1Spec = rfc2437.RSAPrivateKey()
    elif idx == 1:
        asn1Spec = rfc2459.DSAPrivateKey()
    else:
        break

    key, rest = decoder.decode(substrate, asn1Spec=asn1Spec)

    if rest:
Exemple #27
0
from pyasn1.codec.der import encoder

from pyasn1_modules import pem
from pyasn1_modules import rfc2459

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

asn1Spec = rfc2459.CertificateList()

cnt = 0

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

    key, rest = decoder.decode(substrate, asn1Spec=asn1Spec)

    if rest:
        substrate = substrate[:-len(rest)]

    print(key.prettyPrint())

    assert encoder.encode(key) == substrate, 'pkcs8 recode fails'

    cnt += 1

print('*** %s CRL(s) re/serialized' % cnt)
Exemple #28
0
    """
  AuthorityInfoAccessSyntax  ::=
             SEQUENCE SIZE (1..MAX) OF AccessDescription
  """
    # FIXME: SIZE not encoded.
    componentType = AccessDescription()


id_ad_caIssuers = univ.ObjectIdentifier('1.3.6.1.5.5.7.48.2')

# End of RFC 5280 4.2.2.1

certCnt = 0

while 1:
    idx, substrate = pem.readPemBlocksFromFile(sys.stdin, (cStart, cEnd))
    if not substrate:
        break

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

    if rest: substrate = substrate[:-len(rest)]

    print(cert.prettyPrint())

    tbs = cert.getComponentByName('tbsCertificate')
    extensions = tbs.getComponentByName('extensions') or []

    for extension in extensions:
        oid = extension.getComponentByName('extnID')
        if oid != id_pe_authorityInfoAccess:
Exemple #29
0
if len(sys.argv) != 1:
    print(
        """Usage:
$ cat CACertificate.pem | %s
$ cat userCertificate.pem | %s"""
        % (sys.argv[0], sys.argv[0])
    )
    sys.exit(-1)

certType = rfc2459.Certificate()

certCnt = 0

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

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

    if rest:
        substrate = substrate[: -len(rest)]

    print(cert.prettyPrint())

    assert (
        encoder.encode(cert, defMode=False) == substrate or encoder.encode(cert, defMode=True) == substrate
    ), "cert recode fails"

    certCnt = certCnt + 1
Exemple #30
0
# stdin, print them pretty and encode back into original wire format.
# Private keys can be generated with "openssl genrsa|gendsa" commands.
#
from pyasn1_modules import rfc2459, rfc2437, pem
from pyasn1.codec.der import encoder, decoder
import sys

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

while 1:
    idx, substrate = pem.readPemBlocksFromFile(sys.stdin, ('-----BEGIN RSA PRIVATE KEY-----', '-----END RSA PRIVATE KEY-----'), ('-----BEGIN DSA PRIVATE KEY-----', '-----END DSA PRIVATE KEY-----') )
    if not substrate:
        break

    if idx == 0:
        asn1Spec = rfc2437.RSAPrivateKey()
    elif idx == 1:
        asn1Spec = rfc2459.DSAPrivateKey()
    else:
        break

    key, rest = decoder.decode(substrate, asn1Spec=asn1Spec)

    if rest: substrate = substrate[:-len(rest)]
        
    print(key.prettyPrint())
  """
  AuthorityInfoAccessSyntax  ::=
             SEQUENCE SIZE (1..MAX) OF AccessDescription
  """
  # FIXME: SIZE not encoded.
  componentType = AccessDescription()

id_ad_caIssuers = univ.ObjectIdentifier('1.3.6.1.5.5.7.48.2')

# End of RFC 5280 4.2.2.1

certCnt = 0

while 1:
  idx, substrate = pem.readPemBlocksFromFile(
    sys.stdin, (cStart, cEnd)
    )
  if not substrate:
    break

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

  if rest: substrate = substrate[:-len(rest)]

  print cert.prettyPrint()

  tbs = cert.getComponentByName('tbsCertificate')
  extensions = tbs.getComponentByName('extensions') or []

  for extension in extensions:
    oid = extension.getComponentByName('extnID')
Exemple #32
0
            assert val is not None

            ret += '/' + str(attrType) + '=' + val

        ret += ']'

    return ret


certs = {}
inChain = []

certfile = open(sys.argv[1])

while 1:
    idx, substrate = pem.readPemBlocksFromFile(certfile, (cStart, cEnd))
    if not substrate:
        break

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

    tbs = cert.getComponentByName('tbsCertificate')

    subjectDN = tbs.getComponentByName('subject')
    print DNToString(subjectDN)

    certs[DNToString(subjectDN)] = cert
    inChain.append(cert)

#for subject, cert in certs.iteritems():
        
      assert val is not None
      
      ret += '/' + str(attrType) + '=' + val
      
    ret += ']'
    
  return ret

certs = {}
inChain = []

certfile = open(sys.argv[1])

while 1:
  idx, substrate = pem.readPemBlocksFromFile(certfile, (cStart, cEnd))
  if not substrate:
    break

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

  tbs = cert.getComponentByName('tbsCertificate')

  subjectDN = tbs.getComponentByName('subject')
  print DNToString(subjectDN)

  certs[DNToString(subjectDN)] = cert
  inChain.append(cert)

#for subject, cert in certs.iteritems():
Exemple #34
0
from pyasn1.codec.der import encoder

from pyasn1_modules import pem
from pyasn1_modules import rfc5208

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

cnt = 0

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

    if idx == 0:
        asn1Spec = rfc5208.PrivateKeyInfo()
    elif idx == 1:
        asn1Spec = rfc5208.EncryptedPrivateKeyInfo()
    else:
        break

    key, rest = decoder.decode(substrate, asn1Spec=asn1Spec)

    if rest:
Exemple #35
0

if len(sys.argv) != 2:
    print(
        """Usage:
$ cat CACertificate.pem userCertificate.pem | %s <ocsp-responder-url>"""
        % sys.argv[0]
    )
    sys.exit(-1)
else:
    ocspUrl = sys.argv[1]

# Parse CA and user certificates

issuerCert, _ = decoder.decode(
    pem.readPemBlocksFromFile(sys.stdin, ("-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----"))[1],
    asn1Spec=rfc2459.Certificate(),
)
userCert, _ = decoder.decode(
    pem.readPemBlocksFromFile(sys.stdin, ("-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----"))[1],
    asn1Spec=rfc2459.Certificate(),
)

# Build OCSP request

ocspReq = mkOcspRequest(issuerCert, userCert)

# Use HTTP POST to get response (see Appendix A of RFC 2560)
# In case you need proxies, set the http_proxy env variable

httpReq = urllib2.Request(ocspUrl, encoder.encode(ocspReq), {"Content-Type": "application/ocsp-request"})