鱼C论坛

 找回密码
 立即注册
查看: 1969|回复: 17

js代码转变python

[复制链接]
发表于 2024-2-15 20:10:29 | 显示全部楼层 |阅读模式
50鱼币
  1. function encryptAES(IdVal) {
  2.     return CryptoJS.AES.encrypt(IdVal, 'lzYW5qaXVqa').toString();
  3. }
复制代码

这是一段js代码,python怎么才能完全复刻它的加密过程,要求完完全全!,出5rmb悬赏

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-2-15 20:10:41 | 显示全部楼层
要完全复刻JavaScript代码中的加密过程,我们首先需要安装`pycryptodome`库。可以使用以下命令来安装:

  1. pip install pycryptodome
复制代码


然后,你可以使用以下Python代码来实现与JavaScript代码相同的加密过程:

  1. from Crypto.Cipher import AES
  2. from Crypto.Util.Padding import pad
  3. from Crypto.Random import get_random_bytes
  4. import base64

  5. def encryptAES(IdVal):
  6.     key = b'lzYW5qaXVqa'
  7.     cipher = AES.new(key, AES.MODE_ECB)
  8.     ciphertext = cipher.encrypt(pad(IdVal.encode(), AES.block_size))
  9.     return base64.b64encode(ciphertext).decode()

  10. # 测试
  11. IdVal = 'your plaintext'
  12. encrypted = encryptAES(IdVal)
  13. print(encrypted)
复制代码


这段代码创建了一个AES密码器,并将其初始化为ECB模式(请注意,ECB模式不是最安全的模式,通常推荐使用更安全的模式,如CBC)。它还使用`pad`函数对输入进行填充,确保其长度是AES分组大小的倍数。然后,使用密钥对填充后的数据进行加密,并使用base64对结果进行编码。最后,返回经过base64编码的密文字符串。

请注意,由于JavaScript和Python之间存在一些差异,因此无法保证生成的密文字符串在两个环境中是完全相同的。但是,它们应该具有相同的解密结果。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2024-2-15 20:12:50 | 显示全部楼层
FishC 发表于 2024-2-15 20:10
要完全复刻JavaScript代码中的加密过程,我们首先需要安装`pycryptodome`库。可以使用以下命令来安装:

...

这段js代码是cbc模式加密吧
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-2-15 20:13:02 | 显示全部楼层
wyhpylc 发表于 2024-02-15 20:12
这段js代码是cbc模式加密吧


非常抱歉,我之前的回答有误。你是对的,这段JavaScript代码是使用CBC模式进行加密。以下是相应的Python代码来复刻这个加密过程:from Crypto.Cipher import AESfrom Crypto.Util.Padding import padfrom Crypto.Random import get_random_bytesimport base64def encryptAES(IdVal):    key = b'lzYW5qaXVqa'    iv = get_random_bytes(AES.block_size)    cipher = AES.new(key, AES.MODE_CBC, iv)    ciphertext = cipher.encrypt(pad(IdVal.encode(), AES.block_size))    return base64.b64encode(iv + ciphertext).decode()# 测试IdVal = 'your plaintext'encrypted = encryptAES(IdVal)print(encrypted)在这段代码中,我们首先生成一个随机的初始化向量(IV),并使用它和密钥创建一个AES密码器,并将其初始化为CBC模式。然后,与之前一样,我们使用`pad`函数对输入进行填充,并加密填充后的数据。最后,我们将IV和密文连接在一起,并使用base64对结果进行编码。请注意,由于每次运行都会生成一个新的随机IV,因此生成的密文字符串在不同运行之间是不同的。但是,解密操作应该能够正确执行。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-2-15 21:02:48 | 显示全部楼层
本帖最后由 学习编程中的Ben 于 2024-2-15 21:04 编辑
  1. from tkinter.filedialog import *
  2. from ttkbootstrap import *
  3. from ttkbootstrap.dialogs import *
  4. import tkinter.messagebox as mb
  5. import os
  6. import sys
  7. import pyperclip
  8. import logging
  9. from Crypto import Random
  10. from Crypto.PublicKey import RSA
  11. from Crypto.Cipher import PKCS1_v1_5 as PKCS1_cipher
  12. import base64
  13. from Crypto.Cipher import AES
  14. import random


  15. class main:
  16.     def __init__(self):
  17.         self.root = Window()
  18.         self.root.geometry("600x400")
  19.         self.root.title("加密器 -- 未命名")

  20.         # 创建主菜单栏
  21.         self.menubar = Menu(self.root)
  22.         # 创建子菜单
  23.         self.menuFile = Menu(self.menubar)
  24.         self.menuTools = Menu(self.menubar)
  25.         self.menuHelp = Menu(self.menubar)
  26.         # 将子菜单加入到主菜单栏
  27.         self.menubar.add_cascade(label="文件", menu=self.menuFile)
  28.         self.menubar.add_cascade(label="功能", menu=self.menuTools)
  29.         self.menubar.add_cascade(label="其他", menu=self.menuHelp)
  30.         self.filename = ""

  31.         # 文本框旁边的行号
  32.         self.login = 0
  33.         self.line_number = tk.Text(self.root, width=4, height=15, padx=5, pady=5)
  34.         self.line_number.pack(side=tk.LEFT, fill=tk.Y)
  35.         self.logger = logging.getLogger(__name__)

  36.         # 将主菜单栏加到根窗口
  37.         self.root["menu"] = self.menubar

  38.         # 文本框
  39.         self.w1 = Text(self.root, width=80, height=30, font=('consolas', 10))
  40.         self.w1.pack()

  41.         # 绑定快捷键
  42.         self.root.bind('<Alt-KeyPress-s>', self.saveFile)
  43.         self.root.bind('<Control-KeyPress-s>', self.save_same_File)
  44.         self.root.bind('<Control-KeyPress-o>', self.openFile)
  45.         self.root.bind('<Control-KeyPress-d>', self.all_die)

  46.         self.root.protocol("WM_DELETE_WINDOW", self.ask_to_exit)

  47.         # 显示菜单栏的功能
  48.         self.filemenu()
  49.         self.toolsmenu()
  50.         self.helpsmenu()

  51.         self.key = 0

  52.         # 在调用mainloop后调用sw
  53.         self.root.after(0, self.update_line_numbers)

  54.         # 总行数
  55.         self.line_count = 0

  56.         # 初始内容,用来比较文本框中的内容是否改变
  57.         self.old_text = self.w1.get(1.0, END)

  58.         # 保存状态:1是未保存,0是已保存
  59.         self.is_save = 1

  60.         # 让tkinter跑起来
  61.         self.root.mainloop()

  62.     # 当有内容改变,没保存却要退出时的提醒框
  63.     def ask_to_exit(self):
  64.         if self.old_text != self.w1.get(1.0, END):
  65.             result = mb.askyesnocancel("提示", "是否保存更改?")
  66.             if result is True:
  67.                 self.openFile()
  68.                 self.root.destroy()
  69.             elif result is False:
  70.                 self.root.destroy()
  71.         else:
  72.             self.root.destroy()

  73.     # 判断行数是否改变,若改变就重新加载行数
  74.     def update_line_numbers(self):
  75.         # 原来的行数
  76.         old_hang_num = 0

  77.         # 现在的行数
  78.         hang_num = self.w1.get("1.0", END).count("\n")

  79.         # 判断行数是否改变,若改变则刷新
  80.         if hang_num != old_hang_num:
  81.             # 将旧行数更新
  82.             old_hang_num = self.w1.get("1.0", END).count("\n")
  83.             self.line_count = old_hang_num
  84.             self.line_number.config(state=tk.NORMAL)
  85.             self.line_number.delete("1.0", tk.END)
  86.             for i in range(1, self.line_count + 1):
  87.                 self.line_number.insert(tk.END, "    " + str(i) + "\n")
  88.             self.line_number.config(state=tk.DISABLED)
  89.         self.root.after(10, self.update_line_numbers)

  90.     # 切换主题的页面
  91.     def themes(self):
  92.         pop = Toplevel()
  93.         pop.title("主题切换")
  94.         pop.geometry("600x200+200+200")

  95.         style = Style()
  96.         theme_names = ["litera", "morph", "darkly", "superhero", "solar", "vapor"]
  97.         theme_selection = Frame(pop)
  98.         # theme_selection.pack(fill=X, expand=YES)
  99.         theme_selection.place(x=10, y=10)
  100.         lbl = Label(theme_selection, text="选择主题:")
  101.         theme_cbo = Combobox(master=theme_selection, text=style.theme.name, values=theme_names, state="readonly")
  102.         theme_cbo.pack(padx=10, side=RIGHT)
  103.         # theme_cbo.place(x=170, y=20)
  104.         theme_cbo.current(theme_names.index(style.theme.name))
  105.         lbl.pack(side=RIGHT)

  106.         # lbl.place(x=70, y=20)

  107.         def change_theme(event):
  108.             theme_cbo_value = theme_cbo.get()
  109.             style.theme_use(theme_cbo_value)
  110.             theme_selected.configure(text=theme_cbo_value)
  111.             theme_cbo.selection_clear()

  112.         theme_cbo.bind('<<ComboboxSelected>>', change_theme)
  113.         theme_selected = Label(
  114.             master=theme_selection,
  115.             text="litera",
  116.             font="-size 24 -weight bold"
  117.         )

  118.         theme_selected.pack(side=LEFT)

  119.         def JieShu():
  120.             pop.destroy()
  121.             # 取消最小化,即为显示窗口
  122.             self.root.state(NORMAL)

  123.         button = Button(pop, text=" 完成<-戳我 ", command=JieShu, bootstyle=(SUCCESS, OUTLINE))
  124.         button.place(x=465, y=155)

  125.         pop.protocol("WM_DELETE_WINDOW", JieShu)
  126.         self.root.iconify()

  127.     def aes_encipher(self):
  128.         k = mb.askokcancel("提示", "本程序的AES不可加密中文\n建议用于加密RSA秘钥\n若强行使用,将会报错!!!\n是否进行加密?")
  129.         if k == False:
  130.             return 0

  131.         pop = Toplevel()
  132.         pop.title("AES加密")
  133.         pop.geometry("650x450+200+200")
  134.         def create_key():
  135.             key = ""
  136.             s = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
  137.                  "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
  138.             for i in range(16):
  139.                 key += s[random.randint(0, 35)]
  140.             return key

  141.         aes_key = create_key()

  142.         k = str(self.w1.get(1.0, END))

  143.         # AES加密
  144.         encrypted_text = self.aesEncrypt(aes_key, k)

  145.         Label(pop, text="密钥:", font=("microsoft yahei", 20)).place(x=50, y=50)

  146.         txt_key = Text(pop, height=3, width=35)
  147.         txt_key.place(x=180, y=40)
  148.         txt_key.insert('1.0', aes_key)
  149.         txt_key.config(state=DISABLED)

  150.         def save_key():
  151.             try:
  152.                 files = [('文本文档', '*.txt')]
  153.                 dir_name = 'mi_yao'
  154.                 if not os.path.exists(dir_name):
  155.                     os.mkdir(dir_name)
  156.                 file = asksaveasfile(title='保存文件', defaultextension=files, filetypes=files,
  157.                                      initialdir='.\\mi_yao\\')
  158.                 with open(file.name, 'wb') as f:
  159.                     f.write(aes_key.encode("utf-8"))
  160.                 print(file.name)
  161.             except AttributeError:
  162.                 pass

  163.         button_key = Button(pop, text="保存至文件", command=save_key)
  164.         button_key.place(x=300, y=130)

  165.         Label(pop, text="密文:", font=("microsoft yahei", 20)).place(x=50, y=230)

  166.         txt_encrypted = Text(pop, height=3, width=35)
  167.         txt_encrypted.place(x=180, y=220)
  168.         txt_encrypted.insert('1.0', encrypted_text)
  169.         txt_encrypted.config(state=DISABLED)

  170.         def save_encrypted():
  171.             try:
  172.                 files = [('加密文件', '*.wpk')]
  173.                 dir_name = 'mi_wen'
  174.                 if not os.path.exists(dir_name):
  175.                     os.mkdir(dir_name)
  176.                 file = asksaveasfile(title='保存文件', defaultextension=files, filetypes=files,
  177.                                      initialdir='.\\mi_wen\\')
  178.                 file.write(encrypted_text)
  179.                 print(file.name)
  180.             except AttributeError:
  181.                 pass

  182.         def finish():
  183.             pop.destroy()
  184.             self.root.state(NORMAL)

  185.         button_finish = Button(pop, text=" 完成<-戳我 ", command=finish)
  186.         button_finish.place(x=510, y=400)

  187.         pop.protocol("WM_DELETE_WINDOW", finish)
  188.         self.root.iconify()

  189.         button_save_encrypted = Button(pop, text="保存至文件", command=save_encrypted)
  190.         button_save_encrypted.place(x=300, y=310)

  191.     def aesEncrypt(self, key, data):
  192.         BLOCK_SIZE = 16  # Bytes
  193.         pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)

  194.         key = key.encode("utf8")
  195.         data = pad(data)
  196.         cipher = AES.new(key, AES.MODE_ECB)
  197.         result = cipher.encrypt(data.encode())
  198.         encodestrs = base64.b64encode(result)
  199.         enctext = encodestrs.decode("utf8")
  200.         return enctext

  201.     def aes_decipher(self):
  202.         pop = Toplevel()
  203.         pop.title("AES解密")
  204.         pop.geometry("450x210+200+200")

  205.         lab_key = Label(pop, text="密钥:", font=("microsoft yahei", 20))
  206.         lab_key.place(x=90, y=20)

  207.         button_upload_key = Button(pop, text="上传密钥文件", command=self.open_file_key)
  208.         button_upload_key.place(x=230, y=33)

  209.         frame = Frame(pop, width=390, height=1)
  210.         frame.place(x=30, y=140)

  211.         button_decrypt = Button(pop, text="   解密   ", command=lambda: self.decrypt(self.key))
  212.         button_decrypt.place(x=180, y=90)

  213.         button_finish = Button(pop, text=" 完成<-戳我 ", command=lambda: self.finish(pop))
  214.         button_finish.place(x=310, y=160)

  215.         pop.protocol("WM_DELETE_WINDOW", self.finish)
  216.         self.root.iconify()

  217.     def finish(self, win):
  218.         self.root.state(NORMAL)
  219.         win.destroy()

  220.     def open_file_data(self):
  221.         try:
  222.             file_path = askopenfilename(title='选择密文', filetypes=[('加密文件', '*.wpk')], initialdir='.\\mi_wen\\')
  223.             if file_path:
  224.                 with open(file_path, 'rb') as f:
  225.                     content = f.read()
  226.                     print(f.name)
  227.                     return content
  228.         except FileNotFoundError:
  229.             mb.showerror('错误', '你没有选择任何文件!')

  230.     def open_file_key(self):
  231.         try:
  232.             file_path = askopenfilename(title='选择密钥文件', filetypes=[('TXT', '*.txt')], initialdir='.\\mi_yao\\')
  233.             if file_path:
  234.                 with open(file_path, 'r') as f:
  235.                     key = f.read()
  236.                     print(f.name)
  237.                     self.key = key
  238.                     mmb.showinfo("上传成功", "上传成功")
  239.         except FileNotFoundError:
  240.             mb.showerror("错误", "你没有选择任何文件!")

  241.     def decrypt(self, key):
  242.         encrypted_data = self.w1.get(1.0, END)
  243.         decrypted_text = self.aesDecrypt(key, encrypted_data)
  244.         self.w1.delete("1.0", "end")
  245.         self.w1.insert(INSERT, decrypted_text)
  246.         mb.showinfo(title="解密成功", message="解密成功!!!")

  247.     def aesDecrypt(self, key, data):
  248.         BLOCK_SIZE = 16  # Bytes
  249.         unpad = lambda s: s[: -ord(s[len(s) - 1:])]

  250.         key = key.encode("utf8")
  251.         data = base64.b64decode(data)
  252.         cipher = AES.new(key, AES.MODE_ECB)
  253.         text_decrypted = unpad(cipher.decrypt(data))
  254.         text_decrypted = text_decrypted.decode("utf8")
  255.         return text_decrypted

  256.     # RSA加密页面
  257.     def rsa_encipher(self):

  258.         pop = Toplevel()
  259.         pop.title("rsa加密")
  260.         pop.geometry("650x450+200+200")

  261.         k = self.w1.get(1.0, END)
  262.         print(k)
  263.         print(type(k))

  264.         # RSA加密
  265.         test = self.RsaCode()
  266.         res_en = test.long_encrypt(k)
  267.         private_key = test.rsa_private_key  # 密钥

  268.         Label(pop, text="密钥:", font=("microsoft yahei", 20)).place(x=50, y=50)

  269.         txt = Text(pop, height=3, width=35)
  270.         txt.place(x=180, y=40)
  271.         txt.insert('1.0', private_key)
  272.         txt.config(state=DISABLED)

  273.         def the_save():
  274.             try:
  275.                 files = [('文本文档', '*.txt')]
  276.                 dir_name = 'mi_yao'
  277.                 if not os.path.exists(dir_name):  # os模块判断并创建
  278.                     os.mkdir(dir_name)
  279.                 file = asksaveasfile(title='保存文件', defaultextension=files, filetypes=files,
  280.                                      initialdir='.\\mi_yao\\')
  281.                 with open(file.name, 'wb') as f:
  282.                     f.write(private_key.encode("utf-8"))
  283.                 print(file.name)
  284.             except AttributeError:
  285.                 pass

  286.         button = Button(pop, text="保存至文件", command=the_save, bootstyle=(PRIMARY, OUTLINE))
  287.         button.place(x=300, y=130)

  288.         Label(pop, text="密文:", font=("microsoft yahei", 20)).place(x=50, y=230)

  289.         txt = Text(pop, height=3, width=35)
  290.         txt.place(x=180, y=220)
  291.         txt.insert('1.0', str(res_en))
  292.         txt.config(state=DISABLED)

  293.         def the_save1():
  294.             try:
  295.                 files = [('加密文件', '*.wpk')]
  296.                 dir_name = 'mi_wen'
  297.                 if not os.path.exists(dir_name):  # os模块判断并创建
  298.                     os.mkdir(dir_name)
  299.                 file = asksaveasfile(title='保存文件', defaultextension=files, filetypes=files,
  300.                                      initialdir='.\\mi_wen\\')
  301.                 file.write(str(res_en))
  302.                 print(file.name)
  303.             except AttributeError:
  304.                 pass

  305.         def JieShu():
  306.             pop.destroy()
  307.             # 取消最小化,即为显示窗口
  308.             self.root.state(NORMAL)

  309.         button = Button(pop, text=" 完成<-戳我 ", command=JieShu, bootstyle=(SUCCESS, OUTLINE))
  310.         button.place(x=510, y=400)

  311.         pop.protocol("WM_DELETE_WINDOW", JieShu)
  312.         self.root.iconify()

  313.         button = Button(pop, text="保存至文件", command=the_save1, bootstyle=(WARNING, OUTLINE))
  314.         button.place(x=300, y=310)

  315.     # RSA加密函数
  316.     class RsaCode:
  317.         def __init__(self):
  318.             random_generator = Random.new().read
  319.             rsa = RSA.generate(1024, random_generator)
  320.             self.rsa_private_key = str(rsa.exportKey())[2:-1].replace("\\n", "\n")
  321.             self.rsa_public_key = str(rsa.public_key().exportKey())[2:-1].replace("\\n", "\n")
  322.             # print(self.rsa_private_key)
  323.             # print(type(self.rsa_private_key))
  324.             # print(self.rsa_public_key)
  325.             # print(type(self.rsa_public_key))

  326.         def encrypt(self, msg):
  327.             msg = msg.encode('utf-8')
  328.             rsakey = RSA.importKey(self.rsa_public_key)
  329.             cipher = PKCS1_cipher.new(rsakey)
  330.             cipher_text = base64.b64encode(cipher.encrypt(msg))
  331.             return cipher_text

  332.         def decrypt(self, cipher_text):
  333.             rsakey = RSA.importKey(self.rsa_private_key)
  334.             cipher = PKCS1_cipher.new(rsakey)
  335.             random_generator = Random.new().read
  336.             text = cipher.decrypt(base64.b64decode(cipher_text), random_generator)
  337.             return text.decode('utf8')

  338.         def long_encrypt(self, msg):
  339.             msg = msg.encode('utf-8')
  340.             length = len(msg)
  341.             default_length = 117
  342.             # 公钥加密
  343.             pubobj = PKCS1_cipher.new(RSA.importKey(self.rsa_public_key))
  344.             # 长度不用分段
  345.             if length < default_length:
  346.                 return base64.b64encode(pubobj.encrypt(msg))
  347.             # 需要分段
  348.             offset = 0
  349.             res = []
  350.             while length - offset > 0:
  351.                 if length - offset > default_length:
  352.                     res.append(pubobj.encrypt(msg[offset:offset + default_length]))
  353.                 else:
  354.                     res.append(pubobj.encrypt(msg[offset:]))
  355.                 offset += default_length
  356.             byte_data = b''.join(res)
  357.             return base64.b64encode(byte_data)

  358.         def long_decrypt(self, msg):
  359.             print(msg)
  360.             print(type(msg))
  361.             msg = base64.b64decode(msg)
  362.             print(msg)
  363.             length = len(msg)
  364.             default_length = 128
  365.             # 私钥解密
  366.             priobj = PKCS1_cipher.new(RSA.importKey(self.rsa_private_key))
  367.             # 长度不用分段
  368.             if length < default_length:
  369.                 return b''.join(priobj.decrypt(msg, b'xyz'))
  370.             # 需要分段
  371.             offset = 0
  372.             res = []
  373.             while length - offset > 0:
  374.                 if length - offset > default_length:
  375.                     res.append(priobj.decrypt(msg[offset:offset + default_length], b'xyz'))
  376.                 else:
  377.                     res.append(priobj.decrypt(msg[offset:], b'xyz'))
  378.                 offset += default_length

  379.             return b''.join(res).decode('utf8')

  380.     # RSA解密函数
  381.     class Rsa_class_know:
  382.         def __init__(self, w1, root, RsaCode):
  383.             self.pop = Toplevel()
  384.             self.pop.title("rsa解密")
  385.             self.pop.geometry("450x210+200+200")

  386.             self.RsaCode = RsaCode
  387.             self.w1 = w1
  388.             self.root = root
  389.             self.mi_wen = ""
  390.             self.mi_yao = ""

  391.             lab = Label(self.pop, text="密钥:", font=("microsoft yahei", 20))
  392.             # lab.config(fg="red")
  393.             lab.place(x=90, y=20)
  394.             button = Button(self.pop, text="上传密钥文件", command=self.OF_mi_yao, bootstyle=(DANGER, OUTLINE))
  395.             # button.config(background="red")
  396.             button.place(x=230, y=33)

  397.             frame = Frame(self.pop, width=390, height=1)
  398.             frame.place(x=30, y=140)

  399.             button = Button(self.pop, text="   解密   ", command=self.know, bootstyle=(INFO, OUTLINE))
  400.             button.place(x=180, y=90)

  401.             button = Button(self.pop, text=" 完成<-戳我 ", command=self.JieShu, bootstyle=(SUCCESS, OUTLINE))
  402.             button.place(x=310, y=160)

  403.             self.pop.protocol("WM_DELETE_WINDOW", self.JieShu)
  404.             root.iconify()

  405.         def OF_mi_wen(self):
  406.             c = askopenfilename(title='选择密文', filetypes=[('加密文件', '*.wpk')], initialdir='.\\mi_wen\\')
  407.             try:
  408.                 # 以GBK编码打开
  409.                 try:
  410.                     with open(c) as f:
  411.                         content = f.read()
  412.                         print(f.name)
  413.                         print(content)
  414.                         self.mi_wen = content
  415.                 except FileNotFoundError:
  416.                     mb.showerror('错误', '你没有选择任何文件!')
  417.             except UnicodeDecodeError:
  418.                 # 以UTF-8编码打开
  419.                 with open(c) as f:
  420.                     content = f.read()
  421.                     print(f.name)
  422.                     print(content)
  423.                     self.mi_wen = content

  424.         def OF_mi_yao(self):
  425.             try:
  426.                 c = askopenfilename(title='选择秘钥文件', filetypes=[('TXT', '*.txt')], initialdir='.\\mi_yao\\')
  427.                 if c:
  428.                     self.mi_yao = c
  429.                     mb.showinfo("上传成功", "上传成功")
  430.             except FileNotFoundError:
  431.                 mb.showerror("错误", "你没有选择任何文件!")

  432.         def know(self):
  433.             test = self.RsaCode()
  434.             with open(self.mi_yao, "r") as f:
  435.                 self.mi_yao = f.read()
  436.             test.rsa_private_key = self.mi_yao.replace("\\n", "\n")
  437.             print("**************" + test.rsa_private_key)
  438.             self.mi_wen = self.w1.get(1.0, END)
  439.             res_de = test.long_decrypt(self.mi_wen[2:-1].encode("utf-8"))
  440.             print('res_de', res_de)
  441.             self.w1.delete("1.0", "end")
  442.             self.w1.insert(INSERT, res_de)
  443.             mb.showinfo(title="解密成功", message="解密成功!!!")
  444.             # self.JieShu()

  445.         def JieShu(self):
  446.             self.root.state(NORMAL)
  447.             self.pop.destroy()
  448.             # 取消最小化,即为显示窗口

  449.     # RSA解密调用
  450.     def rsa_know(self):
  451.         self.root.iconify()
  452.         b = self.Rsa_class_know(self.w1, self.root, self.RsaCode)

  453.     # 打开文件
  454.     def openFile(self, pointless=None):
  455.         global filename
  456.         c = askopenfilename(title='打开一个文件',
  457.                             filetypes=[('全部文件(图片等无法打开)', '*.*'), ('TXT', '*.txt'), ('Word', '*.word'),
  458.                                        ('加密文件', '*.wpk'), ('Python文件', '*.py'), ('C++文件', '*.cpp'),
  459.                                        ('Java文件', '*.java'), ('C文件', '*.c')], initialdir='.\\')
  460.         # print(c.name)
  461.         try:
  462.             # 以GBK编码打开
  463.             try:
  464.                 with open(c) as f:
  465.                     content = f.read()
  466.                     self.w1.delete("1.0", "end")
  467.                     self.w1.insert(INSERT, content)
  468.                     self.filename = f.name
  469.                     self.root.title("加密器 -- " + self.filename)
  470.                     print(f.name)
  471.             except FileNotFoundError:
  472.                 mb.showerror('错误', '你没有选择任何文件!')
  473.         except UnicodeDecodeError:
  474.             # 以UTF-8编码打开
  475.             with open(c, encoding='utf-8') as f:
  476.                 content = f.read()
  477.                 self.w1.delete("1.0", "end")
  478.                 self.w1.insert(INSERT, content)
  479.                 self.filename = f.name
  480.                 self.root.title("加密器 -- " + self.filename)
  481.                 print(f.name)
  482.         self.old_text = self.w1.get("1.0", END)

  483.     # 另存为文件
  484.     def saveFile(self, pointless=None):
  485.         try:
  486.             files = [('TXT', '*.txt'), ('Word', '*.word'),
  487.                      ('Python文件', '*.py'), ('C++文件', '*.cpp'),
  488.                      ('Java文件', '*.java'), ('C文件', '*.c')]
  489.             dir_name = 'wenben'
  490.             if not os.path.exists(dir_name):  # os模块判断并创建
  491.                 os.mkdir(dir_name)
  492.             file = asksaveasfile(title='保存文件', defaultextension=files, filetypes=files, initialdir='.\\wenben\\')
  493.             file.write(self.w1.get(1.0, END))
  494.             file.close()
  495.             file.write(self.w1.get(1.0, END))

  496.             self.filename = file.name
  497.             print(file.name)
  498.         except AttributeError:
  499.             pass













  500.     # 保存文件
  501.     def save_same_File(self, pointless=None):
  502.         try:
  503.             with open(self.filename, "w") as file:
  504.                 file.write(self.w1.get(1.0, END))
  505.             mb.showinfo('成功', '保存完毕!')
  506.         except FileNotFoundError:
  507.             mb.showerror("错误", "请打开文件或选择另存为!")
  508.         self.old_text = self.w1.get(1.0, END)

  509.     # 关于
  510.     def about(self):
  511.         mb.showinfo(title="关于", message="由学习编程中的Ben制作\nQQ:1778454661")

  512.     # "文件"子菜单
  513.     def filemenu(self):
  514.         # 添加菜单项
  515.         # self.menuFile.add_command(label="新建 Ctrl+N", command=self.new)
  516.         self.menuFile.add_command(label="打开  Ctrl+O", command=self.openFile)
  517.         # root.bind("<Control-n>", openFile)

  518.         self.menuFile.add_command(label="保存  Ctrl+S", command=self.save_same_File)
  519.         self.menuFile.add_command(label="另存为  Alt+S", command=self.saveFile)
  520.         self.menuFile.add_separator()  # 添加分割线
  521.         #self.menuFile.add_command(label="关闭窗口 Alt+D", command=self.destroy)
  522.         self.menuFile.add_command(label="退出 Alt+Q", command=self.all_die)

  523.     # "功能"子菜单
  524.     def toolsmenu(self):
  525.         self.menuTools.add_command(label="RSA加密", command=self.rsa_encipher)
  526.         self.menuTools.add_command(label="RSA解密", command=self.rsa_know)
  527.         self.menuTools.add_command(label="AES加密", command=self.aes_encipher)
  528.         self.menuTools.add_command(label="AES解密", command=self.aes_decipher)

  529.     # "帮助"子菜单
  530.     def helpsmenu(self):
  531.         self.menuHelp.add_command(label="切换主题", command=self.themes)
  532.         self.menuHelp.add_separator()
  533.         self.menuHelp.add_command(label="关于", command=self.about)

  534.     # 新窗口
  535.     # def new(self, m=0):
  536.     #     main()

  537.     # 结束程序
  538.     def all_die(self, m=0):
  539.         sys.exit()

  540.     # 退出窗口(仅关闭一个窗口)
  541.     def destroy(self, m=0):
  542.         self.root.destroy()


  543. main()
