欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python实现AES加解密文档里英文字符串**

程序员文章站 2022-06-17 16:08:48
python实现AES加解密文档里英文字符串**AES加解密文档里英文字符串英文文档中也包含了空格与回车符...

python实现AES加解密文档里英文文章**

AES加解密文档里英文字符串
英文文档中也包含了空格与回车符

加密过程

首先读取文件中的内容

将文档中的内容读取,然后将其赋予你申请的变量 在我的实验中我的申请的变量的名字是message

outputFilename = input('what is name to encrypted file:',)#'I believe I can fly_1.txt'
        fileobj = open(inputfilename,encoding='utf-8')
        message = fileobj.read()
        fileobj.close()

读取出来后回车符都变成\n

将读出的字符串转成16进制字符串

首先将读出的message放到一个列表list1中
然后将列表里面的字符串按照字符的顺序循环读出元素并转化成16进制字符串,同时将这个字符串写入一个新列表list2
由于我的方式中回车符是一个16进制字符代表,我的代码中表示是a 因为这个会导致后面的加解密更复杂,所以利用0a代替a 最后导入一个新列表
申请一个变量,将列表中的元素读出,赋值给这个变量名,并且将每个16进制的元素前面的0x删去,再赋值给另外一个变量

list1 = list(message)
list2 = []
for i in list1:
    i_by = i.encode('utf-8')
    for i_bin in i_by:
        list2.append(hex(i_bin))
list3 = ['0x0a' if j == '0xa' else j for j in list2]
print(len(list3))
 b = ''.join(list3)
m = re.sub('0x', '', b)
M = m

因为AES代码是基于一个博主的代码(链接在本文文底),代码只能加密32个16进制的字符

切割字符

将字符串切割,每32个字符作为一组,然后加进一个新的列表中

        h1 = len(M) // 32#计算整除
        h2 = len(M) % 32#计算是否为0,若为0则切割轮数就是h1,若不为0则是h1+1
        list4 = []
        for step in range(0, h1 + 1):
            h3 = M[step * 32:32 * (step + 1)]
            list4.append(h2)
        list5 = list4

进行加密

 for number in list5:
        h4 = '0x'+number
        k=key
        RoundKeys = aes.round_key_generator(k)

        plaintext = eval(h4)
        plaintext = aes.num_2_16bytes(plaintext)
        print(plaintext)
        ciphertext = aes.aes_encrypt(plaintext, RoundKeys)
        list6.append(hex(aes._16bytes2num(ciphertext)))
        print('ciphertext = ' + hex(aes._16bytes2num(ciphertext)))

进行加密后的密文处理

因为切割后如果进行加密的列表中有的元素中可能第一个字符是0,使用该加密算法后会自动吞掉,所以我们要对密文进行处理后再写入一个新文档(如果需要解密的话进行此步骤,不用解密不影响)

        for i1 in range(0,len(list6)):
            list6[i1]=re.sub('0x','',list6[i1])
            if len(list6[i1])<32:
                list6[i1]='0'*(32-len(list6[i1]))+list6[i1]
            print(i1)a
            print(list6[i1])
        a = ''.join(list6)
        a =re.sub('0x','',a)
        fo = open(outputFilename, 'w')
        fo.write(a)
        fo.close()

至此加密过程结束
PS:文档中是中文也可以用此方法加密

解密过程

读取你想加密的文件

 outputFilename = input('what is name to decrypted file:' )  # 'I believe I can fly_2.txt'
      fileobj = open(inputfilename)
      message = fileobj.read()
      fileobj.close()

切割字符串

 list1=[]
      h1 = len(message) // 32#计算整除
      h3 = len(message) % 32#计算是否为0,若为0则切割轮数就是h1,若不为0则是h1+1
      print(h1)
      print(h3)
      for step in range(0, h1):
          h2 = message[step * 32:32 * (step + 1)]
          list1.append(h2)

进行解密

 list2 = []
      for number in list1:
          h4 ='0x'+number
          k = key#0x0f1571c947d9e8590cb7add6af7f6798
          RoundKeys = aes.round_key_generator(k)
          ciphertext = eval(h4)
          ciphertext = aes.num_2_16bytes(ciphertext)
          ciphertext = aes.aes_decrypt(ciphertext, RoundKeys)
          list2.append(hex(aes._16bytes2num(ciphertext)))

进行解密后的密文处理

