import random
import re
import string
from urllib.parse import urlparse
import requests
import hashlib
import os
import oss2
def get_file_md5(file_path):if not os.path.isfile(file_path):return None
with open(file_path,'rb') as f:
md5_hash = hashlib.md5()while True:
data = f.read(4096)if not data:break
md5_hash.update(data)return md5_hash.hexdigest(), os.path.getsize(file_path), os.path.splitext(file_path)[1]
# 上传文件
def upload(file_path, md5_name, accessId, accessSecret):
# 初始化OSS客户端
auth = oss2.Auth(accessId, accessSecret)
bucket = oss2.Bucket(auth, 'http://oss-cn-beijing.aliyuncs.com', 'down11/20240326')
# 文件路径和其他参数
object_name = md5_name
part_size =1024*1024 # 例如,每个分片大小为1MB
# 初始化分片上传并获取upload_id
upload_id = bucket.init_multipart_upload(object_name).upload_id
# 准备分片列表
parts =[]
# 打开文件并上传每个分片
with open(file_path,'rb') as file:while True:
data = file.read(part_size)if not data:break
part_number =len(parts)+1
result = bucket.upload_part(object_name, data, part_number, upload_id=upload_id)
parts.append({'part_number': part_number,'etag': result.etag
})
# 完成分片上传
bucket.complete_multipart_upload(object_name, upload_id, parts)
from hashlib import sha256
import hmac
import base64
import uuid
import hashlib
app_key ="203803574"
app_secret ="9znpamsyl2c7cdrr9sas0le9vbc3r6ba"#KdBtvfW8dNsqP177v6HMn0qNMzCeGF9NhfA6apMf90w=" "HG195lJSk7rRZ+93yRQNfTu8Rgwphcei09Oer+1UvmI="
# "https://bizapi.csdn.net/download-console-api/v1/user/author-layer""spCjl6GflfLzFXDBEe8EitdRjEuGxLuY6Xrq5LJusQo="
# "https://bizapi.csdn.net/download-console-api/v1/user/v2/demandSquare/list""R2CadKDIoJtDIjwk0XAT2WBnScAvXDnWXH89gu0LWkU="
# "https://bizapi.csdn.net/download-console-api/v1/user/v2/author-layer-task/list?taskStatus=1&authorTaskStatus=&pageNo=1&pageSize=2&titleQuery=&taskId=""0C2hyR9Ar53Hv+Bv8T8gCdcuULJ1U4+ktBkthPEcgoY="
# "https://bizapi.csdn.net/download-console-api/v1/user/sources/obtainViewRecord?type=0""eu0NZuDl8yupOTTbzxsM+QZOwXvw0MG9ljZf72cp+zo="
# "https://bizapi.csdn.net/download-console-api/v1/user/sources/getGuideInfo""3kO6mnX1cd7NlpdBmdtKh0JVbZS2eHtErXBq3Ahx1co="
# "https://bizapi.csdn.net/download-console-api/v1/user/sources/category""HbbjCtxjWxV6E2R/6/dDb3LkX0glenZxHIJBtjkS7mI="
# "https://bizapi.csdn.net/download-console-api/v1/user/getUserUploadMsg""fF0jO4UPVIYqUs65pdaY6CMJSeVSGzb3PrUue3DRw7Y="
# "https://bizapi.csdn.net/blog-console-api/v1/getSubdomainExpire""ikRgMDHPgsnBlnEgr992+/odPdfNeid/IIoFhnVZvVA="#x-ca-nonce
def createUuid():
text =""
char_list =[]for c in range(97,97+6):
char_list.append(chr(c))for c in range(49,58):
char_list.append(chr(c))for i in "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx":if i =="4":
text +="4"
elif i =="-":
text +="-"else:
text += random.choice(char_list)return text
def generate_uuid():
hex_chars ='0123456789abcdefABCDEF' # 直接定义十六进制字符集
uuid =[None]*36 # 创建一个长度为36的空列表来存储UUID的各部分
for i in range(36):if i ==8 or i ==13 or i ==18 or i ==23:
uuid[i]='-' # 在指定的位置插入'-'
elif i ==14:
uuid[i]='4' # 在第15位插入'4'else:if i ==19: # 对于第20位,确保是8,9, A, 或 B
uuid[i]= random.choice('89AB')else: # 对于其他'x'的位置,可以是任何十六进制字符
uuid[i]= random.choice(hex_chars)return''.join(uuid) # 将列表中的元素连接成一个字符串
#js生成函数"""
l =function(e){
var t ={};for(var n in e){
var a = n.toLowerCase();
a.startsWith("x-ca-")&&("x-ca-signature"!== a &&"x-ca-signature-headers"!== a &&"x-ca-key"!== a &&"x-ca-nonce"!== a ||(t[a]= e[n]))}return t
}
_ =function(e){
var t = e.method "GET", n = e.url
, a = e.appSecret
, o = e.accept "application/json, text/plain, */*", r = e.date "", c = e.contentType "", i = e.params
, u = e.headers
, f ="";
i ||-1=== n.indexOf("?")? i ||(i ={}):(i =h(n),
n = n.split("?")[0]);
var m ="";
f +="".concat(t,"\n"),
f +="".concat(o,"\n"),
f +="".concat(m,"\n"),
f +="".concat(c,"\n"),
f +="".concat(r,"\n");
var _, b =l(u), g = Array.from(Object.keys(b)).sort(), P =Object(s["a"])(g);
try {for(P.s();!(_ = P.n()).done;){
var v = _.value;
f += v +":"+ b[v]+"\n"}}catch(O){
P.e(O)} finally {
P.f()}
var A =/^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.csdn\.net)/, w = n.replace(A,"");
f +=p(w, i);
var U = d.a.HmacSHA256(f, a), k = U.toString(d.a.enc.Base64);return k
}"""
from urllib.parse import parse_qs
def p(e, t):
# 过滤掉t中值为空字符串或None的键
filtered_t={k: v for k, v in t.items()if v is not None and v !=""}
# 将过滤后的字典项转换成查询字符串的格式
query_string ="&".join([f"{k}={v}"for k, v in filtered_t.items()])
# 如果存在查询字符串,则将其附加到e后面,前面加上问号
if query_string:return f"{e}?{query_string}"else:return e
def h(url):
# 解析URL,提取查询参数
parsed_url =urlparse(url)
query_params =parse_qs(parsed_url.query)
# 将查询参数转换为字典,其中键是参数名,值是参数值的列表
# 如果参数只出现一次,则列表只有一个元素
params_dict ={k: v[0]iflen(v)==1else v for k, v in query_params.items()}
# 返回参数字典
return params_dict
def function_l(e):
t ={}for n in e:
a = n.lower()if a.startswith("x-ca-") and a in ["x-ca-signature","x-ca-signature-headers","x-ca-key","x-ca-nonce"]:
t[a]= e[n]return t
def function_underscore(e):
# 假设 h, s["a"], p, d.a.HmacSHA256, d.a.enc.Base64 已经在其他地方定义或导入
# 初始化变量
t = e.get("method","GET")
n = e["url"]
a = e["appSecret"]
o = e.get("accept","application/json, text/plain, */*")
r = e.get("date","")
c = e.get("contentType","")
i = e.get("params",{})
u = e["headers"]
f =""
# 处理 params 和 url
if not i and n.find("?")==-1:
pass # 假设没有 params 或 url 中没有 '?' 时不进行操作
else:if"?" in n:
i =h(n) # 假设 h 是处理 url 中的查询参数的函数
n = n.split("?")[0]
# 构建待签名的字符串 f
f +="{}\n".format(t)
f +="{}\n".format(o)
f +="\n" # 假设 m 为空字符串
f +="{}\n".format(c)
f +="{}\n".format(r)
# 过滤和排序 headers
b =function_l(u)
g =sorted(b.keys())
P =iter(g) # 假设 s["a"] 是一个返回迭代器的函数
try:while True:
try:
v =next(P)
except StopIteration:break
f +="{}:{}\n".format(v, b[v])
except Exception as O:
# 处理异常,假设 P.e 是处理异常的方法
pass
finally:
# 假设 P.f 是清理资源的方法
pass
# 处理 url
A = r"^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.csdn\.net)"
w = re.sub(A,"", n) # 假设已经导入了 re 模块
# 拼接 query string
f +=p(w, i) # 假设 p 是拼接 query string 的函数
# 生成签名
U = hmac.new(a.encode(), f.encode(), hashlib.sha256).digest()
k = base64.b64encode(U).decode() # 假设 d.a.HmacSHA256 和 d.a.enc.Base64 分别对应于 hmac.new 和 base64.b64encode
return k
# 示例使用
import http.cookiejar as cookielib
# "https://bizapi.csdn.net/download-console-api/v1/user/sources/getAuthorized?fileMd5=eaa25e77d592edc2123ee19a7356e04b&fileSize=572766609"
def make_headers(cookies, url):
nonce =createUuid()
signature =function_underscore({"url": url,"appSecret": app_secret,"headers":{"X-Ca-Key": app_key,"X-Ca-Nonce": nonce
}})print(f"signature is : {signature}")return{"Accept":"application/json, text/plain, */*","Accept-Encoding":"gzip, deflate, br","Accept-Language":"zh-CN,zh;q=0.9","Connection":"keep-alive","Cache-Control":"no-cache","Content-Type":"application/json","Origin":"https://upload.csdn.net","Pragma":"no-cache","Referer":"https://upload.csdn.net/creation/uploadResources","Sec-Ch-Ua-Mobile":"?0","Sec-Fetch-Dest":"empty","Sec-Fetch-Mode":"cors","Sec-Ch-Ua-Platform":'"macOS"',"Uri-Name":"feige","Cookie": cookies,"Sec-Fetch-Site":"same-site","User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36","X-Ca-Key": app_key,"X-Ca-Nonce": nonce,"X-Ca-Signature": signature,"X-Ca-Signature-Headers":"x-ca-key,x-ca-nonce",}if __name__ =="__main__":
nonce ="e6a20b79-1a23-44e1-b49c-5da538633be8" #createUuid() #"42ff7465-ec7c-4f46-bd3d-99d44c21cb83" #generate_uuid()
authorized_url ="https://bizapi.csdn.net/download-console-api/v1/user/sources/getAuthorized?fileMd5=eaa25e77d592edc2123ee19a7356e04b&fileSize=572766609"
signature =function_underscore({"url": authorized_url,"appSecret": app_secret,"headers":{"X-Ca-Key":"203803574","X-Ca-Nonce": nonce
}})print(nonce)print(signature)