Random String Generation and MD5 Hashing with Time and File Handling

  • Share this:

Code introduction


This function generates a random string, records the current time, calculates the MD5 hash of the string, writes the information to a file, then reads the information from the file, matches the information using regular expressions, and converts the matched information to JSON format.


Technology Stack : Python built-in libraries: random, string, datetime, hashlib, os, re, json

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import string
import math
import datetime
import hashlib
import os
import re
import json
import sys
import heapq
import sqlite3

def generate_random_string(length, chars=string.ascii_letters + string.digits):
    return ''.join(random.choice(chars) for _ in range(length))

def xxx(arg1, arg2):
    # 创建一个随机字符串
    random_string = generate_random_string(arg1)
    
    # 使用当前时间
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # 计算字符串的MD5散列值
    md5_hash = hashlib.md5(random_string.encode()).hexdigest()
    
    # 将信息写入文件
    with open('output.txt', 'w') as file:
        file.write(f"Random String: {random_string}\n")
        file.write(f"Current Time: {current_time}\n")
        file.write(f"MD5 Hash: {md5_hash}\n")
    
    # 从文件中读取信息
    with open('output.txt', 'r') as file:
        content = file.read()
    
    # 使用正则表达式匹配信息
    pattern = re.compile(r"Random String: (.*?)\nCurrent Time: .*\nMD5 Hash: (.*?)\n", re.DOTALL)
    match = pattern.search(content)
    
    # 将匹配到的信息转换为JSON格式
    result = json.dumps({
        "random_string": match.group(1),
        "md5_hash": match.group(2)
    })
    
    # 返回JSON字符串
    return result