因为切割后如果进行解密的列表中有的元素中可能第一个字符是0,使用该解密算法后会自动吞掉,所以我们要对明文进行处理后再写入一个新文档

      for i1 in range(0, len(list2)):
          list2[i1] = re.sub('0x', '', list2[i1])
          if len(list2[i1]) < 32:
              list2[i1] = '0' * (32 - len(list2[i1])) + list2[i1]
          print(i1)
          print(list2[i1])
      b = ''.join(list2)
      b = re.sub('0x', '', b)
      fo = open(outputFilename, 'w')
      fo.write(b)
      fo.close()

将16进制转化为英文字符

16进制转字符我借鉴了一个函数

def decode(s):
    return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])

转化的过程

首先将16进制的明文读出 然后将其每两位为一组进行切割并且在每组前面加上16进制特有的0x,同时将每组按照顺序写入一个新列表
再将0x0a改回0xa 最后将获得的明文内容赋值于申请的变量,然后将其写入一个新文档

fileobj_1=open(outputFilename)
      message_1=fileobj_1.read()
      fileobj_1.close()
      h5=len(message_1)//2#计算整除
      h6=len(message_1)%2#计算是否为0,若为0则切割轮数就是h5,若不为0则是h5+1
      print(h5)
      list3=[]
      for step in range(0, h5):
          h2 = '0x'+message_1[step * 2:2 * (step + 1)]
          list3.append(h2)
      list4 = ['0xa' if i == '0x0a' else i for i in list3]
      print(list4)
      list5=[]
      list6=[]
      for j in list4:
          list5.append(bin(int(j, 16)).replace('0b', ''))
      print(list5)
      for h in list5:
        k = decode(h)
        list6.append(k)
      a = ''.join(list6)
      print(a)
      outputFilename_1=input('what is name to decrypted file:')
      fo_1 = open(outputFilename_1, 'w')
      fo_1.write(a)
      fo_1.close()

至此解密结束
PS:此解密方法只能适用于英文(中文可以解密,转换时出现问题),中文由于本人学艺不精,不会将中文转码,转出是乱码。

放上实现每一步的图:

1.将文字转化为16进制
python实现AES加解密文档里英文字符串**
2.文件加密
python实现AES加解密文档里英文字符串**
python实现AES加解密文档里英文字符串**

3.解密
python实现AES加解密文档里英文字符串**

4.将解密的结果转化为字符
python实现AES加解密文档里英文字符串**

最后放入完整的我写的主函数的代码

 aes = AES()
    key = input('input your key:')
    key=eval(key)

    mode = input('please input encrypt or decrypt:')
