Skip to content

Instantly share code, notes, and snippets.

@zweite
Last active December 10, 2016 02:36
Show Gist options
  • Save zweite/61dc94e2fde2d92b6f410a205e789589 to your computer and use it in GitHub Desktop.
Save zweite/61dc94e2fde2d92b6f410a205e789589 to your computer and use it in GitHub Desktop.
一段aes的加解密的坑
package main
import (
"crypto/aes"
"encoding/base64"
"fmt"
"log"
"github.com/kierdavis/cfb8"
)
func main() {
key := "f96290f1be624aceb166494278d52cc5"
raw := "aesssss"
aesCipher := NewAESCipher(key)
enc, err := aesCipher.Encrypt(raw)
if err != nil {
log.Fatal(err)
}
raw_, err := aesCipher.Decrypt(enc)
if err != nil {
log.Fatal(err)
}
if raw == raw_ {
fmt.Println("test pass")
}
}
type AESCipher struct {
key string
}
func NewAESCipher(key string) *AESCipher {
return &AESCipher{
key: key,
}
}
func (a *AESCipher) Encrypt(raw string) (string, error) {
aesModel, err := aes.NewCipher([]byte(a.key))
if err != nil {
return "", err
}
iv := make([]byte, aes.BlockSize)
ci := cfb8.NewEncrypter(aesModel, iv)
dst := make([]byte, len(raw))
ci.XORKeyStream(dst, []byte(raw))
return base64.StdEncoding.EncodeToString(append(iv, dst...)), nil
}
func (a *AESCipher) Decrypt(enc string) (string, error) {
src, err := base64.StdEncoding.DecodeString(enc)
if err != nil {
return "", err
}
aesModel, err := aes.NewCipher([]byte(a.key))
if err != nil {
return "", err
}
iv := src[:aes.BlockSize]
ci := cfb8.NewDecrypter(aesModel, iv)
srcText := src[aes.BlockSize:]
dst := make([]byte, len(srcText))
ci.XORKeyStream(dst, srcText)
return string(dst), nil
}
# 加解密算法同go说明
class AESCipher:
def __init__( self, key ):
self.key = key
def encrypt( self, raw ):
iv = Random.new().read( AES.block_size )
cipher = AES.new( self.key, AES.MODE_CFB, iv )
r = ( iv + cipher.encrypt( raw ) )
return base64.b64encode(r)
def decrypt( self, enc ):
enc = (enc)
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_CFB, iv)
x=(cipher.decrypt( enc[16:] ))
return base64.b64decode(x)
@zweite
Copy link
Author

zweite commented Dec 9, 2016

如果直接使用go标准库中的CFB填充方式进行AES加密,在python中是解密不了的,主要原因在于实现的CFB标准不一样,python使用的包是from Crypto.Cipher import AES,使用的标准是CFB-8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment