zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python字符串加密解密的三种方法分享(base64win32com)

Python方法加密解密 字符串 分享 三种
2023-06-13 09:15:16 时间

1.最简单的方法是用base64:

复制代码代码如下:


importbase64

s1=base64.encodestring("helloworld")
s2=base64.decodestring(s1)
prints1,s2

#aGVsbG8gd29ybGQ=\n
#helloworld

Note:这是最简单的方法了,但是不够保险,因为如果别人拿到你的密文,也可以自己解密来得到明文


2.第二种方法是使用win32com.client

复制代码代码如下:


importwin32com.client
defencrypt(key,content):#key:密钥,content:明文
   EncryptedData=win32com.client.Dispatch("CAPICOM.EncryptedData")
   EncryptedData.Algorithm.KeyLength=5
   EncryptedData.Algorithm.Name=2
   EncryptedData.SetSecret(key)
   EncryptedData.Content=content
   returnEncryptedData.Encrypt()

defdecrypt(key,content):#key:密钥,content:密文
   EncryptedData=win32com.client.Dispatch("CAPICOM.EncryptedData")
   EncryptedData.Algorithm.KeyLength=5
   EncryptedData.Algorithm.Name=2
   EncryptedData.SetSecret(key)
   EncryptedData.Decrypt(content)
   str=EncryptedData.Content
   returnstr

s1=encrypt("lovebread","helloworld")
s2=decrypt("lovebread",s1)
prints1,s2

#MGEGCSsGAQQBgjdYA6BUMFIGCisGAQQBgjdYAwGgRDBCAgMCAAECAmYBAgFABAgq
#GpllWj9cswQQh/fnBUZ6ijwKDTH9DLZmBgQYmfaZ3VFyS/lq391oDtjlcRFGnXpx
#lG7o
#helloworld



Note:这种方法也很方便,而且可以设置自己的密钥,比第一种方法更加安全,是加密解密的首选之策!

3.还有就是自己写加密解密算法,比如:

复制代码代码如下:
defencrypt(key,s):
   b=bytearray(str(s).encode("gbk"))
   n=len(b)#求出b的字节数
   c=bytearray(n*2)
   j=0
   foriinrange(0,n):
       b1=b[i]
       b2=b1^key#b1=b2^key
       c1=b2%16
       c2=b2//16#b2=c2*16+c1
       c1=c1+65
       c2=c2+65#c1,c2都是0~15之间的数,加上65就变成了A-P的字符的编码
       c[j]=c1
       c[j+1]=c2
       j=j+2
   returnc.decode("gbk")

defdecrypt(key,s):
   c=bytearray(str(s).encode("gbk"))
   n=len(c)#计算b的字节数
   ifn%2!=0:
       return""
   n=n//2
   b=bytearray(n)
   j=0
   foriinrange(0,n):
       c1=c[j]
       c2=c[j+1]
       j=j+2
       c1=c1-65
       c2=c2-65
       b2=c2*16+c1
       b1=b2^key
       b[i]=b1
   try:
       returnb.decode("gbk")
   except:
       return"failed"

key=15
s1=encrypt(key,"helloworld")
s2=decrypt(key,s1)
prints1,"\n",s2

#HGKGDGDGAGPCIHAGNHDGLG
#helloworld