Random String Generation and MD5 File Check

  • Share this:

Code introduction


This function first generates a random string of a specified length, then writes it to the specified file. Then, it calculates the MD5 value of the string and checks if there are any other files in the specified directory with the same MD5 value.


Technology Stack : random, string, json, math, datetime, os, re, hashlib, shutil

Code Type : File processing and encryption

Code Difficulty : Intermediate


                
                    
import random
import string
import json
import math
import datetime
import os
import re
import hashlib
import shutil

def generate_random_string(length=10):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def xxx(arg1, arg2, arg3):
    # 生成一个随机字符串,长度为arg1,不包含特殊字符,然后保存到arg2指定的文件中
    random_string = generate_random_string(arg1)
    with open(arg2, 'w') as file:
        file.write(random_string)
    
    # 计算字符串的MD5值
    md5_hash = hashlib.md5(random_string.encode()).hexdigest()
    
    # 检查arg3指定的目录中是否有相同MD5值的文件
    if os.path.isdir(arg3):
        files_with_same_md5 = [f for f in os.listdir(arg3) if hashlib.md5(open(os.path.join(arg3, f), 'rb').read()).hexdigest() == md5_hash]
        return files_with_same_md5
    else:
        return "The provided directory does not exist."