示例#1
0
def encrypt(input_bio, cert, keyring_source, cypher):
    """
    Encrypts the input data with the public key in the certificate from keyring
    source with selected cypher.

    @type input_bio: M2Crypto.BIO
    @param input_bio: input data to encrypt.
    @type cert:  filepath or M2Crypto.BIO or M2Crypto.X509.X509
    @param cert: the recipient certificate reference from filepath, could be
        from file, from memory or from pkcs11 smartcard, based on
        keyring_soruce input parameter.
    @type keyring_source: str
    @keyword keyring_source: the type of the source for input certificate, used
        to recall the appropriate method for encrypter settings. Ammitted
        values are: file, memory, pkcs11.
    @type cypher: str
    @keyword cypher: the cypher to use for encryption of the data, run
        "openssl enc -help" for supported cyphers, you have to choose a public
        key cypher from availables.
    @rtype: M2Crypto.SMIME.PKCS7
    @return: the PKCS#7 encrypted data in PEM format.
    """
    encrypter = SMIME.SMIME()
    x509 = set_certificate(cert, keyring_source)
    sk = X509.X509_Stack()
    sk.push(x509)
    encrypter.set_x509_stack(sk)
    encrypter.set_cipher(SMIME.Cipher(cypher))
    Rand.load_file('randpool.dat', -1)
    try:
        p7 = encrypter.encrypt(input_bio)
    except SMIME.SMIME_Error, e:
        logging.error('smime error: ' + str(e))
        raise
示例#2
0
文件: SMIME.py 项目: zbo/zbodo
def threadSMIME():
    # Seed the PRNG.
    Rand.load_file('randpool.dat', -1)

    # Instantiate an SMIME object.
    s = SMIME.SMIME()
    # Load target cert to encrypt to.
    x509 = X509.load_cert('recipient.pem')
    sk = X509.X509_Stack()
    sk.push(x509)
    s.set_x509_stack(sk)

    # Set cipher: 3-key triple-DES in CBC mode.
    s.set_cipher(SMIME.Cipher('des_ede3_cbc'))

    # Encrypt the buffer.
    p7 = s.encrypt(buf)

    # Output p7 in mail-friendly format.
    out = BIO.MemoryBuffer()
    out.write('From: [email protected]\n')
    out.write('To: [email protected]\n')
    out.write('Subject: M2Crypto S/MIME testing\n')
    s.write(out, p7)

    print out.read()

    # Save the PRNG's state.
    Rand.save_file('randpool.dat')
示例#3
0
文件: wsaa.py 项目: fiqus/pirra
def sign_tra(tra, cert=CERT, key=PRIVATEKEY):
    from M2Crypto import BIO, Rand, SMIME

    def makebuf(text):
        return BIO.MemoryBuffer(text)

    # Make a MemoryBuffer of the message.
    buf = makebuf(tra.encode())

    # Seed the PRNG.
    Rand.load_file('randpool.dat', -1)

    # Instantiate an SMIME object; set it up; sign the buffer.
    s = SMIME.SMIME()
    s.load_key(key, cert)
    p7 = s.sign(buf)

    out = BIO.MemoryBuffer()
    s.write(out, p7)

    msg = email.message_from_bytes(out.read())
    for part in msg.walk():
        filename = part.get_filename()
        if filename == "smime.p7m":  # es la parte firmada?
            return part.get_payload(decode=False)  # devolver CMS
示例#4
0
    def sign(self):

        # Make a MemoryBuffer of the message.
        buf = makebuf('a sign of our times')

        # Seed the PRNG.
        Rand.load_file(randpool, -1)

        # Instantiate an SMIME object; set it up; sign the buffer.
        s = SMIME.SMIME()
        s.load_key(signer_key, signer_cert)

        p7 = s.sign(buf, SMIME.PKCS7_DETACHED)

        # Recreate buf.
        buf = makebuf('a sign of our times')

        # Output p7 in mail-friendly format.
        out = BIO.MemoryBuffer()
        out.write('From: [email protected]\n')
        out.write('To: [email protected]\n')
        out.write('Subject: M2Crypto S/MIME testing\n')

        s.write(out, p7, buf)

        result = out.read()

        # Save the PRNG's state.
        Rand.save_file(randpool)

        open('smime-m2-sign.txt', 'wt').write(result)
示例#5
0
def main(keylen, hashalg):
    global rsa, dgst     # this exists ONLY for speed testing
    
    Rand.load_file('randpool.dat', -1) 
        
    pvtkeyfilename = 'rsa%dpvtkey.pem' % (keylen)
    pubkeyfilename = 'rsa%dpubkey.pem' % (keylen)  
    
    if makenewkey:
        print '  making and saving a new key'
        rsa = RSA.gen_key(keylen, exponent)
        rsa.save_key(pvtkeyfilename, None )  # no pswd callback
        rsa.save_pub_key(pubkeyfilename)
    else:
        print '  loading an existing key'
        rsa = RSA.load_key(pvtkeyfilename)
    print '  rsa key length:', len(rsa)
    
    if not rsa.check_key():
        raise 'key is not initialised'

    # since we are testing signing and verification, let's not 
    # be fussy about the digest.  Just make one.
    md = EVP.MessageDigest(hashalg)
    md.update('can you spell subliminal channel?')
    dgst = md.digest()
    print '  hash algorithm: %s' % hashalg
    if showdigest:
        print '  %s digest: \n%s' % (hashalg, base64.encodestring(dgst))
    
    test(rsa, dgst)
#    test_asn1(rsa, dgst)
    test_speed(rsa, dgst)
    Rand.save_file('randpool.dat')
示例#6
0
def encrypt(input_bio, cert, keyring_source, cypher):
    """
    Encrypts the input data with the public key in the certificate from keyring
    source with selected cypher.

    @type input_bio: M2Crypto.BIO
    @param input_bio: input data to encrypt.
    @type cert:  filepath or M2Crypto.BIO or M2Crypto.X509.X509
    @param cert: the recipient certificate reference from filepath, could be
        from file, from memory or from pkcs11 smartcard, based on
        keyring_soruce input parameter.
    @type keyring_source: str
    @keyword keyring_source: the type of the source for input certificate, used
        to recall the appropriate method for encrypter settings. Ammitted
        values are: file, memory, pkcs11.
    @type cypher: str
    @keyword cypher: the cypher to use for encryption of the data, run
        "openssl enc -help" for supported cyphers, you have to choose a public
        key cypher from availables.
    @rtype: M2Crypto.SMIME.PKCS7
    @return: the PKCS#7 encrypted data in PEM format.
    """
    encrypter = SMIME.SMIME()
    x509 = set_certificate(cert, keyring_source)
    sk = X509.X509_Stack()
    sk.push(x509)
    encrypter.set_x509_stack(sk)
    encrypter.set_cipher(SMIME.Cipher(cypher))
    Rand.load_file('randpool.dat', -1)
    try:
        p7 = encrypter.encrypt(input_bio)
    except SMIME.SMIME_Error, e:
        logging.error('smime error: ' + str(e))
        raise
示例#7
0
def main(keylen, hashalg):
    global rsa, dgst  # this exists ONLY for speed testing

    Rand.load_file('randpool.dat', -1)

    pvtkeyfilename = 'rsa%dpvtkey.pem' % (keylen)
    pubkeyfilename = 'rsa%dpubkey.pem' % (keylen)

    if makenewkey:
        print '  making and saving a new key'
        rsa = RSA.gen_key(keylen, exponent)
        rsa.save_key(pvtkeyfilename, None)  # no pswd callback
        rsa.save_pub_key(pubkeyfilename)
    else:
        print '  loading an existing key'
        rsa = RSA.load_key(pvtkeyfilename)
    print '  rsa key length:', len(rsa)

    if not rsa.check_key():
        raise 'key is not initialised'

    # since we are testing signing and verification, let's not
    # be fussy about the digest.  Just make one.
    md = EVP.MessageDigest(hashalg)
    md.update('can you spell subliminal channel?')
    dgst = md.digest()
    print '  hash algorithm: %s' % hashalg
    if showdigest:
        print '  %s digest: \n%s' % (hashalg, base64.encodestring(dgst))

    test(rsa, dgst)
    #    test_asn1(rsa, dgst)
    test_speed(rsa, dgst)
    Rand.save_file('randpool.dat')
示例#8
0
 def test_load_save(self):
     try:
         os.remove('tests/randpool.dat')
     except OSError:
         pass
     self.assertIn(Rand.load_file('tests/randpool.dat', -1), [0, -1])
     self.assertEqual(Rand.save_file('tests/randpool.dat'), 1024)
     self.assertEqual(Rand.load_file('tests/randpool.dat', -1), 1024)
