Three ways to encrypt and decrypt python strings share of base64 win32com

  • 2020-04-02 13:22:37
  • OfStack

1. The easiest way is to use base64:


import base64
s1 = base64.encodestring('hello world')
s2 = base64.decodestring(s1)
print s1,s2
# aGVsbG8gd29ybGQ=n
# hello world

Note: this is the easiest way, but not safe enough, because if someone gets your ciphertext, they can decrypt it to get the plaintext


2. The second method is to use win32com.client


import win32com.client
def encrypt(key,content): # key: The key ,content: clear 
    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: The key ,content: cipher 
    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 you can set your own key. It is more secure than the first method.

3. There is also the encryption and decryption algorithm written by myself, such as:


def encrypt(key, s):
    b = bytearray(str(s).encode("gbk"))
    n = len(b) #  calculate  b  The number of bytes 
    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 0~15 Between the number of , add 65 Becomes a A-P  The character encoding of 
        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) #  To calculate  b  The number of bytes 
    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


Related articles: