AES CBC 128的实现

原由

AES已经变成目前对称加密中最流行算法之一,AES可以使用128、192、和256位密钥,并且用128位分组加密和解密数据。

项目中需要使用AES对密码信息进行加密,由嵌入式设备使用C语言进行加密,通过服务器中转后,由Android APP完成解密。

个人自测使用python完成。 

源码请见:https://github.com/fpzeng/aes128

 

JAVA代码

 

C代码

 

Python代码

下面代码的IV为1234567812345678,密钥为1234567812345678,使用CBC 128进行加减密。

需要注意:

  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.com

posted @ 2014-12-24 19:22  fpzeng  阅读(2857)  评论(0编辑  收藏  举报