示例#9
0
 def test_load_save(self):
     try:
         os.remove('tests/randpool.dat')
     except OSError:
         pass
     assert Rand.load_file('tests/randpool.dat', -1) == 0
     assert Rand.save_file('tests/randpool.dat') == 1024
     assert Rand.load_file('tests/randpool.dat', -1) == 1024
示例#10
0
 def test_load_save(self):
     try:
         os.remove("test/randpool.dat")
     except OSError:
         pass
     assert Rand.load_file("test/randpool.dat", -1) == 0
     assert Rand.save_file("test/randpool.dat") == 1024
     assert Rand.load_file("test/randpool.dat", -1) == 1024
示例#11
0
 def test_load_save(self):
     try:
         os.remove('tests/randpool.dat')
     except OSError:
         pass
     self.assertIn(Rand.load_file('tests/randpool.dat', -1), [0, -1])
     self.assertEqual(Rand.save_file('tests/randpool.dat'), 1024)
     self.assertEqual(Rand.load_file('tests/randpool.dat', -1), 1024)
示例#12
0
def get_ssl_context():
    from M2Crypto import Rand
    Rand.load_file('randpool.dat', -1)
    ctx = init_context('sslv23', 'server.pem', 'ca.pem',
        SSL.verify_none)
        #SSL.verify_peer | SSL.verify_fail_if_no_peer_cert)
    ctx.set_tmp_dh('dh1024.pem')
    Rand.save_file('randpool.dat')
    return ctx
示例#13
0
def startup(profileDir):
    """
    Initialize the cryptographic services before doing any other
    cryptographic operations.
    
    @param profileDir: The profile directory. Additional entropy will be loaded
                       from a file in this directory. It is not a fatal error
                       if the file does not exist.
    """
    m2threading.init()
    Rand.load_file(_randpoolPath(profileDir), -1)
示例#14
0
def startup(profileDir):
    """
    Initialize the cryptographic services before doing any other
    cryptographic operations.
    
    @param profileDir: The profile directory. Additional entropy will be loaded
                       from a file in this directory. It is not a fatal error
                       if the file does not exist.
    """
    m2threading.init()
    Rand.load_file(_randpoolPath(profileDir), -1)
示例#15
0
文件: test.py 项目: ttggaa/snippets
def sign(cert_file, key_file, message, flags):
    """
    Returns a der encoded signed message
    """
    signer = SMIME.SMIME()
    signer.load_key(key_file, cert_file)
    Rand.load_file('randpool.dat', -1)
    p7 = signer.sign(BIO_from_buffer(message), flags=flags)
    Rand.save_file('randpool.dat')
    signed_message = BIO_from_buffer()
    p7.write_der(signed_message)
    return signed_message.read()
示例#16
0
 def __init__(self, handler, host='localhost', port=8000):
        threading.init()
        Rand.load_file('../randpool.dat', -1)
        ctx=echod_lib.init_context('sslv3','server.pem', 'ca.pem',
                                   SSL.verify_peer)
        ctx.set_tmp_dh('dh1024.pem')
        config = Config()
        server = TCPServer.__connection(self, host, port)
        while 1:
               server.OpenConnection()
               server.HandleConnection(handler,config.config,ctx)
        server.CloseConnection()
        Rand.save_file('../randpool.dat')
        threading.cleanup()
示例#17
0
    def set_message(self, message, certificates=[]):
        """Sign and encrypt the email and prepare it to send"""
        self.message = message
        # Seed the PRNG.
        Rand.load_file('randpool.dat', -1)
    
        smime = SMIME.SMIME()
        
        # put message with attachments into into SSL" I/O buffer
        msg_str = self.message.msg.as_string()
        msg_bio = BIO.MemoryBuffer(bytes(msg_str, 'utf-8'))
        
        if self.sign:
            smime.load_key(self.key, self.cert)
            p7 = smime.sign(msg_bio, SMIME.PKCS7_DETACHED)
            # Recreate the message because sign function has consumed it
            msg_bio = BIO.MemoryBuffer(bytes(msg_str, 'utf-8')) 

        if self.encrypt:
            sk = X509.X509_Stack()
            for cert in certificates:
                sk.push(X509.load_cert(cert))
            smime.set_x509_stack(sk)
            smime.set_cipher(SMIME.Cipher(self.cipher))
            tmp_bio = BIO.MemoryBuffer()
            if self.sign:
                smime.write(tmp_bio, p7, msg_bio)
            else:
                tmp_bio.write(msg_str)
            p7 = smime.encrypt(tmp_bio)

        out = BIO.MemoryBuffer()
        out.write('From: %s\r\n' % self.message.sender)
        out.write('To: %s\r\n' % ", ".join(self.message.recipients))
        out.write('Subject: %s\r\n' % self.message.subject) 
        
        if self.encrypt:
            smime.write(out, p7)
        elif self.sign:
            smime.write(out, p7, msg_bio)
        else:
            out.write(msg_str)
                
        out.close()
        
        # Save the PRNG's state.
        Rand.save_file('randpool.dat')
        
        return out.read().decode("utf-8")
示例#18
0
       def start(self, handler, ssl, host, port,config):
              if ssl:
                     Rand.load_file('ssl/randpool.dat', -1)
                     ctx=echod_lib.init_context('sslv3','ssl/server.pem', 'ssl/ca.pem',
                                                SSL.verify_none)
                     ctx.set_tmp_dh('ssl/dh1024.pem')
                     if port==8000: port += 1
              else:
                     ctx = None

              server = self.__connection(host, port)
              while 1:
                     server.OpenConnection()
                     server.HandleConnection(handler,config.config,ctx)
              server.CloseConnection()
示例#19
0
    def sign_and_encrypt(self):

        # Make a MemoryBuffer of the message.
        buf = makebuf('a sign of our times')

        # Seed the PRNG.
        Rand.load_file(randpool, -1)

        # Instantiate an SMIME object.
        s = SMIME.SMIME()

        # Load signer's key and cert. Sign the buffer.
        s.load_key(signer_key, signer_cert)
        p7 = s.sign(buf, SMIME.PKCS7_DETACHED)

        # Load target cert to encrypt the signed message to.
        x509 = X509.load_cert(recipient_cert)
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)

        # Set cipher: 3-key triple-DES in CBC mode.
        s.set_cipher(SMIME.Cipher('des_ede3_cbc'))

        # Create a temporary buffer.
        tmp = BIO.MemoryBuffer()

        # Write the signed message into the temporary buffer.
        s.write(tmp, p7, buf)

        # Encrypt the temporary buffer.
        p7 = s.encrypt(tmp)

        # Output p7 in mail-friendly format.
        out = BIO.MemoryBuffer()
        out.write('From: [email protected]\n')
        out.write('To: [email protected]\n')
        out.write('Subject: M2Crypto S/MIME testing\n')
        s.write(out, p7)

        result = out.read()

        # Save the PRNG's state.
        Rand.save_file(randpool)

        open('smime-m2-sign-encrypt.txt', 'wt').write(result)
def main(curve, hashalg):
    global ec, dgst  # this exists ONLY for speed testing

    Rand.load_file('randpool.dat', -1)

    if curve in curves2:
        curve = 'X9_62_' + curve
    ec_curve = eval('EC.NID_%s' % curve)

    pvtkeyfilename = '%spvtkey.pem' % (curve)
    pubkeyfilename = '%spubkey.pem' % (curve)

    if makenewkey:
        print '  making and saving a new key'
        ec = EC.gen_params(ec_curve)
        ec.gen_key()
        ec.save_key(pvtkeyfilename, None)
        ec.save_pub_key(pubkeyfilename)
    else:
        print '  loading an existing key'
        ec = EC.load_key(pvtkeyfilename)
    print '  ecdsa key length:', len(ec)
    print '  curve: %s' % curve

    if not ec.check_key():
        raise 'key is not initialised'

    if showpubkey:
        ec_pub = ec.pub()
        pub_der = ec_pub.get_der()
        pub_pem = base64.encodestring(pub_der)
        print '  PEM public key is: \n', pub_pem

    # since we are testing signing and verification, let's not
    # be fussy about the digest.  Just make one.
    md = EVP.MessageDigest(hashalg)
    md.update('can you spell subliminal channel?')
    dgst = md.digest()
    print '  hash algorithm: %s' % hashalg
    if showdigest:
        print '  %s digest: \n%s' % (base64.encodestring(dgst))

    test(ec, dgst)
    #    test_asn1(ec, dgst)
    test_speed(ec, dgst)
    Rand.save_file('randpool.dat')
