久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

CTR 中的 AES 如何用于 Python 和 PyCrypto?

How AES in CTR works for Python with PyCrypto?(CTR 中的 AES 如何用于 Python 和 PyCrypto?)
本文介紹了CTR 中的 AES 如何用于 Python 和 PyCrypto?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我正在使用 python 2.7.1我想在 CTR 模式下使用 AES 加密某事.我為 python 安裝了 PyCrypto 庫.我寫了以下代碼:

I am using python 2.7.1 I want to encrypt sth using AES in CTR mode. I installed PyCrypto library for python. I wrote the following code:

secret = os.urandom(16)
crypto = AES.new(os.urandom(32), AES.MODE_CTR, counter=lambda: secret)
encrypted = crypto.encrypt("asdk")
print crypto.decrypt(encrypted)

我必須運行 crypto.decrypt 與我的明文字節大小一樣多的次數,才能正確獲取解密數據.即:

i have to run crypto.decrypt as many times as the byte size of my plaintext in order to get correctly the decrypted data. I.e:

encrypted = crypto.encrypt("test")
print crypto.decrypt(encrypted)
print crypto.decrypt(encrypted)
print crypto.decrypt(encrypted)
print crypto.decrypt(encrypted)

最后一次解密調用會將明文返回給我.解密的其他輸出是一些亂碼字符串.我想知道這是否正常?我是否必須每次都包含在一個大小等于我的明文的循環中,或者我弄錯了什么?

The last call to decrypt will give me the plaintext back. The other outputs from decrypt are some gibberish strings . I am wondering if this is normal or not? Do i have to include into a loop with size equal of my plaintext every time or i have gotten sth wrong?

推薦答案

根據@gertvdijk 的說法,AES_CTR 是一種不需要需要填充的流密碼.所以我刪除了相關代碼.

According to @gertvdijk, AES_CTR is a stream cipher which does not need padding. So I've deleted the related codes.

這是我知道的.

  1. 在加密和解密時必須使用相同的密鑰(AES.new(...) 中的第一個參數),并保持密鑰的私密性.

  1. You have to use a same key(the first parameter in AES.new(...)) in encryption and decryption, and keep the key private.

加密/解密方法是有狀態的,即crypto.en(de)crypt("abcd")==crypto.en(de)crypt("abcd") 總是正確的.在您的 CTR 中,您的計數器回調始終返回相同的內容,因此在加密時它變得無狀態(我不是 100% 肯定這是原因),但我們仍然發現它在解密時有點有狀態.作為結論,我們應該始終使用新對象來完成它們.

The encryption/decryption methods are stateful, that means crypto.en(de)crypt("abcd")==crypto.en(de)crypt("abcd") is not always true. In your CTR, your counter callback always returns a same thing, so it becomes stateless when encrypt (I am not 100% sure it is the reason), but we still find that it is somewhat stateful in decryption. As a conclusion, we should always use a new object to do them.

加密和解密中的 counter 回調 函數的行為應該相同.在你的情況下,它是讓他們兩個都返回相同的秘密.然而我不認為 secret 是一個秘密".您可以使用隨機生成的 "secret" 并在沒有任何加密的情況下將其傳遞給通信對等方,以便對方可以直接使用它,只要 secret不可預測.

The counter callback function in both encryption and decryption should behave the same. In your case, it is to make both of them return the same secret. Yet I don't think the secret is a "secret". You can use a random generated "secret" and pass it across the communicating peers without any encryption so that the other side can directly use it, as long as the secret is not predictable.

所以我會這樣寫我的密碼,希望它能提供一些幫助.

So I would write my cipher like this, hope it will offer some help.

import os
import hashlib
import Crypto.Cipher.AES as AES