复制代码


去看我AES加密那一部分.代码中有少量注释,勉强看看
第156~第177行

点评

我很赞同!: 5.0
我很赞同!: 5
我去,失踪人口回归  发表于 2024-2-20 08:35

评分

参与人数 2荣誉 +8 鱼币 +5 贡献 +3 收起 理由
alwonwang + 3 + 5 我去,失踪人口回归
歌者文明清理员 + 5 + 3 感谢楼主无私奉献!

查看全部评分

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-2-15 21:21:07 | 显示全部楼层
我去,失踪人口回归
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2024-2-15 21:24:17 From FishC Mobile | 显示全部楼层
liuhongrun2022 发表于 2024-2-15 21:21
我去,失踪人口回归

嘻嘻 这不马上中考吗,来的少了
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2024-2-15 21:31:28 From FishC Mobile | 显示全部楼层
学习编程中的Ben 发表于 2024-2-15 21:02
去看我AES加密那一部分.代码中有少量注释,勉强看看
第156~第177行

这个是随机密钥吧,这个js代码是特定key,我问了一下午gpt都没问出方法来,用js代码加密的用base64解码开头还有个salted,而且这个js代码没有lv,我不确定它的lv是随机还是0,还有密钥补充也是,不知道这个js库是怎么把不是1的补充成128位的(苦笑)
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-2-16 08:51:08 From FishC Mobile | 显示全部楼层
学习编程中的Ben 发表于 2024-2-15 21:02
去看我AES加密那一部分.代码中有少量注释,勉强看看
第156~第177行

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-2-16 09:30:38 From FishC Mobile | 显示全部楼层
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes
import base64

def encryptAES(IdVal):
    key = b'lzYW5qaXVqa'
    cipher = AES.new(key, AES.MODE_CBC, IV=get_random_bytes(16))
    ct_bytes = cipher.encrypt(pad(IdVal.encode('utf-8'), AES.block_size))
    iv = base64.b64encode(cipher.iv).decode('utf-8')
    ct = base64.b64encode(ct_bytes).decode('utf-8')
    return iv + ct

# 测试
encrypted_data = encryptAES("test123")
print(encrypted_data)
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2024-2-16 10:38:30 | 显示全部楼层
陶远航 发表于 2024-2-16 09:30
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Random import get_ra ...

aes的密钥要求是128位吧,这个js库会对长度不足的密钥进行补充,这个代码没有密钥补充
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-2-19 12:34:49 | 显示全部楼层
  1. pip install pyexecjs
复制代码
  1. import execjs

  2. jstext=‘’‘
  3. function encryptAES(IdVal) {
  4.     return CryptoJS.AES.encrypt(IdVal, 'lzYW5qaXVqa').toString();
  5. }
  6. ’‘’
  7. ctx=execjs.compile(jstext)#编译js代码
  8. a=ctx.call("encryptAES","xxxx")#第一个参数为函数名,第二个参数为调用函数所需要的参数

  9. print(a)
