本文整理汇总了Python中Crypt.CryptHash.sha512sum方法的典型用法代码示例。如果您正苦于以下问题:Python CryptHash.sha512sum方法的具体用法?Python CryptHash.sha512sum怎么用?Python CryptHash.sha512sum使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Crypt.CryptHash
的用法示例。
在下文中一共展示了CryptHash.sha512sum方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: hashFiles
# 需要导入模块: from Crypt import CryptHash [as 别名]
# 或者: from Crypt.CryptHash import sha512sum [as 别名]
def hashFiles(self, dir_inner_path, ignore_pattern=None, optional_pattern=None):
files_node = {}
files_optional_node = {}
for file_relative_path in self.site.storage.list(dir_inner_path):
file_name = helper.getFilename(file_relative_path)
ignored = optional = False
if file_name == "content.json":
ignored = True
elif ignore_pattern and re.match(ignore_pattern, file_relative_path):
ignored = True
elif file_name.startswith("."):
ignored = True
elif optional_pattern and re.match(optional_pattern, file_relative_path):
optional = True
if ignored: # Ignore content.json, definied regexp and files starting with .
self.log.info("- [SKIPPED] %s" % file_relative_path)
else:
file_path = self.site.storage.getPath(dir_inner_path + "/" + file_relative_path)
sha512sum = CryptHash.sha512sum(file_path) # Calculate sha512 sum of file
if optional:
self.log.info("- [OPTIONAL] %s (SHA512: %s)" % (file_relative_path, sha512sum))
files_optional_node[file_relative_path] = {"sha512": sha512sum, "size": os.path.getsize(file_path)}
else:
self.log.info("- %s (SHA512: %s)" % (file_relative_path, sha512sum))
files_node[file_relative_path] = {"sha512": sha512sum, "size": os.path.getsize(file_path)}
return files_node, files_optional_node
示例2: hashFile
# 需要导入模块: from Crypt import CryptHash [as 别名]
# 或者: from Crypt.CryptHash import sha512sum [as 别名]
def hashFile(self, dir_inner_path, file_relative_path, optional=False):
back = {}
file_inner_path = dir_inner_path + "/" + file_relative_path
file_path = self.site.storage.getPath(file_inner_path)
file_size = os.path.getsize(file_path)
sha512sum = CryptHash.sha512sum(file_path) # Calculate sha512 sum of file
if optional and not self.hashfield.hasHash(sha512sum):
self.optionalDownloaded(file_inner_path, self.hashfield.getHashId(sha512sum), file_size, own=True)
back[file_relative_path] = {"sha512": sha512sum, "size": os.path.getsize(file_path)}
return back
示例3: testHashfield
# 需要导入模块: from Crypt import CryptHash [as 别名]
# 或者: from Crypt.CryptHash import sha512sum [as 别名]
def testHashfield(self, site):
sample_hash = site.content_manager.contents["content.json"]["files_optional"].values()[0]["sha512"]
site.storage.verifyFiles(quick_check=True) # Find what optional files we have
# Check if hashfield has any files
assert len(site.content_manager.hashfield) > 0
# Check exsist hash
assert site.content_manager.hashfield.getHashId(sample_hash) in site.content_manager.hashfield
# Add new hash
new_hash = CryptHash.sha512sum(StringIO("hello"))
assert site.content_manager.hashfield.getHashId(new_hash) not in site.content_manager.hashfield
assert site.content_manager.hashfield.appendHash(new_hash)
assert not site.content_manager.hashfield.appendHash(new_hash) # Don't add second time
assert site.content_manager.hashfield.getHashId(new_hash) in site.content_manager.hashfield
# Remove new hash
assert site.content_manager.hashfield.removeHash(new_hash)
assert site.content_manager.hashfield.getHashId(new_hash) not in site.content_manager.hashfield
示例4: hashFiles
# 需要导入模块: from Crypt import CryptHash [as 别名]
# 或者: from Crypt.CryptHash import sha512sum [as 别名]
def hashFiles(self, dir_inner_path, ignore_pattern=None, optional_pattern=None):
files_node = {}
files_optional_node = {}
if not re.match("^[[email protected]=\.\+-/]*$", dir_inner_path):
ignored = True
self.log.error("- [ERROR] Only ascii encoded directories allowed: %s" % dir_inner_path)
for file_relative_path in self.site.storage.list(dir_inner_path):
file_name = helper.getFilename(file_relative_path)
ignored = optional = False
if file_name == "content.json":
ignored = True
elif ignore_pattern and re.match(ignore_pattern, file_relative_path):
ignored = True
elif file_name.startswith(".") or file_name.endswith("-old") or file_name.endswith("-new"):
ignored = True
elif not re.match("^[[email protected]=\.\+\-/]+$", file_relative_path):
ignored = True
self.log.error("- [ERROR] Only ascii encoded filenames allowed: %s" % file_relative_path)
elif optional_pattern and re.match(optional_pattern, file_relative_path):
optional = True
if ignored: # Ignore content.json, defined regexp and files starting with .
self.log.info("- [SKIPPED] %s" % file_relative_path)
else:
file_inner_path = dir_inner_path + "/" + file_relative_path
file_path = self.site.storage.getPath(file_inner_path)
sha512sum = CryptHash.sha512sum(file_path) # Calculate sha512 sum of file
if optional:
self.log.info("- [OPTIONAL] %s (SHA512: %s)" % (file_relative_path, sha512sum))
file_size = os.path.getsize(file_path)
files_optional_node[file_relative_path] = {"sha512": sha512sum, "size": file_size}
if not self.hashfield.hasHash(sha512sum):
self.optionalDownloaded(file_inner_path, sha512sum, file_size, own=True)
else:
self.log.info("- %s (SHA512: %s)" % (file_relative_path, sha512sum))
files_node[file_relative_path] = {"sha512": sha512sum, "size": os.path.getsize(file_path)}
return files_node, files_optional_node
示例5:
# 需要导入模块: from Crypt import CryptHash [as 别名]
# 或者: from Crypt.CryptHash import sha512sum [as 别名]
if valid_signs >= signs_required:
break # Break if we has enough signs
self.log.debug("%s: Valid signs: %s/%s" % (inner_path, valid_signs, signs_required))
return valid_signs >= signs_required
else: # Old style signing
return CryptBitcoin.verify(sign_content, self.site.address, sign)
except Exception, err:
self.log.error("Verify sign error: %s" % Debug.formatException(err))
return False
else: # Check using sha512 hash
file_info = self.getFileInfo(inner_path)
if file_info:
if "sha512" in file_info:
hash_valid = CryptHash.sha512sum(file) == file_info["sha512"]
elif "sha1" in file_info: # Backward compatibility
hash_valid = CryptHash.sha1sum(file) == file_info["sha1"]
else:
hash_valid = False
if file_info.get("size", 0) != file.tell():
self.log.error(
"%s file size does not match %s <> %s, Hash: %s" %
(inner_path, file.tell(), file_info.get("size", 0), hash_valid)
)
return False
return hash_valid
else: # File not in content.json
self.log.error("File not in content.json: %s" % inner_path)
return False
示例6: verifyPiece
# 需要导入模块: from Crypt import CryptHash [as 别名]
# 或者: from Crypt.CryptHash import sha512sum [as 别名]
def verifyPiece(self, inner_path, pos, piece):
piecemap = self.getPiecemap(inner_path)
piece_i = pos / piecemap["piece_size"]
if CryptHash.sha512sum(piece, format="digest") != piecemap["sha512_pieces"][piece_i]:
raise VerifyError("Invalid hash")
return True
示例7: sign
# 需要导入模块: from Crypt import CryptHash [as 别名]
# 或者: from Crypt.CryptHash import sha512sum [as 别名]
def sign(self, inner_path = "content.json", privatekey=None, filewrite=True, update_changed_files=False):
content = self.contents.get(inner_path)
if not content: # Content not exits yet, load default one
self.log.info("File %s not exits yet, loading default values..." % inner_path)
content = {"files": {}, "signs": {}} # Default content.json
if inner_path == "content.json": # Its the root content.json, add some more fields
content["title"] = "%s - ZeroNet_" % self.site.address
content["description"] = ""
content["signs_required"] = 1
content["ignore"] = ""
directory = self.toDir(self.site.storage.getPath(inner_path))
self.log.info("Opening site data directory: %s..." % directory)
hashed_files = {}
changed_files = [inner_path]
for root, dirs, files in os.walk(directory):
for file_name in files:
file_path = self.site.storage.getPath("%s/%s" % (root.strip("/"), file_name))
file_inner_path = re.sub(re.escape(directory), "", file_path)
if file_name == "content.json" or (content.get("ignore") and re.match(content["ignore"], file_inner_path)) or file_name.startswith("."): # Ignore content.json, definied regexp and files starting with .
self.log.info("- [SKIPPED] %s" % file_inner_path)
else:
sha512sum = CryptHash.sha512sum(file_path) # Calculate sha512 sum of file
self.log.info("- %s (SHA512: %s)" % (file_inner_path, sha512sum))
hashed_files[file_inner_path] = {"sha512": sha512sum, "size": os.path.getsize(file_path)}
if file_inner_path in content["files"].keys() and hashed_files[file_inner_path]["sha512"] != content["files"][file_inner_path].get("sha512"):
changed_files.append(file_path)
self.log.debug("Changed files: %s" % changed_files)
if update_changed_files:
for file_path in changed_files:
self.site.storage.onUpdated(file_path)
# Generate new content.json
self.log.info("Adding timestamp and sha512sums to new content.json...")
new_content = content.copy() # Create a copy of current content.json
new_content["files"] = hashed_files # Add files sha512 hash
new_content["modified"] = time.time() # Add timestamp
if inner_path == "content.json":
new_content["address"] = self.site.address
new_content["zeronet_version"] = config.version
new_content["signs_required"] = content.get("signs_required", 1)
from Crypt import CryptBitcoin
self.log.info("Verifying private key...")
privatekey_address = CryptBitcoin.privatekeyToAddress(privatekey)
valid_signers = self.getValidSigners(inner_path)
if privatekey_address not in valid_signers:
return self.log.error("Private key invalid! Valid signers: %s, Private key address: %s" % (valid_signers, privatekey_address))
self.log.info("Correct %s in valid signers: %s" % (privatekey_address, valid_signers))
if inner_path == "content.json" and privatekey_address == self.site.address: # If signing using the root key sign the valid signers
new_content["signers_sign"] = CryptBitcoin.sign("%s:%s" % (new_content["signs_required"], ",".join(valid_signers)), privatekey)
if not new_content["signers_sign"]: self.log.info("Old style address, signers_sign is none")
self.log.info("Signing %s..." % inner_path)
if "signs" in new_content: del(new_content["signs"]) # Delete old signs
if "sign" in new_content: del(new_content["sign"]) # Delete old sign (backward compatibility)
sign_content = json.dumps(new_content, sort_keys=True)
sign = CryptBitcoin.sign(sign_content, privatekey)
#new_content["signs"] = content.get("signs", {}) # TODO: Multisig
if sign: # If signing is successful (not an old address)
new_content["signs"] = {}
new_content["signs"][privatekey_address] = sign
if inner_path == "content.json": # To root content.json add old format sign for backward compatibility
oldsign_content = json.dumps(new_content, sort_keys=True)
new_content["sign"] = CryptBitcoin.signOld(oldsign_content, privatekey)
if not self.validContent(inner_path, new_content):
self.log.error("Sign failed: Invalid content")
return False
if filewrite:
self.log.info("Saving to %s..." % inner_path)
json.dump(new_content, open(self.site.storage.getPath(inner_path), "w"), indent=2, sort_keys=True)
self.log.info("File %s signed!" % inner_path)
if filewrite: # Written to file
return True
else: # Return the new content
return new_content
示例8: VerifyError
# 需要导入模块: from Crypt import CryptHash [as 别名]
# 或者: from Crypt.CryptHash import sha512sum [as 别名]
else:
return self.verifyContent(inner_path, new_content)
else: # Old style signing
if CryptBitcoin.verify(sign_content, self.site.address, sign):
return self.verifyContent(inner_path, new_content)
else:
raise VerifyError("Invalid old-style sign")
except Exception, err:
self.log.warning("%s: verify sign error: %s" % (inner_path, Debug.formatException(err)))
raise err
else: # Check using sha512 hash
file_info = self.getFileInfo(inner_path)
if file_info:
if CryptHash.sha512sum(file) != file_info.get("sha512", ""):
raise VerifyError("Invalid hash")
if file_info.get("size", 0) != file.tell():
raise VerifyError(
"File size does not match %s <> %s" %
(inner_path, file.tell(), file_info.get("size", 0))
)
return True
else: # File not in content.json
raise VerifyError("File not in content.json")
def optionalDelete(self, inner_path):
self.site.storage.delete(inner_path)
示例9: range
# 需要导入模块: from Crypt import CryptHash [as 别名]
# 或者: from Crypt.CryptHash import sha512sum [as 别名]
for i in range(10):
yield "."
ok = CryptBitcoin.verify(data, address, sign)
assert ok, "does not verify from %s" % address
CryptBitcoin.opensslVerify = opensslVerify_bk
yield "<br>CryptHash:<br>"
from Crypt import CryptHash
from cStringIO import StringIO
data = StringIO("Hello"*1024*1024) #5m
with benchmark("sha512 x 10 000", 1):
for i in range(10):
for y in range(10000):
hash = CryptHash.sha512sum(data)
yield "."
valid = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"
assert hash == valid, "%s != %s" % (hash, valid)
yield "<br>Db:<br>"
from Db import Db
schema = {
"db_name": "TestDb",
"db_file": "%s/benchmark.db" % config.data_dir,
"maps": {
".*": {
"to_table": {
"test": "test"
示例10: VerifyError
# 需要导入模块: from Crypt import CryptHash [as 别名]
# 或者: from Crypt.CryptHash import sha512sum [as 别名]
else:
return True
else: # Old style signing
if CryptBitcoin.verify(sign_content, self.site.address, sign):
return True
else:
raise VerifyError("Invalid old-style sign")
except Exception, err:
self.log.warning("Verify sign error: %s" % Debug.formatException(err))
raise err
else: # Check using sha512 hash
file_info = self.getFileInfo(inner_path)
if file_info:
if CryptHash.sha512sum(file) != file_info["sha512"]:
raise VerifyError("Invalid hash")
if file_info.get("size", 0) != file.tell():
raise VerifyError(
"File size does not match %s <> %s" %
(inner_path, file.tell(), file_info.get("size", 0))
)
return True
else: # File not in content.json
raise VerifyError("File not in content.json")
def optionalDownloaded(self, inner_path, hash, size=None, own=False):
if size is None: