Beispiel #1
0
 def testEncode1(self):
     # Empty sequence
     der = DerOctetString()
     self.assertEquals(encode(), b('\x04\x00'))
     # Small payload
     der.payload = b('\x01\x02')
     self.assertEquals(encode(), b('\x04\x02\x01\x02'))
Beispiel #2
0
 def testEncode2(self):
     # Multi-byte integers
     # Value 128
     der = DerInteger(128)
     self.assertEquals(encode(), b('\x02\x02\x00\x80'))
     # Value 0x180
     der = DerInteger(0x180)
     self.assertEquals(encode(), b('\x02\x02\x01\x80'))
     # One very long integer
     der = DerInteger(2**2048)
     self.assertEquals(
         encode(),
         b('\x02\x82\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00'))
Beispiel #3
0
 def testEncode6(self):
     # Two positive integers
     der = DerSequence()
     der.append(0x180)
     der.append(0xFF)
     self.assertEquals(encode(), b('0\x08\x02\x02\x01\x80\x02\x02\x00\xff'))
     self.failUnless(der.hasOnlyInts())
     self.failUnless(der.hasOnlyInts(False))
     # Two mixed integers
     der = DerSequence()
     der.append(2)
     der.append(-2)
     self.assertEquals(encode(), b('0\x06\x02\x01\x02\x02\x01\xFE'))
     self.assertEquals(der.hasInts(), 1)
     self.assertEquals(der.hasInts(False), 2)
     self.failIf(der.hasOnlyInts())
     self.failUnless(der.hasOnlyInts(False))
     #
     der.append(0x01)
     der[1:] = [9, 8]
     self.assertEquals(len(der), 3)
     self.assertEqual(der[1:], [9, 8])
     self.assertEqual(der[1:-1], [9])
     self.assertEquals(encode(),
                       b('0\x09\x02\x01\x02\x02\x01\x09\x02\x01\x08'))
Beispiel #4
0
 def testEncode1(self):
     der = DerObjectId('1.2.840.113549.1.1.1')
     self.assertEquals(encode(),
                       b('\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01'))
     #
     der = DerObjectId()
     der.value = '1.2.840.113549.1.1.1'
     self.assertEquals(encode(),
                       b('\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01'))
Beispiel #5
0
 def testObjEncode4(self):
     # Implicit tags (constructed)
     der = DerObject(0x10, implicit=1, constructed=True)
     der.payload = b('ppll')
     self.assertEquals(encode(), b('\xa1\x04ppll'))
     # Implicit tags (primitive)
     der = DerObject(0x02, implicit=0x1E, constructed=False)
     der.payload = b('ppll')
     self.assertEquals(encode(), b('\x9E\x04ppll'))
Beispiel #6
0
 def testEncode2(self):
     # Two integers
     der = DerSetOf()
     der.add(0x180)
     der.add(0xFF)
     self.assertEquals(encode(), b('1\x08\x02\x02\x00\xff\x02\x02\x01\x80'))
     # Initialize with integers
     der = DerSetOf([0x180, 0xFF])
     self.assertEquals(encode(), b('1\x08\x02\x02\x00\xff\x02\x02\x01\x80'))
Beispiel #7
0
 def testEncode1(self):
     # Empty set
     der = DerSetOf()
     self.assertEquals(encode(), b('1\x00'))
     # One single-byte integer (zero)
     der.add(0)
     self.assertEquals(encode(), b('1\x03\x02\x01\x00'))
     # Invariant
     self.assertEquals(encode(), b('1\x03\x02\x01\x00'))
Beispiel #8
0
 def testEncode3(self):
     # Negative integers
     # Value -1
     der = DerInteger(-1)
     self.assertEquals(encode(), b('\x02\x01\xFF'))
     # Value -128
     der = DerInteger(-128)
     self.assertEquals(encode(), b('\x02\x01\x80'))
     # Value
     der = DerInteger(-87873)
     self.assertEquals(encode(), b('\x02\x03\xFE\xA8\xBF'))
Beispiel #9
0
 def testEncode1(self):
     # Single-byte integers
     # Value 0
     der = DerInteger(0)
     self.assertEquals(encode(), b('\x02\x01\x00'))
     # Value 1
     der = DerInteger(1)
     self.assertEquals(encode(), b('\x02\x01\x01'))
     # Value 127
     der = DerInteger(127)
     self.assertEquals(encode(), b('\x02\x01\x7F'))
Beispiel #10
0
 def testEncode1(self):
     # Empty sequence
     der = DerBitString()
     self.assertEquals(encode(), b('\x03\x01\x00'))
     # Small payload
     der = DerBitString(b('\x01\x02'))
     self.assertEquals(encode(), b('\x03\x03\x00\x01\x02'))
     # Small payload
     der = DerBitString()
     der.value = b('\x01\x02')
     self.assertEquals(encode(), b('\x03\x03\x00\x01\x02'))
Beispiel #11
0
    def test_expected_only_integers(self):

        der_bin1 = encode()
        der_bin2 = encode()

        DerSequence().decode(der_bin1, only_ints_expected=True)
        DerSequence().decode(der_bin1, only_ints_expected=False)
        DerSequence().decode(der_bin2, only_ints_expected=False)
        self.assertRaises(ValueError,
                          DerSequence().decode,
                          der_bin2,
                          only_ints_expected=True)
Beispiel #12
0
 def testEncode1(self):
     # Empty sequence
     der = DerSequence()
     self.assertEquals(encode(), b('0\x00'))
     self.failIf(der.hasOnlyInts())
     # One single-byte integer (zero)
     der.append(0)
     self.assertEquals(encode(), b('0\x03\x02\x01\x00'))
     self.assertEquals(der.hasInts(), 1)
     self.assertEquals(der.hasInts(False), 1)
     self.failUnless(der.hasOnlyInts())
     self.failUnless(der.hasOnlyInts(False))
     # Invariant
     self.assertEquals(encode(), b('0\x03\x02\x01\x00'))
Beispiel #13
0
 def testEncode2(self):
     # Indexing
     der = DerSequence()
     der.append(0)
     der[0] = 1
     self.assertEquals(len(der), 1)
     self.assertEquals(der[0], 1)
     self.assertEquals(der[-1], 1)
     self.assertEquals(encode(), b('0\x03\x02\x01\x01'))
     #
     der[:] = [1]
     self.assertEquals(len(der), 1)
     self.assertEquals(der[0], 1)
     self.assertEquals(encode(), b('0\x03\x02\x01\x01'))
Beispiel #14
0
    def _export_private_der(self, include_ec_params=True):

        assert self.has_private()

        # ECPrivateKey ::= SEQUENCE {
        #           version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
        #           privateKey     OCTET STRING,
        #           parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
        #           publicKey  [1] BIT STRING OPTIONAL
        #    }

        # Public key - uncompressed form
        modulus_bytes = self.pointQ.size_in_bytes()
        public_key = (b'\x04' + self.pointQ.x.to_bytes(modulus_bytes) +
                      self.pointQ.y.to_bytes(modulus_bytes))

        seq = [
            1,
            DerOctetString(self.d.to_bytes(modulus_bytes)),
            DerObjectId(self._curve.oid, explicit=0),
            DerBitString(public_key, explicit=1)
        ]

        if not include_ec_params:
            del seq[2]

        return encode()
Beispiel #15
0
 def testEncode4(self):
     # One very long integer
     der = DerSequence()
     der.append(2**2048)
     self.assertEquals(
         encode(),
         b('0\x82\x01\x05') +
         b('\x02\x82\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') +
         b('\x00\x00\x00\x00\x00\x00\x00\x00\x00'))
Beispiel #16
0
 def testObjEncode1(self):
     # No payload
     der = DerObject(b('\x02'))
     self.assertEquals(encode(), b('\x02\x00'))
     # Small payload (primitive)
     der.payload = b('\x45')
     self.assertEquals(encode(), b('\x02\x01\x45'))
     # Invariant
     self.assertEquals(encode(), b('\x02\x01\x45'))
     # Initialize with numerical tag
     der = DerObject(0x04)
     der.payload = b('\x45')
     self.assertEquals(encode(), b('\x04\x01\x45'))
     # Initialize with constructed type
     der = DerObject(b('\x10'), constructed=True)
     self.assertEquals(encode(), b('\x30\x00'))
Beispiel #17
0
 def testEncode7(self):
     # One integer and another type (already encoded)
     der = DerSequence()
     der.append(0x180)
     der.append(b('0\x03\x02\x01\x05'))
     self.assertEquals(encode(),
                       b('0\x09\x02\x02\x01\x800\x03\x02\x01\x05'))
     self.failIf(der.hasOnlyInts())
Beispiel #18
0
 def testEncode8(self):
     # One integer and another type (yet to encode)
     der = DerSequence()
     der.append(0x180)
     der.append(DerSequence([5]))
     self.assertEquals(encode(),
                       b('0\x09\x02\x02\x01\x800\x03\x02\x01\x05'))
     self.failIf(der.hasOnlyInts())
Beispiel #19
0
def _generate_cache_key(request, method, headerlist, key_prefix):
    """Return a cache key from the headers given in the header list."""
    ctx = hashlib.md5()
    for header in headerlist:
        value = request.META
        if value is not None:
            ctx.update(value.encode())
    url = hashlib.md5(encode('ascii'))
    cache_key = 'views.decorators.cache.cache_page.%s.%s.%s.%s' % (
        key_prefix, method, url.hexdigest(), ctx.hexdigest())
    return _i18n_cache_key_suffix(request, cache_key)
Beispiel #20
0
    def test_expected_nr_elements(self):
        der_bin = encode()

        DerSequence().decode(der_bin, nr_elements=3)
        DerSequence().decode(der_bin, nr_elements=(2, 3))
        self.assertRaises(ValueError,
                          DerSequence().decode,
                          der_bin,
                          nr_elements=1)
        self.assertRaises(ValueError,
                          DerSequence().decode,
                          der_bin,
                          nr_elements=(4, 5))
Beispiel #21
0
    def sign(self, msg_hash):
        """Produce the DSA/ECDSA signature of a message.

        :parameter msg_hash:
            The hash that was carried out over the message.
            The object belongs to the :mod:`Crypto.Hash` package.

            Under mode *'fips-186-3'*, the hash must be a FIPS
            approved secure hash (SHA-1 or a member of the SHA-2 family),
            of cryptographic strength appropriate for the DSA key.
            For instance, a 3072/256 DSA key can only be used
            in combination with SHA-512.
        :type msg_hash: hash object

        :return: The signature as a *byte string*
        :raise ValueError: if the hash algorithm is incompatible to the (EC)DSA key
        :raise TypeError: if the (EC)DSA key has no private half
        """

        if not self._valid_hash(msg_hash):
            raise ValueError("Hash is not sufficiently strong")

        # Generate the nonce k (critical!)
        nonce = self._compute_nonce(msg_hash)

        # Perform signature using the raw API
        z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes])
        sig_pair = self._key._sign(z, nonce)

        # Encode the signature into a single byte string
        if self._encoding == 'binary':
            output = b"".join([long_to_bytes(x, self._order_bytes)
                                 for x in sig_pair])
        else:
            # Dss-sig  ::=  SEQUENCE  {
            #               r       OCTET STRING,
            #               s       OCTET STRING
            # }
            output = encode()

        return output
Beispiel #22
0
    def export_key(self,
                   format='PEM',
                   passphrase=None,
                   pkcs=1,
                   protection=None,
                   randfunc=None):
        """Export this RSA key.

        Args:
          format (string):
            The format to use for wrapping the key:

            - *'PEM'*. (*Default*) Text encoding, done according to `RFC1421`_/`RFC1423`_.
            - *'DER'*. Binary encoding.
            - *'OpenSSH'*. Textual encoding, done according to OpenSSH specification.
              Only suitable for public keys (not private keys).

          passphrase (string):
            (*For private keys only*) The pass phrase used for protecting the output.

          pkcs (integer):
            (*For private keys only*) The ASN.1 structure to use for
            serializing the key. Note that even in case of PEM
            encoding, there is an inner ASN.1 DER structure.

            With ``pkcs=1`` (*default*), the private key is encoded in a
            simple `PKCS#1`_ structure (``RSAPrivateKey``).

            With ``pkcs=8``, the private key is encoded in a `PKCS#8`_ structure
            (``PrivateKeyInfo``).

            .. note::
                This parameter is ignored for a public key.
                For DER and PEM, an ASN.1 DER ``SubjectPublicKeyInfo``
                structure is always used.

          protection (string):
            (*For private keys only*)
            The encryption scheme to use for protecting the private key.

            If ``None`` (default), the behavior depends on :attr:`format`:

            - For *'DER'*, the *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC*
              scheme is used. The following operations are performed:

                1. A 16 byte Triple DES key is derived from the passphrase
                   using :func:`Crypto.Protocol.KDF.PBKDF2` with 8 bytes salt,
                   and 1 000 iterations of :mod:`Crypto.Hash.HMAC`.
                2. The private key is encrypted using CBC.
                3. The encrypted key is encoded according to PKCS#8.

            - For *'PEM'*, the obsolete PEM encryption scheme is used.
              It is based on MD5 for key derivation, and Triple DES for encryption.

            Specifying a value for :attr:`protection` is only meaningful for PKCS#8
            (that is, ``pkcs=8``) and only if a pass phrase is present too.

            The supported schemes for PKCS#8 are listed in the
            :mod:`Crypto.IO.PKCS8` module (see :attr:`wrap_algo` parameter).

          randfunc (callable):
            A function that provides random bytes. Only used for PEM encoding.
            The default is :func:`Crypto.Random.get_random_bytes`.

        Returns:
          byte string: the encoded key

        Raises:
          ValueError:when the format is unknown or when you try to encrypt a private
            key with *DER* format and PKCS#1.

        .. warning::
            If you don't provide a pass phrase, the private key will be
            exported in the clear!

        .. _RFC1421:    http://www.ietf.org/rfc/rfc1421.txt
        .. _RFC1423:    http://www.ietf.org/rfc/rfc1423.txt
        .. _`PKCS#1`:   http://www.ietf.org/rfc/rfc3447.txt
        .. _`PKCS#8`:   http://www.ietf.org/rfc/rfc5208.txt
        """

        if passphrase is not None:
            passphrase = tobytes(passphrase)

        if randfunc is None:
            randfunc = Random.get_random_bytes

        if format == 'OpenSSH':
            e_bytes, n_bytes = [x.to_bytes() for x in (self._e, self._n)]
            if bord(e_bytes[0]) & 0x80:
                e_bytes = b'\x00' + e_bytes
            if bord(n_bytes[0]) & 0x80:
                n_bytes = b'\x00' + n_bytes
            keyparts = [b'ssh-rsa', e_bytes, n_bytes]
            keystring = b''.join(
                [struct.pack(">I", len(kp)) + kp for kp in keyparts])
            return b'ssh-rsa ' + binascii.b2a_base64(keystring)[:-1]

        # DER format is always used, even in case of PEM, which simply
        # encodes it into BASE64.
        if self.has_private():
            binary_key = encode()
            if pkcs == 1:
                key_type = 'RSA PRIVATE KEY'
                if format == 'DER' and passphrase:
                    raise ValueError("PKCS#1 private key cannot be encrypted")
            else:  # PKCS#8
                if format == 'PEM' and protection is None:
                    key_type = 'PRIVATE KEY'
                    binary_key = PKCS8.wrap(binary_key, oid, None)
                else:
                    key_type = 'ENCRYPTED PRIVATE KEY'
                    if not protection:
                        protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'
                    binary_key = PKCS8.wrap(binary_key, oid, passphrase,
                                            protection)
                    passphrase = None
        else:
            key_type = "PUBLIC KEY"
            binary_key = _create_subject_public_key_info(
                oid, DerSequence([self.n, self.e]))

        if format == 'DER':
            return binary_key
        if format == 'PEM':
            pem_str = PEM.encode(binary_key, key_type, passphrase, randfunc)
            return tobytes(pem_str)

        raise ValueError(
            "Unknown key format '%s'. Cannot export the RSA key." % format)
Beispiel #23
0
 def testInit1(self):
     der = DerBitString(b("\xFF"))
     self.assertEquals(encode(), b('\x03\x02\x00\xFF'))
Beispiel #24
0
 def testObjEncode2(self):
     # Initialize with payload
     der = DerObject(0x03, b('\x12\x12'))
     self.assertEquals(encode(), b('\x03\x02\x12\x12'))
Beispiel #25
0
 def testObjEncode5(self):
     # Encode type with explicit tag
     der = DerObject(0x10, explicit=5)
     der.payload = b("xxll")
     self.assertEqual(encode(), b("\xa5\x06\x10\x04xxll"))
Beispiel #26
0
 def testInit1(self):
     der = DerSetOf([DerInteger(1), DerInteger(2)])
     self.assertEquals(encode(), b('1\x06\x02\x01\x01\x02\x01\x02'))
Beispiel #27
0
 def testObjEncode3(self):
     # Long payload
     der = DerObject(b('\x10'))
     der.payload = b("0") * 128
     self.assertEquals(encode(), b('\x10\x81\x80' + "0" * 128))
Beispiel #28
0
 def testEncode4(self):
     # Only non integers
     der = DerSetOf()
     der.add(b('\x01\x00'))
     der.add(b('\x01\x01\x01'))
     self.assertEquals(encode(), b('1\x05\x01\x00\x01\x01\x01'))
Beispiel #29
0
def _generate_cache_header_key(key_prefix, request):
    """Return a cache key for the header cache."""
    url = hashlib.md5(encode('ascii'))
    cache_key = 'views.decorators.cache.cache_header.%s.%s' % (key_prefix,
                                                               url.hexdigest())
    return _i18n_cache_key_suffix(request, cache_key)
Beispiel #30
0
 def testInit2(self):
     der = DerBitString(DerInteger(1))
     self.assertEquals(encode(), b('\x03\x04\x00\x02\x01\x01'))