示例#21
0
def main(curve, hashalg):
    global ec, dgst     # this exists ONLY for speed testing
    
    Rand.load_file('randpool.dat', -1) 
    
    if curve in curves2:
        curve = 'X9_62_' + curve
    ec_curve = eval('EC.NID_%s' % curve)
    
    pvtkeyfilename = '%spvtkey.pem' % (curve)
    pubkeyfilename = '%spubkey.pem' % (curve)  
    
    if makenewkey:
        print '  making and saving a new key'
        ec = EC.gen_params(ec_curve)
        ec.gen_key()
        ec.save_key(pvtkeyfilename, None )
        ec.save_pub_key(pubkeyfilename)
    else:
        print '  loading an existing key'
        ec=EC.load_key(pvtkeyfilename)
    print '  ecdsa key length:', len(ec)
    print '  curve: %s' % curve
    
    if not ec.check_key():
        raise 'key is not initialised'
        
    if showpubkey:
        ec_pub = ec.pub()
        pub_der = ec_pub.get_der()
        pub_pem = base64.encodestring(pub_der)
        print '  PEM public key is: \n',pub_pem

    # since we are testing signing and verification, let's not 
    # be fussy about the digest.  Just make one.
    md = EVP.MessageDigest(hashalg)
    md.update('can you spell subliminal channel?')
    dgst = md.digest()
    print '  hash algorithm: %s' % hashalg
    if showdigest:
        print '  %s digest: \n%s' % (base64.encodestring(dgst))
    
    test(ec, dgst)
#    test_asn1(ec, dgst)
    test_speed(ec, dgst)
    Rand.save_file('randpool.dat')
示例#22
0
def runall(report_leaks=0):
    report_leaks = report_leaks
    
    if report_leaks:
        import gc
        gc.enable()
        gc.set_debug(gc.DEBUG_LEAK & ~gc.DEBUG_SAVEALL)
    
    import os, unittest
    from M2Crypto import Rand
    
    try:
        Rand.load_file('tests/randpool.dat', -1) 
        unittest.TextTestRunner(verbosity=2).run(suite())
        Rand.save_file('tests/randpool.dat')
    finally:
        if os.name == 'posix':
            from test_ssl import zap_servers
            zap_servers()

    if report_leaks:
        dump_garbage()
示例#23
0
def runall(report_leaks=0):
    report_leaks = report_leaks

    if report_leaks:
        import gc
        gc.enable()
        gc.set_debug(gc.DEBUG_LEAK & ~gc.DEBUG_SAVEALL)

    import os, unittest
    from M2Crypto import Rand

    try:
        Rand.load_file('test/randpool.dat', -1)
        unittest.TextTestRunner(verbosity=2).run(suite())
        Rand.save_file('test/randpool.dat')
    finally:
        if os.name == 'posix':
            from test_ssl import zap_servers
            zap_servers()

    if report_leaks:
        dump_garbage()
示例#24
0
def sign(input_bio, private_key, cert, keyring_source, type):
    """
    Signs the input data with the private key and the certificate from keyring
    source.

    @type input_bio: M2Crypto.BIO
    @param input_bio: input data to sign.
    @type private_key: filepath or M2Crypto.BIO or M2Crypto.EVP.PKey
    @param private_key: sender private key reference, could be from file,
        from memory or from pkcs11 smartcard, based on keyring_soruce input
        parameter.
    @type cert: filepath or M2Crypto.BIO or M2Crypto.X509.X509
    @param cert: sender certificate, could be from filepath, from memory or
        from pkcs11 smartcard, based on keyring_soruce input parameter.
    @type keyring_source: str
    @keyword keyring_source: the type of the source for input certificate, used
        to recall the appropriate method for signer settings. Ammitted
        values are: file, memory, pkcs11.
    @type type: str
    @keyword type: specifies the type of output PKCS#7 data: PEM or DER
    @rtype: M2Crypto.SMIME.PKCS7
    @return: the PKCS#7 signed data in PEM or DER format.
    """
    signer = SMIME.SMIME()
    set_keyring(signer, private_key, cert, keyring_source)
    Rand.load_file('randpool.dat', -1)
    try:
        if type == 'PEM':
            p7 = signer.sign(input_bio, flags=SMIME.PKCS7_DETACHED)
        elif type == 'DER':
            p7 = signer.sign(input_bio)
        else:
            logging.error('pkcs7 type error: unknown type')
            raise BadPKCS7Type('unknown type: ' + type +
                               '; possible values: PEM, DER')
    except SMIME.SMIME_Error, e:
        logging.error('smime error: ' + str(e))
        raise
示例#25
0
def sign(input_bio, private_key, cert, keyring_source, type):
    """
    Signs the input data with the private key and the certificate from keyring
    source.

    @type input_bio: M2Crypto.BIO
    @param input_bio: input data to sign.
    @type private_key: filepath or M2Crypto.BIO or M2Crypto.EVP.PKey
    @param private_key: sender private key reference, could be from file,
        from memory or from pkcs11 smartcard, based on keyring_soruce input
        parameter.
    @type cert: filepath or M2Crypto.BIO or M2Crypto.X509.X509
    @param cert: sender certificate, could be from filepath, from memory or
        from pkcs11 smartcard, based on keyring_soruce input parameter.
    @type keyring_source: str
    @keyword keyring_source: the type of the source for input certificate, used
        to recall the appropriate method for signer settings. Ammitted
        values are: file, memory, pkcs11.
    @type type: str
    @keyword type: specifies the type of output PKCS#7 data: PEM or DER
    @rtype: M2Crypto.SMIME.PKCS7
    @return: the PKCS#7 signed data in PEM or DER format.
    """
    signer = SMIME.SMIME()
    set_keyring(signer, private_key, cert, keyring_source)
    Rand.load_file('randpool.dat', -1)
    try:
        if type == 'PEM':
            p7 = signer.sign(input_bio, flags=SMIME.PKCS7_DETACHED)
        elif type == 'DER':
            p7 = signer.sign(input_bio)
        else:
            logging.error('pkcs7 type error: unknown type')
            raise BadPKCS7Type('unknown type: ' + type +
                        '; possible values: PEM, DER')
    except SMIME.SMIME_Error, e:
        logging.error('smime error: ' + str(e))
        raise
示例#26
0
            r = BN.rand_range(1)
            assert r == 0
        
        for x in range(loops):
            r = BN.rand_range(4)
            assert 0 <= r < 4
        
        # large range
        r512 = BN.rand(512, top=0)
        for x in range(loops):
            r = BN.rand_range(r512)
            assert 0 <= r < r512

            
    def test_randfname(self):
        m = re.compile('^[a-zA-Z0-9]{8}$')
        for x in range(loops):
            r = BN.randfname(8)
            assert m.match(r)
        

def suite():
    return unittest.makeSuite(BNTestCase)


if __name__ == '__main__':
    Rand.load_file('randpool.dat', -1) 
    unittest.TextTestRunner().run(suite())
    Rand.save_file('randpool.dat')

示例#27
0
from M2Crypto import BIO, Rand, SMIME


def makebuf(text):
    return BIO.MemoryBuffer(text)


# Make a MemoryBuffer of the message.
buf = makebuf('a sign of our times')

# Seed the PRNG.
Rand.load_file('randpool.dat', -1)

# Instantiate an SMIME object; set it up; sign the buffer.
s = SMIME.SMIME()
s.load_key('mycert-private.pem', 'mycert.pem')
p7 = s.sign(buf, SMIME.PKCS7_DETACHED)

# Recreate buf.
buf = makebuf("""Content-Type: text/plain

a sign of our times""")

# Output p7 in mail-friendly format.
out = BIO.MemoryBuffer()
s.write(out, p7, buf)
#p7.write(out)
print out.read()

# Save the PRNG's state.
Rand.save_file('randpool.dat')
示例#28
0
 def retfun(*args, **kwargs):
     Rand.load_file(global_randfile, -1)
     r = function(*args, **kwargs)
     Rand.save_file(global_randfile)
     return r
