encrypt.py


#!/usr/bin/env python
#
# Copyright 2012-2015 clowwindy
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from __future__ import absolute_import, division, print_function, \
    with_statement

import os
import sys
import hashlib
import logging

from shadowsocks import common
from shadowsocks.crypto import rc4_md5, openssl, sodium, table

#在 Python 中,在类的方法中,如果要引用全局变量,不需要使用 global 关键字声明。类可以访问全局范围内的变量,即使没有使用 global 声明。但是,如果你需要在类方法中修改全局变量的值,你需要在方法内使用 global 关键字声明该变量名,以便 Python 知道你是在引用全局变量而不是创建一个新的局部变量。

method_supported = {}
method_supported.update(rc4_md5.ciphers)
'''
ciphers = {
    'rc4-md5': (16, 16, create_cipher), 最后是函数 返回的openssl.OpenSSLCrypto对象
}
'''
#在将上面元组用字典的key找到时,返回值设定为m,那么m(2)就是最后的函数,会去对应方法的py文件中,寻找对应的create_cipher函数,在实际调用中,会出现类似于’‘’return m[2](method, key, iv, op)‘’‘的形式,最后返回一个OpenSSLCrypto的对象,并完成了构造函数的初始化
#在Encryptor类中,又会将这个对象封装到.cipher成员中,该成员依赖于构造函数中的加密方法以及password进行构造,key是由password结合md5生成出来的,iv是随机字符串,最后在Encryptor类初始化后,就实现出来
#在Encryptor类的加密解密操作中,已经高度的封装了,只使用encrypt方法,即Encryptor.encrypt(str)即可加密,在内部函数实现时,实际上是通过OpenSSLCrypto.update函数实现的。但是直接使用OpenSSLCrypto时,需要自己处理初始向量,在Encryptor中,如果没有初始向量会自己处理好,核心是iv_sent标志,如果为空,初次加密时则返回      return self.cipher_iv + self.cipher.update(buf) 将初始向量一并返回

method_supported.update(openssl.ciphers)
method_supported.update(sodium.ciphers)
method_supported.update(table.ciphers)

def random_string(length):
    return os.urandom(length)

cached_keys = {}

def try_cipher(key, method=None):
    Encryptor(key, method)

def EVP_BytesToKey(password, key_len, iv_len): #用密码生成key和iv
    # equivalent to OpenSSL's EVP_BytesToKey() with count 1
    # so that we make the same key and iv as nodejs version
    cached_key = '%s-%d-%d' % (password, key_len, iv_len)
    r = cached_keys.get(cached_key, None)
    if r:
        return r
    m = []
    i = 0
    while len(b''.join(m))  0:
            data = m[i - 1] + password #前一个md5加password 进而进一步生成md5 password用来生成原始数据 类似报文鉴别码?
        md5.update(data)
        m.append(md5.digest()) #m 是一个列表,md5.digest() 返回一个包含 MD5 摘要的原始字节串(bytes)。append() 方法将这个字节串添加到列表 m 中
        i += 1
    ms = b''.join(m)
    key = ms[:key_len]
    iv = ms[key_len:key_len + iv_len] #生成的128bit串联的字节串 前keylen作为key 后面的作为iv初始向量
    cached_keys[cached_key] = (key, iv)
    return key, iv

class Encryptor(object): #cipher.update封装到Encryptor.encrypt
    def __init__(self, password, method):
        self.password = password
        self.key = None
        self.method = method
        self.iv_sent = False #初始向量
        self.cipher_iv = b''
        self.decipher = None
        self.decipher_iv = None
        method = method.lower()
        self._method_info = self.get_method_info(method) # 'rc4-md5': (16, 16, create_cipher) 返回的是后面的元组
        if self._method_info:
            #是一个对象 OpenSSLCrypto对象 在openssl.py中
            self.cipher = self.get_cipher(password, method, 1,
                                          random_string(self._method_info[1])) #元组的第一个元素 此时op给定1 第四个 初始向量 随机字符串
        else:
            logging.error('method %s not supported' % method)
            sys.exit(1)

    def get_method_info(self, method):
        method = method.lower()
        m = method_supported.get(method)
        return m

    def iv_len(self):
        return len(self.cipher_iv)

    def get_cipher(self, password, method, op, iv): #生成初始向量 最后返回OpenSSlCrypto对象 返回值的update即可加密 封装到Encryptor.cipher 对类Encryptor而言,Encryptor.encrypt就是调用OpenSSlCrypto.update加密  关键是key和iv的生成 相较于OpenSSlCrypto不同
        password = common.to_bytes(password)
        m = self._method_info
        if m[0] > 0:
            key, iv_ = EVP_BytesToKey(password, m[0], m[1]) #keylength是m[0] 用的随机
        else:
            # key_length == 0 indicates we should use the key directly
            key, iv = password, b''
        self.key = key
        iv = iv[:m[1]]#取iv length的长度 这里是输入的随机字符串
        if op == 1:
            # this iv is for cipher not decipher
            self.cipher_iv = iv[:m[1]]
        return m[2](method, key, iv, op)
    #class OpenSSLCrypto(object):
    #def __init__(self, cipher_name, key, iv, op): 加密解密的初始向量 返回了一个OpenSSLCrypto对象 在openssl.py中

    def encrypt(self, buf):
        if len(buf) == 0:
            return buf
        if self.iv_sent: # self.cipher_iv = iv[:m[1]] 其中 key, iv_ = EVP_BytesToKey(password, m[0], m[1]) #keylength是m[0]
            return self.cipher.update(buf)
        else:
            self.iv_sent = True
            return self.cipher_iv + self.cipher.update(buf) #有别于OpenSSLCrypto的加密方式的处理

    def decrypt(self, buf):#没有get——decipher,也就没有 key, iv_ = EVP_BytesToKey(password, m[0], m[1]) 获取iv的过程,直接靠传入的字符串的前面来获得初始向量,实际上通过password计算也能得到?选择方式的问题
        if len(buf) == 0:
            return buf
        if self.decipher is None:#初始化
            decipher_iv_len = self._method_info[1] #元组的第二个元组
            decipher_iv = buf[:decipher_iv_len] #取出初始向量
            self.decipher_iv = decipher_iv
            self.decipher = self.get_cipher(self.password, self.method, 0,
                                            iv=decipher_iv)
            buf = buf[decipher_iv_len:]
            if len(buf) == 0:
                return buf
        return self.decipher.update(buf)

