AES CBC 128的實現

起因

AES已經變成目前對稱加密中最流行算法之一,AES能夠使用12八、19二、和256位密鑰,而且用128位分組加密和解密數據。python

項目中須要使用AES對密碼信息進行加密,由嵌入式設備使用C語言進行加密,經過服務器中轉後,由Android APP完成解密。git

我的自測使用python完成。 github

源碼請見:https://github.com/fpzeng/aes128算法

 

JAVA代碼

 

C代碼

 

Python代碼

下面代碼的IV爲1234567812345678,密鑰爲1234567812345678,使用CBC 128進行加減密。服務器

須要注意:dom

  1. IV必須是16字節。
  2. 私鑰必須時16字節。
  3. 待加密內容長度不是16字節倍數時,須要補齊。通常補0,如python代碼行數13的chr(0)
  4. 因爲輸入的待加密內容長度是補齊了的,因此須要經過unpad來去除末尾的0,如python代碼行數16。

 

 1 import base64
 2 import traceback
 3 from Crypto.Cipher import AES
 4 from Crypto import Random
 5 from clint.textui import colored
 6 class AESCipher:
 7     def __init__( self, key ):
 8         self.key = key
 9         self.bs = 16
10         self.iv = '1234567812345678'
11 
12     def _pad(self, s):
13         return s + (self.bs - len(s) % self.bs) * chr(0)
14 
15     def _unpad(self, s):
16         return s[:s.index(chr(0))]
17 
18     def encrypt( self, raw ):
19         raw = self._pad(raw)
20         cipher = AES.new( self.key, AES.MODE_CBC, self.iv )
21         return base64.b64encode(cipher.encrypt(raw))
22 
23     def decrypt( self, enc ):
24         enc = base64.b64decode(enc)
25         assert enc!=None
26         cipher = AES.new(self.key, AES.MODE_CBC, self.iv )
27         assert cipher!=None
28         return self._unpad(cipher.decrypt(enc)) 
29 
30 if __name__=="__main__":
31     aes=AESCipher('1234567812345678')
32     try:
33         plaintext = "1234qwer"
34         print colored.green("input: %s"%(plaintext))
35         encrypt_data = aes.encrypt(plaintext)
36         print colored.green("encrypt: %s"%(encrypt_data))
37         decrypt_data = aes.decrypt(encrypt_data)
38         print colored.green("decrypt: %s"%(decrypt_data))
39     except Exception,e:
40         print e
41         traceback.print_exc()
42         del aes

  

做者

阿曾(zfpnuc@gmail.comui

相關文章
相關標籤/搜索