①base64
Base64 is a method of representing arbitrary binary data in 64 characters.
When using Notepad to open exe, jpg, pdf files, we will see a lot of garbled code, because binary files contain many characters that cannot be displayed and printed, so if you want text processing software like Notepad to be able to process binary data, you need a conversion method from binary to string. Base64 is the most common binary encoding method.
import base64
s1 = base64.encodestring('hello world') #Note that this uses binary streams instead in Python 3, but it's still easy to use
s2 = base64.decodestring(s1)
print s1,s2
# aGVsbG8gd29ybGQ=\n
# hello world
This is the easiest way, but it's not safe enough, because if someone else gets your ciphertext, they can decrypt it to get the plaintext
②win32com.client
import win32com.client
def encrypt(key,content): # Key: key, content: clear text
EncryptedData = win32com.client.Dispatch('CAPICOM.EncryptedData')
EncryptedData.Algorithm.KeyLength = 5
EncryptedData.Algorithm.Name = 2
EncryptedData.SetSecret(key)
EncryptedData.Content = content
return EncryptedData.Encrypt()
def decrypt(key,content): # Key: key, content: ciphertext
EncryptedData = win32com.client.Dispatch('CAPICOM.EncryptedData')
EncryptedData.Algorithm.KeyLength = 5
EncryptedData.Algorithm.Name = 2
EncryptedData.SetSecret(key)
EncryptedData.Decrypt(content)
str = EncryptedData.Content
return str
s1 = encrypt('lovebread', 'hello world')
s2 = decrypt('lovebread', s1)
print s1,s2
# MGEGCSsGAQQBgjdYA6BUMFIGCisGAQQBgjdYAwGgRDBCAgMCAAECAmYBAgFABAgq
# GpllWj9cswQQh/fnBUZ6ijwKDTH9DLZmBgQYmfaZ3VFyS/lq391oDtjlcRFGnXpx
# lG7o
# hello world
This method is also very convenient, and can set their own key, more secure than the first method, is the first choice of encryption and decryption!
③ Write your own encryption and decryption algorithm
def encrypt(key, s):
b = bytearray(str(s).encode("gbk"))
n = len(b) # Find the number of bytes of b
c = bytearray(n*2)
j = 0
for i in range(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 are all numbers between 0 and 15, plus 65 becomes the encoding of A-P characters
c[j] = c1
c[j+1] = c2
j = j+2
return c.decode("gbk")
def decrypt(key, s):
c = bytearray(str(s).encode("gbk"))
n = len(c) # Count bytes of b
if n % 2 != 0:
return ""
n = n // 2
b = bytearray(n)
j = 0
for i in range(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
return b.decode("gbk")
More content access omegaxyz.com