def gen_key_iv(password, method):
    method = method.lower()
    (key_len, iv_len, m) = method_supported[method]
    key = None
    if key_len > 0:
        key, _ = EVP_BytesToKey(password, key_len, iv_len)
    else:
        key = password
    iv = random_string(iv_len)
    return key, iv, m #m是class OpenSSLCrypto(object)

def encrypt_all_m(key, iv, m, method, data):
    result = []
    result.append(iv)
    cipher = m(method, key, iv, 1)
    result.append(cipher.update(data))
    return b''.join(result)

def dencrypt_all(password, method, data):
    result = []
    method = method.lower()
    (key_len, iv_len, m) = method_supported[method]#加密器OpenSSLCrtpto的函数名,也就是他的实现
    key = None
    if key_len > 0:
        key, _ = EVP_BytesToKey(password, key_len, iv_len)
    else:
        key = password
    iv = data[:iv_len]
    data = data[iv_len:]
    cipher = m(method, key, iv, 0)
    result.append(cipher.update(data))
    return b''.join(result), key, iv

def encrypt_all(password, method, op, data):
    result = []
    method = method.lower()
    (key_len, iv_len, m) = method_supported[method]
    key = None
    if key_len > 0:
        key, _ = EVP_BytesToKey(password, key_len, iv_len)
    else:
        key = password
    if op:
        iv = random_string(iv_len)
        result.append(iv) #iv的处理
    else:
        iv = data[:iv_len]
        data = data[iv_len:]#解密取出iv
    cipher = m(method, key, iv, op)
    result.append(cipher.update(data))
    return b''.join(result)

CIPHERS_TO_TEST = [
    'aes-128-cfb',
    'aes-256-cfb',
    'rc4-md5',
    'salsa20',
    'chacha20',
    'table',
]

def test_encryptor(): #从OpenSSLCryptO对象高一层 封装到了Encryptor对象 用的方法一样
    from os import urandom
    plain = urandom(10240)
    for method in CIPHERS_TO_TEST:
        logging.warn(method)
        encryptor = Encryptor(b'key', method)
        decryptor = Encryptor(b'key', method)
        cipher = encryptor.encrypt(plain) #会在初始时 在cipher(密文)的最前面 加上iv初始向量 这是在Encyyptor类将OpenSSLCrypto封装进去 使用函数处理的
        plain2 = decryptor.decrypt(cipher)
        assert plain == plain2

def test_encrypt_all():
    from os import urandom
    plain = urandom(10240)
    for method in CIPHERS_TO_TEST:
        logging.warn(method)
        cipher = encrypt_all(b'key', method, 1, plain) #涉及到初始向量的处理
        plain2 = encrypt_all(b'key', method, 0, cipher) #同上
        assert plain == plain2

def test_encrypt_all_m():
    from os import urandom
    plain = urandom(10240)
    for method in CIPHERS_TO_TEST:
        logging.warn(method)
        key, iv, m = gen_key_iv(b'key', method)#获取key, iv, m #m是class OpenSSLCrypto(object)
        cipher = encrypt_all_m(key, iv, m, method, plain) #密文
        plain2, key, iv = dencrypt_all(b'key', method, cipher) #iv是返回的初始向量 这里没有对比
        assert plain == plain2

if __name__ == '__main__':
    test_encrypt_all()
    test_encryptor()
    test_encrypt_all_m() #create_cipher的测试
#一次加解密

发表评论