Ejemplo n.º 1
0
 def sign(self, data):
     """
     Emulates the signing behavior of an ssh key agent.
     """
     digest = MessageDigest('sha1')
     digest.update(data)
     my_data = digest.final()
     return self.instance.sign(data)
def M2Crypto_SHA1():
    global encryptionavg
    global decryptionavg
    from M2Crypto.EVP import MessageDigest
    startTime = time.time()
    h = MessageDigest('sha1')
    h.update(plainContent)
    totalTime = time.time() - startTime
    encryptionavg += totalTime
    #print totalTime
    print('SHA1 Hash: Total time: %.5f seconds' % totalTime)
Ejemplo n.º 3
0
def demo1():
    print 'Test 1: As DER...'
    cert1 = X509.load_cert('server.pem')
    der1 = cert1.as_der()
    dgst1 = MessageDigest('sha1')
    dgst1.update(der1)
    print 'Using M2Crypto:\n', `dgst1.final()`, '\n'

    cert2 = os.popen('openssl x509 -inform pem -outform der -in server.pem')
    der2 = cert2.read()
    dgst2 = MessageDigest('sha1')
    dgst2.update(der2)
    print 'Openssl command line:\n', `dgst2.final()`, '\n'
Ejemplo n.º 4
0
def md5(buf):
    b = MessageDigest('md5')
    b.update(buf)
    b.update('888')
    c = b.digest()
    s = ''
    for i in c:
        s = s + '%02x' % ord(i)
    return s
Ejemplo n.º 5
0
def md5(buf):
    b = MessageDigest("md5")
    b.update(buf)
    b.update("888")
    c = b.digest()
    s = ""
    for i in c:
        s = s + "%02x" % ord(i)
    return s
Ejemplo n.º 6
0
from M2Crypto import EC
from M2Crypto.EVP import MessageDigest
def bigint(string):
    return int(string.encode('hex'), 16)

# raw data
myhash = "hello world"

# digest data using sha256
md = MessageDigest('sha256')
md.update(myhash)
myhash = md.digest()
print '#'*30
print '#'*10, myhash
print '#'*30


# sign digested data using EC key pair
# load_key can also load private key, and use load_pub_key to load public key
# return (r,s)
# load key from string
# privKey = open('Cesium-ECC-PrivateKey.pem','rb')
# privKey = privKey.read()
# bio = BIO.MemoryBuffer(privKey)
# key = EC.load_key_bio(bio)

key = EC.load_key('Cesium-ECC-ECParam.pem')
sigr, sigs = key.sign_dsa(myhash)
print '#'*30
print '#'*10, 'sigr: ', sigr
Ejemplo n.º 7
0
def m2_sha_2(iter, txt=txt):
    s = MessageDigest('sha1')
    s.update(txt * iter)
    out = s.digest()
Ejemplo n.º 8
0
def m2_sha(iter, txt=txt):
    s = MessageDigest('sha1')
    for i in range(iter):
        s.update(txt)
    out = s.digest()
Ejemplo n.º 9
0
def demo1():
    print 'Test 1: As DER...'
    cert1 = X509.load_cert('server.pem')
    der1 = cert1.as_der()
    dgst1 = MessageDigest('sha1')
    dgst1.update(der1)
    print 'Using M2Crypto:\n', ` dgst1.final() `, '\n'

    cert2 = os.popen('openssl x509 -inform pem -outform der -in server.pem')
    der2 = cert2.read()
    dgst2 = MessageDigest('sha1')
    dgst2.update(der2)
    print 'Openssl command line:\n', ` dgst2.final() `, '\n'
Ejemplo n.º 10
0
def m2_sha_2(iter, txt=txt):
    s = MessageDigest('sha1')
    s.update(txt * iter)
    out = s.digest()
