对称加密算法使用示例

news2024/11/14 13:47:17

Demo包括以下对称加密算法组合
在这里插入图片描述
备注:XTS仅支持AES128和AES256,不支持AES192

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import cmac
from cryptography.hazmat.primitives.ciphers.aead import AESCCM
from Crypto.Cipher import DES
from Crypto.Cipher import DES3
from Cryptodome.Util import Counter

plaintext = '6BC1BEE22E409F96E93D7E117393172AAE2D8A571E03AC9C9EB76FAC45AF8E5130C81C46A35CE411E5FBC1191A0A52EFF69F2445DF4F9B17AD2B417BE66C3710'
key64 = '2B7E151628AED2A6'
key128 = '2B7E151628AED2A6ABF7158809CF4F3C'
key192 = '0123456789ABCDEF23456789ABCDEF01456789ABCDEF0123'
key256 = '603DEB1015CA71BE2B73AEF0857D77811F352C073B6108D72D9810A30914DFF4'
key512 = '603DEB1015CA71BE2B73AEF0857D77811F352C073B6108D72D9810A30914DFF4603DEB1015CA71BE2B73AEF0857D77811F352C073B6108D72D9810A30914DFAA'
iv = '000102030405060708090A0B0C0D0E0F'
iv64 = '0001020304050607'
xts_iv = '00000000000000120123456789ABCDEF'
desCtr_iv = '00010203040506'

ciphertext_AES128_Ecb = '3AD77BB40D7A3660A89ECAF32466EF97F5D3D58503B9699DE785895A96FDBAAF43B1CD7F598ECE23881B00E3ED0306887B0C785E27E8AD3F8223207104725DD4'
ciphertext_AES128_Cbc = '7649ABAC8119B246CEE98E9B12E9197D5086CB9B507219EE95DB113A917678B273BED6B8E3C1743B7116E69E222295163FF1CAA1681FAC09120ECA307586E1A7'
ciphertext_AES128_Cfb = '3B3FD92EB72DAD20333449F8E83CFB4AC8A64537A0B3A93FCDE3CDAD9F1CE58B26751F67A3CBB140B1808CF187A4F4DFC04B05357C5D1C0EEAC4C66F9FF7F2E6'
ciphertext_AES128_Ofb = '3B3FD92EB72DAD20333449F8E83CFB4A7789508D16918F03F53C52DAC54ED8259740051E9C5FECF64344F7A82260EDCC304C6528F659C77866A510D9C1D6AE5E'
ciphertext_AES128_Ctr = '3B3FD92EB72DAD20333449F8E83CFB4A010C041999E03F36448624483E582D0EA62293CFA6DF74535C354181168774DF2D55A54706273C50D7B4F8A8CDDC6ED7'
ciphertext_AES128_Xts = '076515D03AB09CE841B5C0BE1B91E173A3FEBC9A5CAF188A5FA24659674D7931D9415D429FBAF8EC29F29C5FDC4385234FB79CEB238467C9E28505F1A2002D6A'

ciphertext_AES192_Ecb = '7724811607BA7314F4978917BB95EF7DB3A20E7E9E4E0A25201CF48AC4511F3ACC48545D5B7B9D5DBE5BF6F82C3D362C972B98E85E4639946318AA4DDA036E49'
ciphertext_AES192_Cbc = 'FAC92E86CE086D2F337F8CE30FE51424CA8B401E01C0B286ED2CAAA18634163CA20E043F27A9BF8037B90949CF8D940EF00690D0D6442DB29B7F47FA349FF646'
ciphertext_AES192_Cfb = '06E82581F9A5A283E0E65CE07CC8AC061535DC944C9647A000571D1D0E64C1B698013E0A15764A735CAAE3D29D9571F3B0C5F2018FC493A93D56254461F2B0FA'
ciphertext_AES192_Ofb = '06E82581F9A5A283E0E65CE07CC8AC061AE27B400A153F17A55C2048A213E17EF8BF38CC0DBC94716939444023D4BFF152A97E2ABBB44C2E129D9295DD1040DA'
ciphertext_AES192_Ctr = '06E82581F9A5A283E0E65CE07CC8AC06941D0E4F560FB559B6CBE9BB899AE2F251E6CD8B9FB0064FD2A87F48CD6755AF195409785AAAAA33FF9331D596EC8637'

ciphertext_AES256_Ecb = 'F3EED1BDB5D2A03C064B5A7E3DB181F8591CCB10D410ED26DC5BA74A31362870B6ED21B99CA6F4F9F153E7B1BEAFED1D23304B7A39F9F3FF067D8D8F9E24ECC7'
ciphertext_AES256_Cbc = 'F58C4C04D6E5F1BA779EABFB5F7BFBD69CFC4E967EDB808D679F777BC6702C7D39F23369A9D9BACFA530E26304231461B2EB05E2C39BE9FCDA6C19078C6A9D1B'
ciphertext_AES256_Cfb = 'DC7E84BFDA79164B7ECD8486985D386039FFED143B28B1C832113C6331E5407BDF10132415E54B92A13ED0A8267AE2F975A385741AB9CEF82031623D55B1E471'
ciphertext_AES256_Ofb = 'DC7E84BFDA79164B7ECD8486985D38604FEBDC6740D20B3AC88F6AD82A4FB08D71AB47A086E86EEDF39D1C5BBA97C4080126141D67F37BE8538F5A8BE740E484'
ciphertext_AES256_Ctr = 'DC7E84BFDA79164B7ECD8486985D3860D577788B8D8A85745513A5D50F821F30FFE96D5CF54B238DCC8D6783A87F3BEAE9AF546344CB9CA4D1E553FFC06BC73E'
ciphertext_AES256_Xts = 'A97569C77B139625C2E6E8E61D13AA608A861433A39D2D38598ACF48A18FF5AD09B4AEFE8F8CDFD41A0189207137680D635AD688640A5614157534F47F5533CF'

ciphertext_SM4_Ecb = 'A51411FF04A711443891FCE7AB842A29D5B50F46A9A730A0F590FFA776D99855C9A86A4D71447F4E873ADA4F388AF9B92B25557B50514D155939E6EC940AD90E'
ciphertext_SM4_Cbc = 'AC529AF989A62FCE9CDDC5FFB84125CAB168DD69DB3C0EEA1AB16DE6AEA43C592C15567BFF8F707486C202C7BE59101F74A629B350CD7E11BE99998AF5206D6C'
ciphertext_SM4_Cfb = 'BC710D762D070B26361DA82B54565E46A4CD42786A3A5293A3C6CBC123F0B354407055B1C1A5D9982C187D5C3EE0CED84B82C40F2F0A4E0341797F1F307B8047'
ciphertext_SM4_Ofb = 'BC710D762D070B26361DA82B54565E4607A0C62834740AD3240D239125E11621D476B21CC9F04951F0741D2EF9E094981584FC142BF13AA626B82F9D7D076CCE'
ciphertext_SM4_Ctr = 'BC710D762D070B26361DA82B54565E46B02B3DBDDD50D5B458AECCB25DA105E16AD70BC01175AD43B0806A2E7B9CA545602459A06B7D130DDE42A3E0476818D2'

ciphertext_DES_Ecb = '6EDFD1B7A001CD17CDC57FF79CF872D01197A6D213594F7A3D7C7CECBCDDD2203A758B06752E180D550FDD575AF13B94183D4DA11E14756B0FD9D96416A06014'
ciphertext_DES_Cbc = '39721ED4246D188FF8BAA61A8E381C3BF7312B53C854C0C6D99BF1273B5C92CC72273D9591C9C47276982AF946CB79B1C2A22E1D7F2858C2D7B87DDB949F153C'
ciphertext_DES_Cfb = '7BDADBA789E0984284EB8EC346A42FD9F72B34F5B41CF57C72636F6582A9C016DB50881BC7893DD6B6883AD4B62CBF783F98EEF111D3EDBF38E287E60E05A39F'
ciphertext_DES_Ofb = '7BDADBA789E09842B6B19AC5BD431B5959069471421C991D3A59D3E0CE0B97D753CC581E0A161343C6650DA9594C750F94A22AC6B3E572330CD66E8581727075'
ciphertext_DES_Ctr = '0939B5447B883ADBCDBD2D925AE2BA0053C47E620DB253A4D5583431D8AD52232B41D12126ECEDB6EE9964679EB52DDAE37F50C79DBA5D16BD30243E41CC30C4'


ciphertext_TDES_Ecb = '714772F339841D34267FCC4BD2949CC3EE11C22A576A303876183F99C0B6DE873583992D38124EB5C6FCD81A0054E2DF6C4A09AC778EE1400533463C6F961F25'
ciphertext_TDES_Cbc = 'DF4FB48A5C3414FA340A1553EFAE84317B4C6AAB8845FB9247EE5E08514DD2BC515A4AA25332ECA936EE6EBE03EE555DD7D72374BD3D3D150F8AB00F19A5AE97'
ciphertext_TDES_Cfb = '5BF32CB19369FAD61BDCF7FAE406C8882603F96CAF26BA99ACA1B4CCA093BB07327B3F0AEFE4A14C7A321A028AE430D7E596EF8AFDFEAA2221D76F5F1651ABC2'
ciphertext_TDES_Ofb = '5BF32CB19369FAD64F7A4CCFD5AACA773EAE39EBEB0699F9CAC0EDD694A0BF1567E482C3F0E214DAE06276F1933BB41DD4A86F556604526051F048EDE873345F'
ciphertext_TDES_Ctr = 'C9CC042291F86CBB946A65CB249C82F704CD8541E47EAADE2A85C1B47FE0AFFCC69CA35F32A07FAA650AA0427BE46D8D03A42348A7F696409D19D3285B455250'


AES128_Cmac = '51F0BEBF7E3B9D92FC49741779363CFE'
AES192_Cmac = '0596A22DD3733CB85DDB0D7788A6844E'
AES256_Cmac = 'E1992190549F6ED5696A2C056C315410'
SM4_Cmac = 'CC2B4F3D2C5AAF8A4AC30E28650EDDC0'
DES_Cmac = '25F3A44B018D7064'
TDES_Cmac = 'B252B71671727992'

AES128_Cbcmac = '3FF1CAA1681FAC09120ECA307586E1A7'
AES192_Cbcmac = 'F00690D0D6442DB29B7F47FA349FF646'
AES256_Cbcmac = 'B2EB05E2C39BE9FCDA6C19078C6A9D1B'
SM4_Cbcmac = '74A629B350CD7E11BE99998AF5206D6C'
DES_Cbcmac = 'D7B87DDB949F153C'
TDES_Cbcmac = '0F8AB00F19A5AE97'

AES128_Gmac = 'D3930E4AD1EC3497496F129A22CD7BB0'
AES192_Gmac = '819153FAEF49F634B302B81A6015F0B4'
AES256_Gmac = '4DFE69C3216464172E6C1416937E76D2'