示例#29
0
    def sign_and_attachment(self):
        server = 'mail.example.dom'
        sender = '*****@*****.**'
        to = [
            '*****@*****.**',
        ]
        subject = 'test'
        text = 'test message'
        files = ['m2-demo.py']
        attachments = {}
        bcc = []

        if isinstance(to, str):
            to = [to]

        # create multipart message
        msg = MIMEMultipart()

        # attach message text as first attachment
        msg.attach(MIMEText(text))

        # attach files to be read from file system
        for file in files:
            part = MIMEBase('application', "octet-stream")
            part.set_payload(open(file, "rb").read())
            Encoders.encode_base64(part)
            part.add_header(
                'Content-Disposition',
                'attachment; filename="%s"' % os.path.basename(file))
            msg.attach(part)

        # attach filest read from dictionary
        for name in attachments:
            part = MIMEBase('application', "octet-stream")
            part.set_payload(attachments[name])
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            'attachment; filename="%s"' % name)
            msg.attach(part)

        # put message with attachments into into SSL' I/O buffer
        msg_str = msg.as_string()
        buf = BIO.MemoryBuffer(msg_str)

        # load seed file for PRNG
        Rand.load_file(randpool, -1)

        smime = SMIME.SMIME()

        # load certificate
        smime.load_key(signer_key, signer_cert)

        # sign whole message
        p7 = smime.sign(buf, SMIME.PKCS7_DETACHED)

        # create buffer for final mail and write header
        out = BIO.MemoryBuffer()
        out.write('From: %s\n' % sender)
        out.write('To: %s\n' % COMMASPACE.join(to))
        out.write('Date: %s\n' % formatdate(localtime=True))
        out.write('Subject: %s\n' % subject)
        out.write('Auto-Submitted: %s\n' % 'auto-generated')

        # convert message back into string
        buf = BIO.MemoryBuffer(msg_str)

        # append signed message and original message to mail header
        smime.write(out, p7, buf)

        # load save seed file for PRNG
        Rand.save_file(randpool)

        # extend list of recipents with bcc adresses
        to.extend(bcc)

        result = out.read()

        open('smime-m2-attachment.txt', 'wt').write(result)
        return

        # finaly send mail
        smtp = smtplib.SMTP(server)
        smtp.sendmail(sender, to, result)
        smtp.close()
示例#30
0
"""S/MIME HOWTO demo program.

Copyright (c) 1999-2001 Ng Pheng Siong. All rights reserved."""

from M2Crypto import BIO, Rand, SMIME, X509


def makebuf(text):
    return BIO.MemoryBuffer(text)


# Make a MemoryBuffer of the message.
buf = makebuf("a sign of our times")

# Seed the PRNG.
Rand.load_file("randpool.dat", -1)

# Instantiate an SMIME object.
s = SMIME.SMIME()

# Load signer's key and cert. Sign the buffer.
s.load_key("signer_key.pem", "signer.pem")
p7 = s.sign(buf)

# Load target cert to encrypt the signed message to.
x509 = X509.load_cert("recipient.pem")
sk = X509.X509_Stack()
sk.push(x509)
s.set_x509_stack(sk)

# Set cipher: 3-key triple-DES in CBC mode.
示例#31
0
 def setUp(self):
     """ override TestAsServer """
     TestAsServer.setUp(self)
     Rand.load_file('randpool.dat', -1)
示例#32
0
 def setUp(self):
     """ override TestAsServer """
     TestAsServer.setUp(self)
     Rand.load_file('randpool.dat', -1)
示例#33
0
from M2Crypto import BIO, SMIME, X509, Rand
#
cert=".certs/book.com/cert.pem"
rand=".certs/book.com/rand.pem"
json='{ "name":"hdknr","address":"shibuya" }'

# Buffer
buf = BIO.MemoryBuffer(json)

# Seed the PRNG
Rand.load_file(rand,-1)

# S/MIME object
s = SMIME.SMIME()

# Load certificate
x509 = X509.load_cert(cert)
sk=X509.X509_Stack()
sk.push(x509)
s.set_x509_stack(sk)

#Set cipher: 3-key triple-DES in CBC mode.
s.set_cipher(SMIME.Cipher('des_ede3_cbc'))

# Encrypt the buffer.
p7 = s.encrypt(buf)
#p7  = s.sign(buf)

out = BIO.MemoryBuffer()
s.write(out, p7)
smime = out.read() 
示例#34
0
def send_mail_ssl(server, sender, to, to_cert, subject, text, files=[], attachments={}, send=False):
    """
    Sends SSL signed mail

    server - mailserver domain name eg. smtp.foo.bar
    sender - content of From field eg. "No Reply" <*****@*****.**>
    to - string with email addresses of recipent
    subject - subject of a mail
    text - text of email
    files - list of strings with paths to file to be attached
    attachmets - dict where keys are file names and values are content of files
    to be attached
    send - bool whether message should really be sent
    """

    # create multipart message
    msg = MIMEMultipart()

    # attach message text as first attachment
    msg.attach(MIMEText(text))

    # attach files to be read from file system
    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(file, "rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'
                       % os.path.basename(file))
        msg.attach(part)

    # attach filest read from dictionary
    for name in attachments:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(attachments[name])
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % name)
        msg.attach(part)

    msg_str = msg.as_string()

    # Make a MemoryBuffer of the message.
    buf = BIO.MemoryBuffer(msg_str)

    # Seed the PRNG.
    Rand.load_file('randpool.dat', -1)

    # Instantiate an SMIME object.
    s = SMIME.SMIME()

    # Load target cert to encrypt to.
    x509 = X509.load_cert_string(to_cert)
    sk = X509.X509_Stack()
    sk.push(x509)
    s.set_x509_stack(sk)

    # Set cipher: 3-key triple-DES in CBC mode.
    s.set_cipher(SMIME.Cipher('des_ede3_cbc'))

    # Encrypt the buffer.
    p7 = s.encrypt(buf)

    # Output p7 in mail-friendly format.
    out = BIO.MemoryBuffer()
    out.write('From: %s\n' % sender)
    out.write('To: %s\n' % to)
    out.write('Subject: %s\n' % subject)

    # append signed message and original message to mail header
    s.write(out, p7)

    # Save the PRNG's state.
    Rand.save_file('randpool.dat')

    # finally send mail
    if send:
        #        print("would have sent")
        smtp = smtplib.SMTP(server)
        smtp.sendmail(sender, to, out.read() )
        smtp.close()
    else:
        print("sending is disabled (use --send)")
示例#35
0
        pass
    except:
        raise

    # Check umask sanity if we're on posix.
    if os.name == 'posix' and not os.environ.get('Z_DEBUG_MODE'):
        # umask is silly, blame POSIX.  We have to set it to get its value.
        current_umask = os.umask(0)
        os.umask(current_umask)
        if current_umask != 077:
            current_umask = '%03o' % current_umask
            zLOG.LOG("z2", zLOG.INFO, (
                'Your umask of %s may be too permissive; for the security of '
                'your Zope data, it is recommended you use 077' % current_umask
                ))

except:
    # Log startup exception and tell zdaemon not to restart us.
    try:
        zLOG.LOG("z2", zLOG.PANIC, "Startup exception",
                 error=sys.exc_info())
    except: pass
    sys.exit(0)

# Start Medusa, Ye Hass!
Rand.load_file('%s/randpool.dat' % INSTANCE_HOME, -1)
sys.ZServerExitCode=0
asyncore.loop()
Rand.save_file('%s/randpool.dat' % INSTANCE_HOME)
sys.exit(sys.ZServerExitCode)
示例#36
0
文件: server1.py 项目: jenner/vmw.zsi
class HTTPS_Server(SSLServer):
    def __init__(self, ME, HandlerClass, sslctx):
        SSLServer.__init__(self, ME, HandlerClass, sslctx)
        self.tracefile = None

    def finish(self):
        self.request.set_shutdown(SSL.SSL_RECEIVED_SHUTDOWN | SSL.SSL_SENT_SHUTDOWN)
        self.request.close()

def init_ssl_context(dir, debug=None):
    ctx = SSL.Context('sslv23')
    if debug: ctx.set_info_callback()
    ctx.load_cert(certfile=dir+'/cert.pem', keyfile=dir+'/plainkey.pem')
    ctx.set_verify(SSL.verify_none, 1)
    ctx.set_allow_unknown_ca(1)
    ctx.set_session_id_ctx('xkms_srv')
    return ctx

dir = os.environ.get('XKMSHOME', '/opt/xkms') + '/openssl/ssl'
randfile = dir + '/xkms-ca/.rand'
Rand.load_file(randfile, -1)
sslctx = init_ssl_context(dir, 1)
s = HTTPS_Server(('', 9999), XKMSRequestHandler, sslctx)
s.tracefile=sys.stderr
try:
    s.serve_forever()
except KeyboardInterrupt:
    print "Quitting..."
    pass
Rand.save_file(randfile)
示例#37
0
from M2Crypto import BIO, SMIME, X509, Rand
#
cert = ".certs/book.com/cert.pem"
rand = ".certs/book.com/rand.pem"
json = '{ "name":"hdknr","address":"shibuya" }'

# Buffer
buf = BIO.MemoryBuffer(json)

# Seed the PRNG
Rand.load_file(rand, -1)

# S/MIME object
s = SMIME.SMIME()

# Load certificate
x509 = X509.load_cert(cert)
sk = X509.X509_Stack()
sk.push(x509)
s.set_x509_stack(sk)

#Set cipher: 3-key triple-DES in CBC mode.
s.set_cipher(SMIME.Cipher('des_ede3_cbc'))

# Encrypt the buffer.
p7 = s.encrypt(buf)
#p7  = s.sign(buf)

out = BIO.MemoryBuffer()
s.write(out, p7)
smime = out.read()