예제 #1
0
def CMS(data, format="PEM"):
    """
    Factory function to create CMS objects from received messages.
    
    Parses CMS data and returns either SignedData or EnvelopedData
    object. format argument can be either "PEM" or "DER".

    It determines object type from the contents of received CMS
    structure.
    """
    bio = Membio(data)
    if format == "PEM":
        ptr = libcrypto.PEM_read_bio_CMS(bio.bio, None, None, None)
    else:
        ptr = libcrypto.d2i_CMS_bio(bio.bio, None)
    if ptr is None:
        raise CMSError("Error parsing CMS data")
    typeoid = Oid(libcrypto.OBJ_obj2nid(libcrypto.CMS_get0_type(ptr)))
    if typeoid.shortname() == "pkcs7-signedData":
        return SignedData(ptr)
    elif typeoid.shortname() == "pkcs7-envelopedData":
        return EnvelopedData(ptr)
    elif typeoid.shortname() == "pkcs7-encryptedData":
        return EncryptedData(ptr)
    else:
        raise NotImplementedError("cannot handle "+typeoid.shortname())
예제 #2
0
def CMS(data, format="PEM"):
    """
    Factory function to create CMS objects from received messages.
    
    Parses CMS data and returns either SignedData or EnvelopedData
    object. format argument can be either "PEM" or "DER".

    It determines object type from the contents of received CMS
    structure.
    """
    bio = Membio(data)
    if format == "PEM":
        ptr = libcrypto.PEM_read_bio_CMS(bio.bio, None, None, None)
    else:
        ptr = libcrypto.d2i_CMS_bio(bio.bio, None)
    if ptr is None:
        raise CMSError("Error parsing CMS data")
    typeoid = Oid(libcrypto.OBJ_obj2nid(libcrypto.CMS_get0_type(ptr)))
    if typeoid.shortname() == "pkcs7-signedData":
        return SignedData(ptr)
    elif typeoid.shortname() == "pkcs7-envelopedData":
        return EnvelopedData(ptr)
    elif typeoid.shortname() == "pkcs7-encryptedData":
        return EncryptedData(ptr)
    else:
        raise NotImplementedError("cannot handle " + typeoid.shortname())
예제 #3
0
	def test_cn(self):
		o=Oid("2.5.4.3")
		self.assertEqual(repr(o),"Oid('2.5.4.3')")
		self.assertEqual(o.dotted(),"2.5.4.3")
		self.assertEqual(str(o),"2.5.4.3")
		self.assertEqual(o.shortname(),"CN")
		self.assertEqual(o.longname(),"commonName")
예제 #4
0
 def test_cn(self):
     o=Oid("2.5.4.3")
     self.assertEqual(repr(o),"Oid('2.5.4.3')")
     self.assertEqual(o.dotted(),"2.5.4.3")
     self.assertEqual(str(o),"2.5.4.3")
     self.assertEqual(o.shortname(),"CN")
     self.assertEqual(o.longname(),"commonName")
예제 #5
0
파일: cms.py 프로젝트: est/ctypescrypto
def CMS(data, format="PEM"):
    """
    Parses CMS data and returns either SignedData or EnvelopedData
    object
    """
    bio = Membio(data)
    if format == "PEM":
        ptr = libcrypto.PEM_read_bio_CMS(bio.bio, None, None, None)
    else:
        ptr = libcrypto.d2i_CMS_bio(bio.bio, None)
    typeoid = Oid(libcrypto.OBJ_obj2nid(libcrypto.CMS_get0_type(ptr)))
    if typeoid.shortname() == "pkcs7-signedData":
        return SignedData(ptr)
    elif typeoid.shortname() == "pkcs7-envelopedData":
        return EnvelopedData(ptr)
    elif typeoid.shortname() == "pkcs7-encryptedData":
        return EncryptedData(ptr)
    else:
        raise NotImplementedError("cannot handle "+typeoid.shortname())
예제 #6
0
def CMS(data, format="PEM"):
    """
    Parses CMS data and returns either SignedData or EnvelopedData
    object
    """
    bio = Membio(data)
    if format == "PEM":
        ptr = libcrypto.PEM_read_bio_CMS(bio.bio, None, None, None)
    else:
        ptr = libcrypto.d2i_CMS_bio(bio.bio, None)
    if ptr is None:
        raise CMSError("Error parsing CMS data")
    typeoid = Oid(libcrypto.OBJ_obj2nid(libcrypto.CMS_get0_type(ptr)))
    if typeoid.shortname() == "pkcs7-signedData":
        return SignedData(ptr)
    elif typeoid.shortname() == "pkcs7-envelopedData":
        return EnvelopedData(ptr)
    elif typeoid.shortname() == "pkcs7-encryptedData":
        return EncryptedData(ptr)
    else:
        raise NotImplementedError("cannot handle " + typeoid.shortname())
예제 #7
0
	def test_fromunicode(self):
		o=Oid(u'commonName')
		self.assertEqual(o.shortname(),'CN')