复制代码


取巧了一点,直接用python跑js代码.不知道是不是你想要的,仅供参考
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-2-19 12:57:37 | 显示全部楼层
我搞一下,等等
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-2-19 13:03:34 | 显示全部楼层
为了使用Python完全复制上述的JavaScript函数encryptAES,你可以使用pycryptodome这个库,这是一个第三方的库,提供给我们很多加密算法的实现,包含AES。下面的代码展示了如何用Python实现一个类似的功能:

  1. from Crypto.Cipher import AES
  2. from Crypto.Util.Padding import pad
  3. from base64 import b64encode
  4. def encrypt_aes(id_val, key):
  5.     # 使用16位的密钥(128位)。如果密钥长度不是16位,则需要进行相应的截取或填充。
  6.     key = key.encode('utf-8')[:16]  # 取密钥的前16个字节
  7.     # 需要被加密的数据必须是16的倍数,使用pad函数自动补充
  8.     data_to_encrypt = pad(id_val.encode('utf-8'), AES.block_size)
  9.     # 使用CBC模式
  10.     cipher = AES.new(key, AES.MODE_CBC)
  11.     # 加密数据
  12.     encrypted_data = cipher.encrypt(data_to_encrypt)
  13.     # 得到加密后的数据需要编码成base64字符串,因为CryptoJS的toString方法默认输出base64字符串
  14.     encrypted_data_b64 = b64encode(encrypted_data).decode('utf-8')
  15.     # 取出初始化向量IV,并将其转换成base64字符串
  16.     iv_b64 = b64encode(cipher.iv).decode('utf-8')
  17.     # 返回IV和加密数据的组合,这种格式在解密时可以提取出IV和加密后的数据
  18.     return iv_b64 + ':' + encrypted_data_b64
  19. # 函数调用示例
  20. encrypted_message = encrypt_aes("SomeDataToEncrypt", "lzYW5qaXVqa")
  21. print(encrypted_message)