Ejemplo n.º 11
0
def m2_sha(iter, txt=txt):
    s = MessageDigest('sha1')
    for i in range(iter):
        s.update(txt)
    out = s.digest()
 def do_stamp(self, cr, uid, ids, context):
     if context is None:
         context = {}
     form = self.browse(cr, uid, ids)[0]
     stamp_res = 'stamp_done'
     xslt_path = self._find_file_in_addons('asti_eaccounting_mx_base/sat_xslt', form.xml_target + '.xslt')
     try:
         xslt_file = open(xslt_path, 'r')
     except:
         raise osv.except_osv('Hoja XSLT no encontrada', u'La hoja de transformaci\xf3n no fue encontrada en la ruta "%s"' % xslt_path)
     xsltTree = et.parse(xslt_file)
     xsltTree.find('{http://www.w3.org/1999/XSL/Transform}output').attrib['omit-xml-declaration'] = 'yes'
     try:
         xslt = et.XSLT(xsltTree)
     except et.XSLTParseError:
         xsltTree.find('{http://www.w3.org/1999/XSL/Transform}include').attrib['href'] = xslt_path.replace(form.xml_target, 'utils')
         try:
             xslt = et.XSLT(xsltTree)
             stamp_res = 'stamp_xcpt'
         except:
             xslt = None
     if xslt is None:
         raise osv.except_osv('Error al cargar la hoja XSLT', 'Por favor intente sellar de nuevo el documento.')
     xmlTree = et.ElementTree(et.fromstring(b64dec(form.primary_file)))
     transformedDocument = str(xslt(xmlTree))
     user = self.pool.get('res.users').browse(cr, uid, uid)
     ##########
     certificate_obj = self.pool.get('res.company.facturae.certificate')
     certificate_ids = certificate_obj.search(cr, uid, [
             ('company_id', '=', user.company_id.id),
             ('date_start', '<=', time.strftime('%Y-%m-%d')),
             ('date_end', '>=', time.strftime('%Y-%m-%d')),
             ('active', '=', True),
         ], limit=1)
     certificate_id = certificate_ids and certificate_ids[0] or False
     if not certificate_id:
         raise osv.except_osv(u'Informaci\xf3n faltante', u'No se ha encontrado una configuraci\xf3n de certificados disponible para la compa\xf1\xeda %s' % user.company_id.name)
     #########
     #allConfiguredCerts = user.company_id._get_current_certificate(cr, uid, [user.company_id.id], context=ctx)
     #allConfiguredCerts = user.company_id.certificate_id.id
     #print "allConfiguredCerts: ", allConfiguredCerts
     #if user.company_id.id not in allConfiguredCerts.keys() or not allConfiguredCerts[user.company_id.id]:
     #    raise osv.except_osv(u'Informaci\xf3n faltante', u'No se ha encontrado una configuraci\xf3n de certificados disponible para la compa\xf1\xeda %s' % user.company_id.name)
     #eCert = self.pool.get('res.company.facturae.certificate').browse(cr, uid, [allConfiguredCerts[user.company_id.id]])[0]        
     ##########
     eCert = self.pool.get('res.company.facturae.certificate').browse(cr, uid, [certificate_id])[0]
     ##########
     if not eCert.certificate_key_file_pem:
         raise osv.except_osv(u'Informaci\xf3n faltante', 'Se necesita una clave en formato PEM para poder sellar el documento')
     crypter = RSA.load_key_string(b64dec(eCert.certificate_key_file_pem))
     algrthm = MessageDigest('sha1')
     algrthm.update(transformedDocument)
     rawStamp = crypter.sign(algrthm.digest(), 'sha1')
     certHexNum = X509.load_cert_string(b64dec(eCert.certificate_file_pem), X509.FORMAT_PEM).get_serial_number()
     certNum = ('%x' % certHexNum).replace('33', 'B').replace('3', '')
     cert = ''.join([ ln for ln in b64dec(eCert.certificate_file_pem).split('\n') if 'CERTIFICATE' not in ln ])
     target = '{'
     if form.xml_target == 'accounts_catalog':
         target += self._ACCOUNTS_CATALOG_URI + '}Catalogo'
     elif form.xml_target == 'trial_balance':
         target += self._TRIAL_BALANCE_URI + '}Balanza'
     xmlTree.getroot().attrib['Sello'] = b64enc(rawStamp)
     xmlTree.getroot().attrib['noCertificado'] = certNum
     xmlTree.getroot().attrib['Certificado'] = cert
     validationResult = self._validate_xml(cr, uid, form.xml_target + '.xsd', xmlTree, form.filename)
     if isinstance(validationResult, dict):
         return validationResult
     self.write(cr, uid, ids, {'state': stamp_res,
      'stamped_file': b64enc(self._outputXml(xmlTree))})
     return self._reopen_wizard(ids[0])
Ejemplo n.º 13
0
 def do_stamp(self, cr, uid, ids, context):
     if context is None:
         context = {}
     form = self.browse(cr, uid, ids)[0]
     stamp_res = "stamp_done"
     xslt_path = self._find_file_in_addons("asti_eaccounting_mx_base/sat_xslt", form.xml_target + ".xslt")
     try:
         xslt_file = open(xslt_path, "r")
     except:
         raise osv.except_osv(
             "Hoja XSLT no encontrada", u'La hoja de transformaci\xf3n no fue encontrada en la ruta "%s"' % xslt_path
         )
     xsltTree = et.parse(xslt_file)
     xsltTree.find("{http://www.w3.org/1999/XSL/Transform}output").attrib["omit-xml-declaration"] = "yes"
     try:
         xslt = et.XSLT(xsltTree)
     except et.XSLTParseError:
         xsltTree.find("{http://www.w3.org/1999/XSL/Transform}include").attrib["href"] = xslt_path.replace(
             form.xml_target, "utils"
         )
         try:
             xslt = et.XSLT(xsltTree)
             stamp_res = "stamp_xcpt"
         except:
             xslt = None
     if xslt is None:
         raise osv.except_osv("Error al cargar la hoja XSLT", "Por favor intente sellar de nuevo el documento.")
     xmlTree = et.ElementTree(et.fromstring(b64dec(form.primary_file)))
     transformedDocument = str(xslt(xmlTree))
     user = self.pool.get("res.users").browse(cr, uid, uid)
     ##########
     certificate_obj = self.pool.get("res.company.facturae.certificate")
     certificate_ids = certificate_obj.search(
         cr,
         uid,
         [
             ("company_id", "=", user.company_id.id),
             ("date_start", "<=", time.strftime("%Y-%m-%d")),
             ("date_end", ">=", time.strftime("%Y-%m-%d")),
             ("active", "=", True),
         ],
         limit=1,
     )
     certificate_id = certificate_ids and certificate_ids[0] or False
     if not certificate_id:
         raise osv.except_osv(
             u"Informaci\xf3n faltante",
             u"No se ha encontrado una configuraci\xf3n de certificados disponible para la compa\xf1\xeda %s"
             % user.company_id.name,
         )
     #########
     # allConfiguredCerts = user.company_id._get_current_certificate(cr, uid, [user.company_id.id], context=ctx)
     # allConfiguredCerts = user.company_id.certificate_id.id
     # print "allConfiguredCerts: ", allConfiguredCerts
     # if user.company_id.id not in allConfiguredCerts.keys() or not allConfiguredCerts[user.company_id.id]:
     #    raise osv.except_osv(u'Informaci\xf3n faltante', u'No se ha encontrado una configuraci\xf3n de certificados disponible para la compa\xf1\xeda %s' % user.company_id.name)
     # eCert = self.pool.get('res.company.facturae.certificate').browse(cr, uid, [allConfiguredCerts[user.company_id.id]])[0]
     ##########
     eCert = self.pool.get("res.company.facturae.certificate").browse(cr, uid, [certificate_id])[0]
     ##########
     if not eCert.certificate_key_file_pem:
         raise osv.except_osv(
             u"Informaci\xf3n faltante", "Se necesita una clave en formato PEM para poder sellar el documento"
         )
     crypter = RSA.load_key_string(b64dec(eCert.certificate_key_file_pem))
     algrthm = MessageDigest("sha1")
     algrthm.update(transformedDocument)
     rawStamp = crypter.sign(algrthm.digest(), "sha1")
     certHexNum = X509.load_cert_string(b64dec(eCert.certificate_file_pem), X509.FORMAT_PEM).get_serial_number()
     certNum = ("%x" % certHexNum).replace("33", "B").replace("3", "")
     cert = "".join([ln for ln in b64dec(eCert.certificate_file_pem).split("\n") if "CERTIFICATE" not in ln])
     target = "{"
     if form.xml_target == "accounts_catalog":
         target += self._ACCOUNTS_CATALOG_URI + "}Catalogo"
     elif form.xml_target == "trial_balance":
         target += self._TRIAL_BALANCE_URI + "}Balanza"
     xmlTree.getroot().attrib["Sello"] = b64enc(rawStamp)
     xmlTree.getroot().attrib["noCertificado"] = certNum
     xmlTree.getroot().attrib["Certificado"] = cert
     validationResult = self._validate_xml(cr, uid, form.xml_target + ".xsd", xmlTree, form.filename)
     if isinstance(validationResult, dict):
         return validationResult
     self.write(cr, uid, ids, {"state": stamp_res, "stamped_file": b64enc(self._outputXml(xmlTree))})
     return self._reopen_wizard(ids[0])
Ejemplo n.º 14
0
    def __call__(self, peerCert, host=None):
        if peerCert is None:
            raise NoCertificate('peer did not return certificate')

        if host is not None:
            self.host = host

        if self.fingerprint:
            if self.digest not in ('sha1', 'md5'):
                raise ValueError('unsupported digest "%s"' %(self.digest))

            if (self.digest == 'sha1' and len(self.fingerprint) != 40) or \
               (self.digest == 'md5' and len(self.fingerprint) != 32):
                raise WrongCertificate('peer certificate fingerprint length does not match')

            der = peerCert.as_der()
            md = MessageDigest(self.digest)
            md.update(der)
            digest = md.final()
            if octx_to_num(digest) != int(self.fingerprint, 16):
                raise WrongCertificate('peer certificate fingerprint does not match')

        if self.host and self.ssl_config.fqdn_check and self.ssl_config.check:
            hostValidationPassed = False
            self.useSubjectAltNameOnly = False

            # subjectAltName=DNS:somehost[, ...]*
            try:
                subjectAltName = peerCert.get_ext('subjectAltName').get_value()
                if self._splitSubjectAltName(self.host, subjectAltName):
                    hostValidationPassed = True
                elif self.useSubjectAltNameOnly:
                    raise WrongHost(expectedHost=self.host,
                                    actualHost=subjectAltName,
                                    fieldName='subjectAltName')
            except LookupError:
                pass

            # commonName=somehost[, ...]*
            if not hostValidationPassed:
                hasCommonName = False
                commonNames = ''
                for entry in peerCert.get_subject().get_entries_by_nid(NID_commonName):
                    hasCommonName = True
                    commonName = entry.get_data().as_text()
                    if not commonNames:
                        commonNames = commonName
                    else:
                        commonNames += ',' + commonName
                    if self._match(self.host, commonName):
                        hostValidationPassed = True
                        break

                if not hasCommonName:
                    raise WrongCertificate('no commonName in peer certificate')

                if not hostValidationPassed:
                    raise WrongHost(expectedHost=self.host,
                                    actualHost=commonNames,
                                    fieldName='commonName')

        return True
Ejemplo n.º 15
0
 def fingerprint(x509):
     der = x509.as_der()
     md = MessageDigest('sha1')
     md.update(der)
     digest = md.final()
     return hex(util.octx_to_num(digest))
Ejemplo n.º 16
0
def fingerprint(x509):
    der = x509.as_der()
    md = MessageDigest('sha1')
    md.update(der)
    digest = md.final()
    return hex(util.octx_to_num(digest))