예제 #8
0
파일: mac.py 프로젝트: sv99/ctypescrypto
class MAC(Digest):
	"""
		This object represents MAC context. It is quite simular
		to digest algorithm. It is simular to hmac objects provided
		by standard library
	"""
	def __init__(self,algorithm,key,digest=None,**kwargs):
		"""
		Constructor has to obligatory arguments:
			
			@param algorithm - which is name of MAC algorithm i.e 'hmac' or 
					'gost-mac' or equivalent Oid object
			@param key - byte buffer with key.

		Optional parameters are:
			digest - Oid or name of the digest algorithm to use. If none
				specified, OpenSSL will try to derive one from the MAC
				algorithm (or if algorithm is hmac, we'll substititute md5
				for compatibility with standard hmac module

			any other keyword argument is passed to EVP_PKEY_CTX as string
			option.

		"""
		if isinstance(algorithm,str):
			self.algorithm=Oid(algorithm)
		elif isinstance(algorithm,Oid):
			self.algorithm=algorithm
		else:
			raise TypeError("Algorthm must be string or Oid")
		if self.algorithm==Oid('hmac') and digest is None:
				digest='md5'
		self.name=self.algorithm.shortname().lower()
		if digest is not None:
			self.digest_type=DigestType(digest)
			self.name+='-'+self.digest_type.digest_name
			d=self.digest_type.digest
		else:
			self.digest_type=None
			d=None
		self.key=libcrypto.EVP_PKEY_new_mac_key(self.algorithm.nid,None,key,len(key))
		if self.key is None:
			raise DigestError("EVP_PKEY_new_mac_key")
		pctx=c_void_p()
		self.ctx = libcrypto.EVP_MD_CTX_create()
		if self.ctx == 0:
			raise DigestError("Unable to create digest context")
		if libcrypto.EVP_DigestSignInit(self.ctx,pointer(pctx),d,None,self.key) <= 0:
			raise DigestError("Unable to intialize digest context")
		self.digest_finalized=False
		if self.digest_type is None:
			self.digest_type=DigestType(Oid(libcrypto.EVP_MD_type(libcrypto.EVP_MD_CTX_md(self.ctx))))
		for (name,val) in kwargs.items():
			if libcrypto.EVP_PKEY_CTX_ctrl_str(pctx,name,val)<=0:
				raise DigestError("Unable to set mac parameter")
		self.digest_size = self.digest_type.digest_size()
		self.block_size = self.digest_type.block_size()
	def digest(self,data=None):
		"""
		Method digest is redefined to return keyed MAC value instead of
		just digest.
		"""
		if data is not None:
			self.update(data)
		b=create_string_buffer(256)
		size=c_size_t(256)
		if libcrypto.EVP_DigestSignFinal(self.ctx,b,pointer(size))<=0:
			raise DigestError('SignFinal')
		self.digest_finalized=True
		return b.raw[:size.value]
예제 #9
0
파일: mac.py 프로젝트: est/ctypescrypto
class MAC(Digest):
    """
        This object represents MAC context. It is quite simular
        to digest algorithm. It is simular to hmac objects provided
        by standard library
    """
    def __init__(self, algorithm, key, digest=None, **kwargs):
        """
        Constructor has to obligatory arguments:
            
            @param algorithm - which is name of MAC algorithm i.e 'hmac' or 
                    'gost-mac' or equivalent Oid object
            @param key - byte buffer with key.

        Optional parameters are:
            digest - Oid or name of the digest algorithm to use. If none
                specified, OpenSSL will try to derive one from the MAC
                algorithm (or if algorithm is hmac, we'll substititute md5
                for compatibility with standard hmac module

            any other keyword argument is passed to EVP_PKEY_CTX as string
            option.

        """
        if isinstance(algorithm, str):
            self.algorithm = Oid(algorithm)
        elif isinstance(algorithm, Oid):
            self.algorithm = algorithm
        else:
            raise TypeError("Algorthm must be string or Oid")
        if self.algorithm == Oid('hmac') and digest is None:
            digest = 'md5'
        self.name = self.algorithm.shortname().lower()
        if digest is not None:
            self.digest_type = DigestType(digest)
            self.name += '-' + self.digest_type.digest_name
            d = self.digest_type.digest
        else:
            self.digest_type = None
            d = None
        self.key = libcrypto.EVP_PKEY_new_mac_key(self.algorithm.nid, None,
                                                  key, len(key))
        if self.key is None:
            raise DigestError("EVP_PKEY_new_mac_key")
        pctx = c_void_p()
        self.ctx = libcrypto.EVP_MD_CTX_create()
        if self.ctx == 0:
            raise DigestError("Unable to create digest context")
        if libcrypto.EVP_DigestSignInit(self.ctx, pointer(pctx), d, None,
                                        self.key) <= 0:
            raise DigestError("Unable to intialize digest context")
        self.digest_finalized = False
        if self.digest_type is None:
            self.digest_type = DigestType(
                Oid(libcrypto.EVP_MD_type(libcrypto.EVP_MD_CTX_md(self.ctx))))
        for (name, val) in kwargs.items():
            if libcrypto.EVP_PKEY_CTX_ctrl_str(pctx, name, val) <= 0:
                raise DigestError("Unable to set mac parameter")
        self.digest_size = self.digest_type.digest_size
        self.block_size = self.digest_type.block_size

    def digest(self, data=None):
        """
        Method digest is redefined to return keyed MAC value instead of
        just digest.
        """
        if data is not None:
            self.update(data)
        b = create_string_buffer(256)
        size = c_size_t(256)
        if libcrypto.EVP_DigestSignFinal(self.ctx, b, pointer(size)) <= 0:
            raise DigestError('SignFinal')
        self.digest_finalized = True
        return b.raw[:size.value]
예제 #10
0
 def test_fromunicode(self):
     o=Oid(u'commonName')
     self.assertEqual(o.shortname(),'CN')