# AEAD
Aead_Nonce = 'CAFEBABEFACEDBADDECAF888'
Aead_Aad = '0123456789ABCDEF23456789ABCDEF01'
Aead_GcmAes128Tag = '06B4E01298868141756E95CDDE7D2850'
Aead_GcmAes128Ciphetext = '6AC7D9F77A1C8A43AF5BE6373B9F656281ADE2F91AE5AE428656A3E0BF5DDE1E69DBB5A61F1C5D69DECF7C80C946193435D0F34AC5C4BFFA35A2587ED3861CF2'
Aead_GcmAes192Tag = 'FD9EC6145B980B4D24FAFB642A842650'
Aead_GcmAes192Ciphetext = 'A80C56187EBB3EDFA2A0686F3C3C227DE41683F0BF28687383A9B69D12E540F5ED5EC84C47DD0FCD95102E130C7D4C29BB32B0C9ED78D981F16B4A8833DEBF3C'
Aead_GcmAes256Tag = '0A72773658DDE8ABED7089FC1F21BEAF'
Aead_GcmAes256Ciphetext = 'CCE65692C1064EED7FA3046AA46BD8EAA9C7AA990B4F968BAE83CAE728C04F8C05A18F4F2DD6E117A6C0B8482ACE7C73FCD0F1AE228FA6AB40DDF786D5C9131A'

Aead_CcmAes128Tag = '7394F92CB2D42095A5E2F02811390D88'
Aead_CcmAes128Ciphetext = 'E1BDC8D127DDB3A22B580BFD180C9C8A0FE4FE72959B920215B31BF2DB55B1BA2D5BA3D7E2D806B8F7E668AECBFD47136D306771D53C60B601FBB11DA981C4DD'
Aead_CcmAes192Tag = 'C2AEA41463EB77EB58D5572FD02843AA'
Aead_CcmAes192Ciphetext = '278BD09D7BA976A4B74F9B19616AF77B356E1DFBD150796F3E067F776B8CCAAE251507E59119F4184AEBB3B6B76E0617D653A5473BC7035869BFEE0B0B89BC02'
Aead_CcmAes256Tag = 'C2DFCFDC0373CC88EC719CE59DF1C644'
Aead_CcmAes256Ciphetext = 'F5E926DE9905353CFFE6FBAF205805684C5557EACA2F908017DF8D3359EC1D440CA70A972BBA4FB38C9C9D5AFB4E880C7D6C1F95C4CDDC9278AACEC861E1286E'

# 简化版函数,只单独实现某种算法
def AES128_ECB():
    print('AES128 ECB',end='\t')
    cipher = Cipher(algorithms.AES(bytes.fromhex(key128)), modes.ECB(bytes.fromhex(iv)))  
    encryptor = cipher.encryptor()   # 使用encryptor指向该加密的方法
    ct = encryptor.update(bytes.fromhex(plaintext)) + encryptor.finalize()   # 使用uodate方法给入明文,使用finalize方法完成操作,最终返回密文对象
    if ct.hex().upper() == ciphertext_Ecb:
        print('-- 加密成功 --',end='\t')
    decryptor = cipher.decryptor()
    ct = decryptor.update(ct) + decryptor.finalize()
    if ct.hex().upper() == plaintext:
        print(' -- 解密成功 --')

def AES128_CBC():
    print('AES128 CBC',end='\t')
    cipher = Cipher(algorithms.AES(bytes.fromhex(key128)), modes.CBC(bytes.fromhex(iv)))  
    encryptor = cipher.encryptor()   # 使用encryptor指向该加密的方法
    ct = encryptor.update(bytes.fromhex(plaintext)) + encryptor.finalize()   # 使用uodate方法给入明文,使用finalize方法完成操作,最终返回密文对象
    if ct.hex().upper() == ciphertext_Cbc:
        print('-- 加密成功 --',end='\t')
    decryptor = cipher.decryptor()
    ct = decryptor.update(ct) + decryptor.finalize()
    if ct.hex().upper() == plaintext:
        print(' -- 解密成功 --')

def AES128_CTR():
    print('AES128 CTR',end='\t')
    cipher = Cipher(algorithms.AES(bytes.fromhex(key128)), modes.CTR(bytes.fromhex(iv)))  
    encryptor = cipher.encryptor()   # 使用encryptor指向该加密的方法
    ct = encryptor.update(bytes.fromhex(plaintext)) + encryptor.finalize()   # 使用uodate方法给入明文,使用finalize方法完成操作,最终返回密文对象
    if ct.hex().upper() == ciphertext_Ctr:
        print('-- 加密成功 --',end='\t')
    decryptor = cipher.decryptor()
    ct = decryptor.update(ct) + decryptor.finalize()
    if ct.hex().upper() == plaintext:
        print(' -- 解密成功 --')

def AES128_XTS():
    print('AES128 XTS',end='\t')
    cipher = Cipher(algorithms.AES(bytes.fromhex(key256)), modes.XTS(bytes.fromhex(xts_iv)))  
    encryptor = cipher.encryptor()   # 使用encryptor指向该加密的方法
    ct = encryptor.update(bytes.fromhex(plaintext)) + encryptor.finalize()   # 使用uodate方法给入明文,使用finalize方法完成操作,最终返回密文对象
    if ct.hex().upper() == ciphertext_Xts:
        print('-- 加密成功 --',end='\t')
    decryptor = cipher.decryptor()
    ct = decryptor.update(ct) + decryptor.finalize()
    if ct.hex().upper() == plaintext:
        print('-- 解密成功 --')


# 汇总所有的加解密算法
def Sym_Cipher(algo, mode, key, keyLen, expectedResult):
    if algo == 'AES':
        if mode == 'ECB':
            print("AES{0} {1} Demo.".format(keyLen, mode), end='\t')
            cipher = Cipher(algorithms.AES(bytes.fromhex(key)), modes.ECB())
        elif mode == 'CBC':
            print("AES{0} {1} Demo.".format(keyLen, mode), end='\t')
            cipher = Cipher(algorithms.AES(bytes.fromhex(key)), modes.CBC(bytes.fromhex(iv)))
        elif mode == 'CTR':
            print("AES{0} {1} Demo.".format(keyLen, mode), end='\t')
            cipher = Cipher(algorithms.AES(bytes.fromhex(key)), modes.CTR(bytes.fromhex(iv)))
        elif mode == 'CFB':
            print("AES{0} {1} Demo.".format(keyLen, mode), end='\t')
            cipher = Cipher(algorithms.AES(bytes.fromhex(key)), modes.CFB(bytes.fromhex(iv)))
        elif mode == 'OFB':
            print("AES{0} {1} Demo.".format(keyLen, mode), end='\t')
            cipher = Cipher(algorithms.AES(bytes.fromhex(key)), modes.OFB(bytes.fromhex(iv)))
        elif mode == 'XTS':
            print("AES{0} {1} Demo.".format(int(keyLen/2), mode), end='\t')
            if keyLen == 256 or keyLen == 512:
                cipher = Cipher(algorithms.AES(bytes.fromhex(key)), modes.XTS(bytes.fromhex(xts_iv)))
            else:
                print("秘钥长度不正确, 仅支持AES128 or AES256, 分别需要给入256 or 512 bit秘钥")
        else:
            print("模式不支持.")
            return
    elif algo == 'SM4':
        if mode == 'ECB':
            print("SM4 {0} Demo.".format(mode), end='\t')
            cipher = Cipher(algorithms.SM4(bytes.fromhex(key)), modes.ECB())
        elif mode == 'CBC':
            print("SM4{0} Demo.".format(mode), end='\t')
            cipher = Cipher(algorithms.SM4(bytes.fromhex(key)), modes.CBC(bytes.fromhex(iv)))
        elif mode == 'CTR':
            print("SM4{0} Demo.".format(mode), end='\t')
            cipher = Cipher(algorithms.SM4(bytes.fromhex(key)), modes.CTR(bytes.fromhex(iv)))
        elif mode == 'CFB':
            print("SM4{0} Demo.".format(mode), end='\t')
            cipher = Cipher(algorithms.SM4(bytes.fromhex(key)), modes.CFB(bytes.fromhex(iv)))
        elif mode == 'OFB':
            print("SM4{0} Demo.".format(mode), end='\t')
            cipher = Cipher(algorithms.SM4(bytes.fromhex(key)), modes.OFB(bytes.fromhex(iv)))
        else:
            print("模式不支持.")
    elif algo == 'DES':
        if mode == 'ECB':
            print("DES {0} Demo.".format(mode), end='\t')
            cipher = Cipher(algorithms.TripleDES(bytes.fromhex(key)), modes.ECB()) # 秘钥长度给64bit,就是按照DES进行运算
        elif mode == 'CBC':
            print("DES {0} Demo.".format(mode), end='\t')
            cipher = Cipher(algorithms.TripleDES(bytes.fromhex(key)), modes.CBC(bytes.fromhex(iv64)))
        elif mode == 'CTR':
            print("DES {0} Demo.".format(mode), end='\t')
        elif mode == 'CFB':
            print("DES {0} Demo.".format(mode), end='\t')
            cipher = Cipher(algorithms.TripleDES(bytes.fromhex(key)), modes.CFB(bytes.fromhex(iv64)))
        elif mode == 'OFB':
            print("DES {0} Demo.".format(mode), end='\t')
            cipher = Cipher(algorithms.TripleDES(bytes.fromhex(key)), modes.OFB(bytes.fromhex(iv64)))
        else:
            print("模式不支持.")
    elif algo == 'TDES':
        if mode == 'ECB':
            print("TDES {0} Demo.".format(mode), end='\t')
            cipher = Cipher(algorithms.TripleDES(bytes.fromhex(key)), modes.ECB())
        elif mode == 'CBC':
            print("TDES {0} Demo.".format(mode), end='\t')
            cipher = Cipher(algorithms.TripleDES(bytes.fromhex(key)), modes.CBC(bytes.fromhex(iv64)))
        elif mode == 'CTR':
            print("TDES {0} Demo.".format(mode), end='\t')
        elif mode == 'CFB':
            print("TDES {0} Demo.".format(mode), end='\t')
            cipher = Cipher(algorithms.TripleDES(bytes.fromhex(key)), modes.CFB(bytes.fromhex(iv64)))
        elif mode == 'OFB':
            print("TDES {0} Demo.".format(mode), end='\t')
            cipher = Cipher(algorithms.TripleDES(bytes.fromhex(key)), modes.OFB(bytes.fromhex(iv64)))
        else:
            print("模式不支持.")
    else:
        print("算法不支持.")
        return
    # DES CTR 和TDES CTR使用Crypto包的代码
    # 注意计数器值,64bit,不能都是Nonce,至少需要留一个字节作为循环计数
    if algo == 'DES' and mode == 'CTR':
        ctr = Counter.new(8, prefix=bytes.fromhex(desCtr_iv), little_endian=True, initial_value=0)
        cipher = DES.new(bytes.fromhex(key), DES.MODE_CTR, counter = ctr)
        ct = cipher.encrypt(bytes.fromhex(plaintext))  # 加密明文
        if ct.hex().upper() == expectedResult:
            print('-- 加密成功 --',end='\t')
        else:
            print('-- 加密失败 --',end='\t')
        cipher = DES.new(bytes.fromhex(key), DES.MODE_CTR, counter = ctr)
        ct = cipher.decrypt(ct)  # 解密密文
        if ct.hex().upper() == plaintext:
            print(' -- 解密成功 --')
        else:
            print('-- 解密失败 --')
    elif algo == 'TDES' and mode == 'CTR':
        ctr = Counter.new(8, prefix=bytes.fromhex(desCtr_iv), little_endian=True, initial_value=0)
        cipher = DES3.new(bytes.fromhex(key), DES3.MODE_CTR, counter = ctr)
        ct = cipher.encrypt(bytes.fromhex(plaintext))  # 加密明文
        if ct.hex().upper() == expectedResult:
            print('-- 加密成功 --',end='\t')
        else:
            print('-- 加密失败 --',end='\t')
        cipher = DES3.new(bytes.fromhex(key), DES3.MODE_CTR, counter = ctr)
        ct = cipher.decrypt(ct)  # 解密密文
        if ct.hex().upper() == plaintext:
            print(' -- 解密成功 --')
        else:
            print('-- 解密失败 --')
    else: # 使用cryptography包驱动
        encryptor = cipher.encryptor()   # 使用encryptor指向该加密的方法
        ct = encryptor.update(bytes.fromhex(plaintext)) + encryptor.finalize()   # 使用uodate方法给入明文,使用finalize方法完成操作,最终返回密文对象
        if ct.hex().upper() == expectedResult:
            print('-- 加密成功 --',end='\t')
        else:
            print('-- 加密失败 --',end='\t')
        decryptor = cipher.decryptor()
        ct = decryptor.update(ct) + decryptor.finalize()
        if ct.hex().upper() == plaintext:
            print(' -- 解密成功 --')
        else:
            print('-- 解密失败 --')

def Sym_Mac(algo, mode, key, keyLen, expectedResult):
    if algo == 'AES':
        if mode == 'CMAC':
            print("AES{0} CMAC Demo.".format(keyLen), end='\t')
            c = cmac.CMAC(algorithms.AES(bytes.fromhex(key)))
        elif mode == 'CBCMAC':
            print("AES{0} CBCMAC Demo.".format(keyLen, mode), end='\t')
            cipher = Cipher(algorithms.AES(bytes.fromhex(key)), modes.CBC(bytes.fromhex(iv)))
        else:
            print("不支持 {0} 模式".format(mode))
    elif algo == 'SM4':
        if mode == 'CMAC':
            print("SM4 CMAC Demo.", end='\t')
            c = cmac.CMAC(algorithms.SM4(bytes.fromhex(key)))
        elif mode == 'CBCMAC':
            print("SM4 CBCMAC Demo.", end='\t')
            cipher = Cipher(algorithms.SM4(bytes.fromhex(key)), modes.CBC(bytes.fromhex(iv)))
        else:
            print("不支持 {0} 模式".format(mode))
    elif algo == 'DES':
        if mode == 'CMAC':
            print("DES CMAC Demo.".format(mode), end='\t')
            c = cmac.CMAC(algorithms.TripleDES(bytes.fromhex(key)))
        elif mode == 'CBCMAC':
            print("DES CBCMAC Demo.", end='\t')
            cipher = Cipher(algorithms.TripleDES(bytes.fromhex(key)), modes.CBC(bytes.fromhex(iv64)))
        else:
            print("不支持 {0} 模式".format(mode))
    elif algo == 'TDES':
        if mode == 'CMAC':
            print("TDES CMAC Demo.".format(mode), end='\t')
            c = cmac.CMAC(algorithms.TripleDES(bytes.fromhex(key)))
        elif mode == 'CBCMAC':
            print("TDES CBCMAC Demo.", end='\t')
            cipher = Cipher(algorithms.TripleDES(bytes.fromhex(key)), modes.CBC(bytes.fromhex(iv64)))
        else:
            print("不支持 {0} 模式".format(mode))
    else:
        pass
    if mode == 'CMAC':
        c.update(bytes.fromhex(plaintext)) 
        mac = c.finalize()
    elif mode == 'CBCMAC':
        encryptor = cipher.encryptor()   # 使用encryptor指向该加密的方法
        ct = encryptor.update(bytes.fromhex(plaintext)) + encryptor.finalize()   # 使用uodate方法给入明文,使用finalize方法完成操作,最终返回密文对象
        if algo == 'AES' or algo == 'SM4':      # CBCMAC实际是按照CBC进行加密后,取最后一个数据块作为MAC值
            mac = ct[-16:]
        else:
            mac = ct[-8:]

    if mac.hex().upper() == expectedResult:
        print('-- 签名正确 --')
    else:
        print(mac.hex().upper())
        print('-- 签名错误 --')