复制代码


请确保你已经安装了pycryptodome,如果没有的话,你可以使用
  1. pip install pycryptodome
复制代码
命令来安装这个库。
上面的函数encrypt_aes默认使用编码为UTF-8的字符串作为输入,使用提供的密钥对其进行AES加密,并返回一个base64编码的加密字符串。注意,由于JavaScript中通常会包括IV(初始化向量),在加密时我们也会生成一个IV,并将其和加密后的数据一起返回。
如果你需要和CryptoJS进行互操作,确保你使用了相同的密钥和IV,同时处理加密后的数据格式,以便JavaScript可以正确地解密。



求最佳
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2024-2-20 21:09:41 | 显示全部楼层
zhangchenyvn 发表于 2024-2-19 13:03
为了使用Python完全复制上述的JavaScript函数encryptAES,你可以使用pycryptodome这个库,这是一个第三方的 ...

ValueError: Incorrect AES key length (11 bytes)
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2024-2-20 21:12:06 | 显示全部楼层
zhangchenyvn 发表于 2024-2-19 13:03
为了使用Python完全复制上述的JavaScript函数encryptAES,你可以使用pycryptodome这个库,这是一个第三方的 ...

b'lzYW5qaXVqa'
这是encode后的值
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2024-2-20 21:15:45 | 显示全部楼层
zhangchenyvn 发表于 2024-2-19 13:03
为了使用Python完全复制上述的JavaScript函数encryptAES,你可以使用pycryptodome这个库,这是一个第三方的 ...

我按照那个js库进行密钥补足后,输出的密文还是无法解开……
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-25 13:21

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表