#加密
    if mode=='encrypt':
        inputfilename=input('print you want encrypt filename:')#'I believe I can fly .txt'
        if not os.path.exists(inputfilename):
            print('the file %s does not exist.Quitting' % (inputfilename))
            sys.exit()
        outputFilename = input('what is name to encrypted file:',)#'I believe I can fly_1.txt'
        fileobj = open(inputfilename,encoding='utf-8')
        message = fileobj.read()
        fileobj.close()
        list1 = list(message)
        list2 = []
        for i in list1:
            i_by = i.encode('utf-8')
            for i_bin in i_by:
                list2.append(hex(i_bin))
        list3 = ['0x0a' if j == '0xa' else j for j in list2]
        print(len(list3))
        b = ''.join(list3)
        m = re.sub('0x', '', b)
        print(m)
        M = m
        h1 = len(M) // 32
        h3 = len(M) % 32
        print(h1)
        print(h3)
        list4 = []
        for step in range(0, h1 + 1):
            h2 = M[step * 32:32 * (step + 1)]
            list4.append(h2)
        list5 = list4
        print(list5)
        list6 = []
        for number in list5:
            h4 = '0x'+number
            k=key
            RoundKeys = aes.round_key_generator(k)

            plaintext = eval(h4)
            plaintext = aes.num_2_16bytes(plaintext)
            print(plaintext)
            ciphertext = aes.aes_encrypt(plaintext, RoundKeys)
            list6.append(hex(aes._16bytes2num(ciphertext)))
            print('ciphertext = ' + hex(aes._16bytes2num(ciphertext)))
             #print()0x0f1571c947d9e8590cb7add6af7f6798
        for i1 in range(0,len(list6)):
            list6[i1]=re.sub('0x','',list6[i1])
            if len(list6[i1])<32:
                list6[i1]='0'*(32-len(list6[i1]))+list6[i1]
            print(i1)
            print(list6[i1])
        b = ''.join(list6)
        b =re.sub('0x','',b)
        fo = open(outputFilename, 'w')
        fo.write(b)
        fo.close()
        #解密
    elif mode == 'decrypt':
      inputfilename = input('print you want decrypt filename:')  # 'I believe I can fly_1.txt'
      if not os.path.exists(inputfilename):
            print('the file %s does not exist.Quitting' % (inputfilename))
            sys.exit()
      outputFilename = input('what is name to decrypted file:' )  
      fileobj = open(inputfilename)
      message = fileobj.read()
      fileobj.close()
      list1=[]
      h1 = len(message) // 32
      h3 = len(message) % 32
      print(h1)
      print(h3)
      for step in range(0, h1):
          h2 = message[step * 32:32 * (step + 1)]
          list1.append(h2)
      list2 = []
      for number in list1:
          h4 ='0x'+number
          k = key
          RoundKeys = aes.round_key_generator(k)
          ciphertext = eval(h4)
          ciphertext = aes.num_2_16bytes(ciphertext)
          ciphertext = aes.aes_decrypt(ciphertext, RoundKeys)
          list2.append(hex(aes._16bytes2num(ciphertext)))
      for i1 in range(0, len(list2)):
          list2[i1] = re.sub('0x', '', list2[i1])
          if len(list2[i1]) < 32:
              list2[i1] = '0' * (32 - len(list2[i1])) + list2[i1]
          print(i1)
          print(list2[i1])
      b = ''.join(list2)
      b = re.sub('0x', '', b)
      fo = open(outputFilename, 'w')
      fo.write(b)
      fo.close()
      fileobj_1=open(outputFilename)
      message_1=fileobj_1.read()
      fileobj_1.close()
      h5=len(message_1)//2
      h6=len(message_1)%2
      print(h5)
      list3=[]
      for step in range(0, h5):
          h2 = '0x'+message_1[step * 2:2 * (step + 1)]
          list3.append(h2)
      list4 = ['0xa' if i == '0x0a' else i for i in list3]
      print(list4)
      list5=[]
      list6=[]
      for j in list4:
          list5.append(bin(int(j, 16)).replace('0b', ''))
      print(list5)
      for h in list5:
        k = decode(h)
        list6.append(k)
      a = ''.join(list6)
      print(a)
      outputFilename_1=input('what is name to decrypted file:')
      fo_1 = open(outputFilename_1, 'w')
      fo_1.write(a)
      fo_1.close()
    else:
      print('wrong input!')

PS:使用主函数时别忘记上面的一个转字符的代码哦

加密的文档

I believe I can fly


I used to think that I could not go on
And life was nothing but an awful song
But now I know the meaning of true love
I'm leaning on the everlasting arms
If I can see it, then I can do it
If I just believe it, there's nothing to it
I believe I can fly
I believe I can touch the sky
I think about it every night and day (Night and day)
Spread my wings and fly away
I believe I can soar
I see me running through that open door
I believe I can fly
I believe I can fly
I believe I can fly hoo
meaning byGirlgirl3ooo
I think they mean that it can help your with the song See All
See I was on the verge of breaking down
Sometimes silence can seem so loud
There are miracles in life I must achieve
But first I know it starts inside of me, ho oh
If I can see it hoo, then I can be it
If I just believe it, there's nothing to it
I believe I can fly
I believe I can touch the sky
I think about it every night and day
Spread my wings and fly away
I believe I can soar
I see me running through that open door
I believe I can fly
I believe I can fly
Oh, I believe I can fly hoo
Hey, 'cause I believe in me, oh
If I can see it hoo, then I can do it
If I just believe it, there's nothing to it hey
I believe I can fly hoo
I believe I can touch the sky
I think about it every night and day
Spread my wings and fly away
I believe I can soar
I see me running through that open door
I believe I can fly (I can fly)
I believe I can fly (I can fly)
I believe I can fly (I can fly) hey
If I just spread my wings (I can fly)
I can fly (I can fly)
I can fly (I can fly)
I can fly,(I can fly) hey
If I just spread my wings (I can fly)
I can fly (I can fly)
(I can fly)
(I can fly)

注意

本文章的代码是基于借鉴的AES代码,所以具有在加解密时候的局限性,需要按照32个字符为一组将明文切割加密和密文切割解密,如果是其他的字符个数可以自行改动参数。

最后

本人还是一个新手,在本代码中的变量命名有点简单,可能代码有的复杂,希望大佬们不要介意。而且可能中间有的地方写的不够好,希望大佬指正,还有最后中文转码,如果有大佬了解的希望可以教我一下,谢谢。

AES代码借鉴于(加解密都有哦):https://blog.csdn.net/weixin_42580862/article/details/101703941

本文地址:https://blog.csdn.net/qq_44847088/article/details/111143659