def Sym_Aead(mode, key, keyLen, expectedResult, expectedTag):
    if mode == 'GCM':
        print("AES{0} {1} Demo.".format(keyLen, mode), end='\t')
        encryptor = Cipher(algorithms.AES(bytes.fromhex(key)),modes.GCM(bytes.fromhex(Aead_Nonce)),).encryptor()
        encryptor.authenticate_additional_data(bytes.fromhex(Aead_Aad))
        ct = encryptor.update(bytes.fromhex(plaintext)) + encryptor.finalize()
        if ct.hex().upper() == expectedResult and encryptor.tag.hex().upper() == expectedTag:
            print(" -- 加密认证成功 --", end='\t')
        else:
            print(" -- 加密认证失败 --", end='\t')
        # tag = bytes.fromhex(Aead_GcmAes192Tag)  # 先不处理tag错误的场景
        decryptor = Cipher(algorithms.AES(bytes.fromhex(key)),modes.GCM(bytes.fromhex(Aead_Nonce), bytes.fromhex(expectedTag))).decryptor()
        decryptor.authenticate_additional_data(bytes.fromhex(Aead_Aad))
        try:      # 验签模式下,必须给入tag,若tag不正确,此处会报异常,若正常执行完成,说明tag正确
            ct = decryptor.update(ct) + decryptor.finalize()
            if ct.hex().upper() == plaintext:
                print(" -- 解密认证成功 --")
            else:
                print(" -- 解密失败 --")
                print(ct.hex().upper())
        except:
            print(" -- 验签失败 --")
    elif mode == 'CCM':
        print("AES{0} {1} Demo.".format(keyLen, mode), end='\t')
        aesccm = AESCCM(bytes.fromhex(key))
        ct = aesccm.encrypt(bytes.fromhex(Aead_Nonce), bytes.fromhex(plaintext), bytes.fromhex(Aead_Aad))
        if ct.hex().upper()[0:-32] == expectedResult and ct.hex().upper()[-32:] == expectedTag:
            print(" -- 加密认证成功 --", end='\t')
        else:
            print(" -- 加密认证失败 --", end='\t')

        ct = aesccm.decrypt(bytes.fromhex(Aead_Nonce), ct, bytes.fromhex(Aead_Aad))
        if ct.hex().upper() == plaintext:
            print(" -- 解密认证成功 --")
        else:
            print(" -- 解密认证失败 --")
            print(ct.hex().upper())
    elif mode == 'GMAC':
        print("AES{0} {1} Demo.".format(keyLen, mode), end='\t')
        encryptor = Cipher(algorithms.AES(bytes.fromhex(key)),modes.GCM(bytes.fromhex(Aead_Nonce))).encryptor()
        encryptor.authenticate_additional_data(bytes.fromhex(plaintext)) # GCM模式下,明文放到AAD为止
        ct = encryptor.update(bytes.fromhex('')) + encryptor.finalize()  # 没有明文,只有AAD时为GMAC
        if encryptor.tag.hex().upper() == expectedTag:
            print(" -- 加密认证成功 --", end='\t')
        else:
            print(" -- 加密认证失败 --", end='\t')
        decryptor = Cipher(algorithms.AES(bytes.fromhex(key)),modes.GCM(bytes.fromhex(Aead_Nonce), bytes.fromhex(expectedTag))).decryptor()
        decryptor.authenticate_additional_data(bytes.fromhex(plaintext))
        try:
            ct = decryptor.update(bytes.fromhex('')) + decryptor.finalize()  
            print(" -- 验签成功 --")
        except:
            print(" -- 验签失败 --")

        # GMAC第二种用法
        # aes = AES.new(bytes.fromhex(key128), AES.MODE_GCM, bytes.fromhex(Aead_Nonce)).update(bytes.fromhex(Aead_Aad))  # 创建一个aes对象
        # en_text, auth_tag = aes.encrypt_and_digest(bytes.fromhex(''))  # 加密明文
        # print("GCM加密测试\n密文(hex形式):", en_text.hex())
        # print(auth_tag.hex())


