You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
103 lines
2.5 KiB
103 lines
2.5 KiB
import hashlib
|
|
import json
|
|
|
|
# 支持的哈希类型列表
|
|
SUPPORTED_HASH_TYPES = [
|
|
'md5',
|
|
'sha1',
|
|
'sha224',
|
|
'sha256',
|
|
'sha384',
|
|
'sha512',
|
|
'sha3_224',
|
|
'sha3_256',
|
|
'sha3_384',
|
|
'sha3_512'
|
|
]
|
|
|
|
def encrypt_string(text, hash_type='md5'):
|
|
"""
|
|
使用指定的哈希算法加密字符串
|
|
|
|
参数:
|
|
text: 要加密的字符串
|
|
hash_type: 哈希算法类型,默认为'md5'
|
|
|
|
返回:
|
|
加密后的哈希值(十六进制字符串)
|
|
"""
|
|
if hash_type not in SUPPORTED_HASH_TYPES:
|
|
raise ValueError(f"不支持的哈希类型: {hash_type}。支持的哈希类型: {SUPPORTED_HASH_TYPES}")
|
|
|
|
# 获取哈希函数
|
|
hash_func = getattr(hashlib, hash_type)
|
|
|
|
# 计算哈希值
|
|
hash_obj = hash_func(text.encode('utf-8'))
|
|
return hash_obj.hexdigest()
|
|
|
|
def encrypt_string_all(text):
|
|
"""
|
|
使用所有支持的哈希算法加密字符串
|
|
|
|
参数:
|
|
text: 要加密的字符串
|
|
|
|
返回:
|
|
字典,包含所有哈希算法对应的加密结果
|
|
"""
|
|
results = {}
|
|
for hash_type in SUPPORTED_HASH_TYPES:
|
|
try:
|
|
results[hash_type] = encrypt_string(text, hash_type)
|
|
except Exception as e:
|
|
results[hash_type] = f"加密失败: {str(e)}"
|
|
|
|
return results
|
|
|
|
def get_hash_info(hash_value):
|
|
"""
|
|
根据哈希值长度推测可能的哈希算法
|
|
|
|
参数:
|
|
hash_value: 哈希值
|
|
|
|
返回:
|
|
可能的哈希算法列表
|
|
"""
|
|
hash_length = len(hash_value)
|
|
|
|
hash_lengths = {
|
|
32: ['MD5'],
|
|
40: ['SHA1'],
|
|
56: ['SHA224'],
|
|
64: ['SHA256'],
|
|
96: ['SHA384'],
|
|
128: ['SHA512'],
|
|
56: ['SHA3_224'],
|
|
64: ['SHA3_256'],
|
|
96: ['SHA3_384'],
|
|
128: ['SHA3_512']
|
|
}
|
|
|
|
if hash_length in hash_lengths:
|
|
return hash_lengths[hash_length]
|
|
else:
|
|
return ['未知哈希算法']
|
|
|
|
# 示例使用
|
|
if __name__ == '__main__':
|
|
# 示例1: 使用MD5加密字符串
|
|
text = "password"
|
|
md5_hash = encrypt_string(text, 'md5')
|
|
print(f"MD5哈希: {md5_hash}")
|
|
|
|
# 示例2: 使用所有算法加密
|
|
all_hashes = encrypt_string_all(text)
|
|
print(f"\n所有哈希算法结果:")
|
|
for algo, hash_val in all_hashes.items():
|
|
print(f" {algo}: {hash_val}")
|
|
|
|
# 示例3: 推测哈希算法
|
|
possible_algorithms = get_hash_info(md5_hash)
|
|
print(f"可能的哈希算法: {possible_algorithms}") |