class Cipher:

        @staticmethod
        def md5sum( raw ):
                m = hashlib.md5()
                m.update(raw)
                return m.hexdigest()

        BS = AES.block_size

        @staticmethod 
        def pad( s ):
                """note that the padding is no necessary"""
                """return s + (Cipher.BS - len(s) % Cipher.BS) * chr(Cipher.BS - len(s) % Cipher.BS)"""
                return s

        @staticmethod
        def unpad( s ):
                """return s[0:-ord(s[-1])]"""
                return s

        def __init__(self, key):
                self.key = Cipher.md5sum(key)
                #the state of the counter callback 
                self.cnter_cb_called = 0 
                self.secret = None

        def _reset_counter_callback_state( self, secret ):
                self.cnter_cb_called = 0
                self.secret = secret

        def _counter_callback( self ):
                """
                this function should be stateful
                """
                self.cnter_cb_called += 1
                return self.secret[self.cnter_cb_called % Cipher.BS] * Cipher.BS


        def encrypt(self, raw):
                secret = os.urandom( Cipher.BS ) #random choose a "secret" which is not secret
                self._reset_counter_callback_state( secret )
                cipher = AES.new( self.key, AES.MODE_CTR, counter = self._counter_callback )
                raw_padded = Cipher.pad( raw )
                enc_padded = cipher.encrypt( raw_padded )
                return secret+enc_padded #yes, it is not secret

        def decrypt(self, enc):
                secret = enc[:Cipher.BS]
                self._reset_counter_callback_state( secret )
                cipher = AES.new( self.key, AES.MODE_CTR, counter = self._counter_callback )
                enc_padded = enc[Cipher.BS:] #we didn't encrypt the secret, so don't decrypt it
                raw_padded = cipher.decrypt( enc_padded )
                return Cipher.unpad( raw_padded )

一些測試:

>>> from Cipher import Cipher
>>> x = Cipher("this is key")
>>> "a"==x.decrypt(x.encrypt("a"))
True
>>> "b"==x.decrypt(x.encrypt("b"))
True
>>> "c"==x.decrypt(x.encrypt("c"))
True
>>> x.encrypt("a")==x.encrypt("a")
False #though the input is same, the outputs are different

參考:http://packages.python.org/pycrypto/Crypto.Cipher.blockalgo-module.html#MODE_CTR

這篇關于CTR 中的 AES 如何用于 Python 和 PyCrypto?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to draw a rectangle around a region of interest in python(如何在python中的感興趣區域周圍繪制一個矩形)
How can I detect and track people using OpenCV?(如何使用 OpenCV 檢測和跟蹤人員?)
How to apply threshold within multiple rectangular bounding boxes in an image?(如何在圖像的多個矩形邊界框中應用閾值?)
How can I download a specific part of Coco Dataset?(如何下載 Coco Dataset 的特定部分?)
Detect image orientation angle based on text direction(根據文本方向檢測圖像方向角度)
Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 一区二区三区视频在线观看 | 国产精品高潮呻吟久久av黑人 | 成人片在线看 | 亚洲欧美综合 | 精品美女视频在线观看免费软件 | 国产亚洲网站 | 中文字幕 国产 | 久久另类视频 | 精品一区二区不卡 | 欧美精品在线一区二区三区 | 久久久www成人免费精品 | 成人免费精品 | 成人精品一区二区三区中文字幕 | 成人久久 | 精久久 | 日韩在线视频一区二区三区 | 亚洲444kkkk在线观看最新 | 成人在线国产 | 日本 欧美 国产 | 亚洲成人国产综合 | 成年人视频在线免费观看 | 亚洲免费高清 | 黄色片a级| 人人射人人草 | 天堂亚洲| 亚洲国产精品久久久 | 国产精品一区二区在线 | 欧美 日韩 综合 | xx视频在线观看 | 密桃av | 色综合视频 | 国产成人久久精品一区二区三区 | 色悠悠久 | 免费观看av网站 | 久久综合久久综合久久综合 | 亚洲一级黄色 | 一级毛片视频在线 | 成人一区在线观看 | 国产aa | 少妇黄色 | 国产亚洲精品综合一区 |