if __name__ == '__main__':
    print(" AES 测试 ".center(60,'-'))
    Sym_Cipher('AES', 'ECB', key128, 128, ciphertext_AES128_Ecb)
    Sym_Cipher('AES', 'CBC', key128, 128, ciphertext_AES128_Cbc)
    Sym_Cipher('AES', 'CFB', key128, 128, ciphertext_AES128_Cfb)
    Sym_Cipher('AES', 'OFB', key128, 128, ciphertext_AES128_Ofb)
    Sym_Cipher('AES', 'CTR', key128, 128, ciphertext_AES128_Ctr)
    Sym_Cipher('AES', 'XTS', key256, 256, ciphertext_AES128_Xts)

    Sym_Cipher('AES', 'ECB', key192, 192, ciphertext_AES192_Ecb)
    Sym_Cipher('AES', 'CBC', key192, 192, ciphertext_AES192_Cbc)
    Sym_Cipher('AES', 'CFB', key192, 192, ciphertext_AES192_Cfb)
    Sym_Cipher('AES', 'OFB', key192, 192, ciphertext_AES192_Ofb)
    Sym_Cipher('AES', 'CTR', key192, 192, ciphertext_AES192_Ctr)

    Sym_Cipher('AES', 'ECB', key256, 256, ciphertext_AES256_Ecb)
    Sym_Cipher('AES', 'CBC', key256, 256, ciphertext_AES256_Cbc)
    Sym_Cipher('AES', 'CFB', key256, 256, ciphertext_AES256_Cfb)
    Sym_Cipher('AES', 'OFB', key256, 256, ciphertext_AES256_Ofb)
    Sym_Cipher('AES', 'CTR', key256, 256, ciphertext_AES256_Ctr)
    Sym_Cipher('AES', 'XTS', key512, 512, ciphertext_AES256_Xts)

    print(" SM4 测试 ".center(60,'-'))
    Sym_Cipher('SM4', 'ECB', key128, 128, ciphertext_SM4_Ecb)
    Sym_Cipher('SM4', 'CBC', key128, 128, ciphertext_SM4_Cbc)
    Sym_Cipher('SM4', 'CFB', key128, 128, ciphertext_SM4_Cfb)
    Sym_Cipher('SM4', 'OFB', key128, 128, ciphertext_SM4_Ofb)
    Sym_Cipher('SM4', 'CTR', key128, 128, ciphertext_SM4_Ctr)

    print(" DES 测试 ".center(60,'-'))
    Sym_Cipher('DES', 'ECB', key64, 64, ciphertext_DES_Ecb)
    Sym_Cipher('DES', 'CBC', key64, 64, ciphertext_DES_Cbc)
    Sym_Cipher('DES', 'CFB', key64, 64, ciphertext_DES_Cfb)
    Sym_Cipher('DES', 'OFB', key64, 64, ciphertext_DES_Ofb)
    Sym_Cipher('DES', 'CTR', key64, 64, ciphertext_DES_Ctr)

    print(" TDES 测试 ".center(60,'-'))
    Sym_Cipher('TDES', 'ECB', key192, 192, ciphertext_TDES_Ecb)
    Sym_Cipher('TDES', 'CBC', key192, 192, ciphertext_TDES_Cbc)
    Sym_Cipher('TDES', 'CFB', key192, 192, ciphertext_TDES_Cfb)
    Sym_Cipher('TDES', 'OFB', key192, 192, ciphertext_TDES_Ofb)
    Sym_Cipher('TDES', 'CTR', key192, 192, ciphertext_TDES_Ctr)

    print(" CMAC测试 ".center(60,'-'))
    Sym_Mac('AES', 'CMAC', key128, 128, AES128_Cmac)
    Sym_Mac('AES', 'CMAC', key192, 192, AES192_Cmac)
    Sym_Mac('AES', 'CMAC', key256, 256, AES256_Cmac)
    Sym_Mac('SM4', 'CMAC', key128, 128, SM4_Cmac)
    Sym_Mac('DES', 'CMAC', key64, 64, DES_Cmac)
    Sym_Mac('TDES', 'CMAC', key192, 192, TDES_Cmac)

    print(" CBCMAC测试 ".center(60,'-'))
    Sym_Mac('AES', 'CBCMAC', key128, 128, AES128_Cbcmac)
    Sym_Mac('AES', 'CBCMAC', key192, 192, AES192_Cbcmac)
    Sym_Mac('AES', 'CBCMAC', key256, 256, AES256_Cbcmac)
    Sym_Mac('SM4', 'CBCMAC', key128, 128, SM4_Cbcmac)
    Sym_Mac('DES', 'CBCMAC', key64, 64, DES_Cbcmac)
    Sym_Mac('TDES', 'CBCMAC', key192, 192, TDES_Cbcmac)

    print(" GMAC 测试 ".center(60,'-'))
    Sym_Aead('GMAC', key128, 128, '', AES128_Gmac)
    Sym_Aead('GMAC', key192, 192, '', AES192_Gmac)
    Sym_Aead('GMAC', key256, 256, '', AES256_Gmac)

    print(" AEAD GCM 测试 ".center(60,'-'))
    Sym_Aead('GCM', key128, 128, Aead_GcmAes128Ciphetext, Aead_GcmAes128Tag)
    Sym_Aead('GCM', key192, 192, Aead_GcmAes192Ciphetext, Aead_GcmAes192Tag)
    Sym_Aead('GCM', key256, 256, Aead_GcmAes256Ciphetext, Aead_GcmAes256Tag)
    print(" AEAD CCM 测试 ".center(60,'-'))
    Sym_Aead('CCM', key128, 128, Aead_CcmAes128Ciphetext, Aead_CcmAes128Tag)
    Sym_Aead('CCM', key192, 192, Aead_CcmAes192Ciphetext, Aead_CcmAes192Tag)
    Sym_Aead('CCM', key256, 256, Aead_CcmAes256Ciphetext, Aead_CcmAes256Tag)

    

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2149783.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SpringBoot 基于 Vue 的地方美食分享网站

摘要 首先,论文一开始便是清楚的论述了系统的研究内容。其次,剖析系统需求分析,弄明白“做什么”,分析包括业务分析和业务流程的分析以及用例分析,更进一步明确系统的需求。然后在明白了系统的需求基础上需要进一步地…

smardaten无代码这么牛逼?逻辑编排不用代码!

目录 前言 经典案例 ①计划编排:数据操作自动化 ②工单派工:流程变更自动化 smardaten能力解析 一、逻辑控制篇 (1)变量定义与操作 (2)数据校验与反馈 (3)动态数据获取与回填…

企业微信oauth2提示应用无法使用

问题描述: 生成oauth2之后,我a公司是服务商,我给b公司的人去点授权链接会提示这个 应用服务商还没有在企业微信为你开通接口调用许可」,导致无法使用此应用,请联系服务商开通 正文 你先要知道一件事!&…

基于SpringBoot+Vue的“课件通”中小学教学课件共享平台

作者:计算机学姐 开发技术:SpringBoot、SSM、Vue、MySQL、JSP、ElementUI、Python、小程序等,“文末源码”。 专栏推荐:前后端分离项目源码、SpringBoot项目源码、SSM项目源码 系统展示 【2025最新】基于JavaSpringBootVueMySQL的…

后端原型设计

一:导航设计 1.1 横向导航栏 常用于浏览器对客的系统。 1.2 纵向导航栏 纵向导航左边可以进行一级菜单和二级菜单,每个二级菜单右边还可以继续再使用标签栏进行导航三级分类。 头条号和CSDN都是采用该方式。 1.3 横纵结合导航栏 横向为一级菜单&…

