Пример #1
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
Пример #2
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
Пример #3
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
Пример #4
0
def m2_sha_2(iter, txt=txt):
    s = MessageDigest('sha1')
    s.update(txt * iter)
    out = s.digest()
Пример #5
0
def m2_sha(iter, txt=txt):
    s = MessageDigest('sha1')
    for i in range(iter):
        s.update(txt)
    out = s.digest()
Пример #6
0
def m2_sha_2(iter, txt=txt):
    s = MessageDigest('sha1')
    s.update(txt * iter)
    out = s.digest()
Пример #7
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])
Пример #9
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])