【发布时间】:2019-11-26 15:30:53
【问题描述】:
我正在编写一个简单的插件:
- 在加载时解密每个带有
.crypt扩展名的文件,提示输入密码 - 在保存时对其进行加密(如果在加载期间已经询问过密码,则不会重新询问密码;仅在将要保存的新文件时询问密码)
在下面的代码中,加密方法很简单:password是一个整数,加密移动+password的每个字符;解密移动-password 的每个字符(即,将password 减去每个字符的值)。这不是真正的加密,也不是安全的方法;当然我稍后会用AES加密或类似的方法来代替它,但是这个例子,这足以展示我在这个问题中遇到的问题。
import sublime_plugin, sublime
password = None
class PromptCryptCommand(sublime_plugin.WindowCommand):
def run(self):
panel = self.window.show_input_panel("Enter password", "2", self.on_done, None, None)
def on_done(self, pwd):
global password
password = int(pwd)
self.window.run_command(action)
class EncryptCommand(sublime_plugin.TextCommand):
def run(self, edit):
region = sublime.Region(0, self.view.size())
plaintext = self.view.substr(region)
ciphertext = ''.join([chr(ord(c)+password) for c in plaintext])
self.view.replace(edit, region, ciphertext)
class DecryptCommand(sublime_plugin.TextCommand):
def run(self, edit):
region = sublime.Region(0, self.view.size())
ciphertext = self.view.substr(region)
plaintext = ''.join([chr(ord(c)-password) for c in ciphertext])
self.view.replace(edit, region, plaintext)
class LoadSaveListener(sublime_plugin.EventListener):
def on_load(self, view):
global action
if view.file_name().endswith(".crypt"):
action = 'decrypt'
view.window().run_command('prompt_crypt')
def on_pre_save(self, view):
global action
if view.file_name().endswith(".crypt"):
if password == None: # password not entered yet, let's prompt for it
action = 'encrypt'
view.window().run_command('prompt_crypt')
else: # password already asked when file was loaded,
view.window().run_command('encrypt')
我遇到了这些我不知道如何解决的问题:
-
我们用 CTRL + S 多次重新保存,文件被重新保存,即重新加密。示例:
plaintext = 'abc' password = 2 after one CTRL+S, content = 'cde' after one more CTRS+S, content = 'efg' after one more CTRS+S, content = 'ghi' etc.我尝试使用
def on_post_save(view):解决此问题,并在保存操作后恢复未加密的明文。它有点工作,但是,即使文件被保存并且没有进行任何更改,Sublime 认为文件被修改了! (因为未加密的明文已经替换了保存的加密版本的文件)。 加载
.crypt文件时,密文显示在编辑器窗口,如何隐藏直到提示输入密码?
【问题讨论】:
-
出现在超棒的直播视频中:youtube.com/watch?v=ih1BBGwayLc :) 谢谢@OdatNurd!
标签: sublimetext3 sublimetext2 sublimetext sublime-text-plugin