1. The simplest method is to use base64:
Copy the Code code as follows:
Import Base64
S1 = base64.encodestring (' Hello World ')
S2 = base64.decodestring (S1)
Print S1,s2
# agvsbg8gd29ybgq=\n
# Hello World
Note: This is the simplest way, but not enough insurance, because if someone else gets your ciphertext, you can decrypt it yourself to get the plaintext.
2. The second method is to use the Win32com.client
Copy the Code code as follows:
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
Note: This method is also very convenient, and can set their own key, more secure than the first method, encryption and decryption is the preferred strategy!
3. There are also write encryption and decryption algorithms, such as:
Copy the Code code as follows:
def encrypt (key, s):
b = ByteArray (str (s). Encode ("GBK"))
n = len (b) # to find the number of bytes in 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//# B2 = c2*16 + C1
C1 = C1 + 65
C2 = C2 + # C1,C2 is the number between 0~15, plus 65 becomes the encoding of the a-p character
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) # Calculates the number of bytes in 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
Try
Return B.decode ("GBK")
Except
Return "Failed"
Key = 15
S1 = Encrypt (key, ' Hello World ')
S2 = Decrypt (key, S1)
Print S1, ' \ n ', s2
# HGKGDGDGAGPCIHAGNHDGLG
# Hello World