ConvexHull-凸包-原理-代码实现

定义:凸包是包围点云的最小凸多面体,所有点都在该多面体的内部或表面上。优点:能够精确地包围点云,并且不存在额外的空白区域。缺点:计算复杂度高,尤其是在高密度点云中,生成凸包的过程较慢。 …

前后端分离项目--下载功能

文章目录 不使用代理服务器blobblob构造函数通过FormData对象的getBlob方法创建Blob对象将Blob对象转换成UR 使用代理服务器 前后端分离项目中下载与其他接口的使用不同,一般下载不走node,不通过代理服务器,而是直接在前台发送请求&#xff0…

人工智能安全治理新篇章:《2024人工智能安全治理框架1.0版》深度解读@附20页PDF文件下载

在数字化浪潮席卷全球的今天,人工智能(AI)技术正以前所未有的速度融入我们的日常生活,从智能助手到自动驾驶,从医疗诊断到金融风控,AI的身影无处不在。然而,技术的双刃剑特性也让我们不得不面对…

3657A/B/AM/BM矢量网络分析仪

苏州新利通 3657A/B/AM/BM 矢量网络分析仪 3657系列矢量网络分析仪适用于无线通信、有线电视、教育及汽车电子等领域,可用于对滤波器、放大器、天线、电缆、有线电视分接头等射频元件的性能测量。该产品采用Windows操作系统;具有误差校准功能、时域功能…

Java基础面试必知:HashMap的数据结构与扩容机制

Java基础面试必知:HashMap的数据结构与扩容机制 在Java开发中, HashMap是使用最为广泛的数据结构之一,它提供了基于键值对的快速存取功能。然而,在面试中,经常会涉及到HashMap的底层实现原理,特别是其数据…

Abp vNext(五)集成MQTTnet,可收发消息

一 前言 MQTT的相关理论内容这里不做过多介绍,请看下面两篇文章: Introduction MQTT协议中文版 MQTT协议-CSDN博客 这篇文章只做代码实现,文章中使用MQTTnet作为MQTT开发的组件。 MQTT分为服务端和客户端,一个服务端对应多个…

Docker + Win 10 学习记录

下载Docker Release notes | Docker Docs 推荐使用4.33版本,最新的Docker版本在win10 22H2无法安装。需要升级到win11. 查看Win10版本是否与最新版的Docker兼容 运行 win R, 然后输入winver 如果你的Docker版本无法在当前的win10安装,请更…

编码器-解码器架构_by《李沐:动手学深度学习v2》pytorch版

系列文章目录 文章目录 系列文章目录一、引言编码器解码器合并编码器和解码器小结练习答案1. 编码器和解码器是否必须是同一类型的神经网络?2. 除了机器翻译,还有其它可以适用于“编码器-解码器”架构的应用吗? 一、引言 正如我们…

LocalDateTime,OffsetDateTime和ZonedDateTime(上)

图片来源:https://www.cnblogs.com/yourbatman/p/14324575.html 一. LocalDate和LocalTime LocalDate:代表不含时区信息的日期,它只能表示年、月、日。它适用于记录一个日子,比如生日、纪念日、或者任何只需要日期而不需要具体时…

除猫毛用粘毛器还是宠物空气净化器?希喂/米家/352/范罗士/有哈空气净化器对比

微博之夜,明星互送礼物环节,要求所有嘉宾准备一份礼物,再由其他明星随机抽取互换礼物。田曦薇送粘毛器可是引起了广泛的争议和批评。不说价格,粘毛器对咱养猫人来讲还真是刚需啊。我朋友家三只猫,出门不用说啥&#xf…

掌握数据中心虚拟化:关键挑战与解决方案

数据中心虚拟化是使用云软件平台将物理数据中心转变为数字数据中心的过程,使企业能够远程访问信息和应用程序。它包括在数据中心内创建物理基础设施的多个虚拟版本,通过将服务器、存储和网络等资源划分为虚拟实体来实现资源的高效利用。 虚拟化环境中的关…

[c++进阶(八)]STL容器适配器之queue

1.前言 和stack一样,队列也没有把他放在容器的一栏里面,而是把他放在容器适配器的一栏。这也是因为queue是使用了别人的相关接口,空间然后来封装自己的内容,最后再给上层用户使用。 2.队列 队列的性质就是先进先出,他…

【C++ 学习】多态的基础和原理(10)

目录 前言1. 概念2. 多态的定义及实现2.1 多态的构成条件2.2 虚函数2.3 虚函数重写2.4 虚函数重写的例外2.4.1 协变2.4.1 析构函数的重写 2.5 多态调用和普通调用2.6 函数重写/函数隐藏/函数重载 的对比2.6.1 函数重写2.6.2 函数隐藏2.6.3 函数重载 2.7 C11 final 和override 3…

HT326 免电感滤波2x20W D类立体声音频功放

特点 输出功率(BTL模式) 2x20W (VDD14.5V,RL4Ω,THDN1%) 单电源系统: 4.5V-18V; 超过90%效率,无需散热器 扩频功能,免电感滤波 模拟差分/单端输入可选 增益:32dB 保护功能:过压/过流/过热/欠压异常,直流检测 和短路保护 无铅无卤封装&#x…

three.js 热力图

使用three.js 和 heatMap.js 实现在 三维场景中展示热力图的效果,以下代码复制粘贴即可在你的本机运行。 在线编辑运行预览可方位 https://threehub.cn/#/codeMirror?navigationThreeJS&classifyexpand&idheatmap3D 在 https://threehub.cn 中还有很多案例…