Skip to content

Instantly share code, notes, and snippets.

@wklken
Created September 22, 2016 07:00
Show Gist options
  • Save wklken/d9eba02e40adbc876ea61704a28ba92b to your computer and use it in GitHub Desktop.
Save wklken/d9eba02e40adbc876ea61704a28ba92b to your computer and use it in GitHub Desktop.
3des: encrypt with python & deencrypt with golang
package main
// reference: https://golang.org/pkg/crypto/des/
// reference: http://blog.studygolang.com/2013/01/go%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86%E4%B9%8Bdes/
import (
"crypto/cipher"
"crypto/des"
"encoding/base64"
"encoding/json"
"fmt"
)
// 3DES解密
func TripleDesDecrypt(crypted, key []byte) ([]byte, error) {
block, err := des.NewTripleDESCipher(key)
if err != nil {
return nil, err
}
// note: IV = key[:8]
blockMode := cipher.NewCBCDecrypter(block, key[:8])
origData := make([]byte, len(crypted))
// origData := crypted
blockMode.CryptBlocks(origData, crypted)
return origData, nil
}
func main() {
data := "a6rzP8ogj4bD2woh7tDBk0gBYtyhgzJhxOrvse0f8hyQUem+V9skOnOp4q+81R5Cs+gPDdUxtGFdITLVUaTjVUOQiGD8scBTWVL71F9BQUNjug28kD7RCV1kDHwJWU5ReiaKPnT0EzaYpzeppvWbPPUxXD30iFwLN0y0DMnQYo0PR8XkyMbgEg=="
raw_data, _ := base64.StdEncoding.DecodeString(data)
fmt.Println(string(raw_data))
// encrypted_data := string(raw_data)
key := []byte("aaaaaaaaaaaaaaaaaaaaaaaa")
result, _ := TripleDesDecrypt(raw_data, key)
fmt.Println("result:")
fmt.Println(string(result))
var f interface{}
err := json.Unmarshal(result, &f)
if err != nil {
fmt.Println("decode json fail")
}
}
#!/usr/bin/env python
# encoding: utf-8
# pip install pycrypto
# 3des, cbc mode
import json
import base64
from Crypto.Cipher import DES3
def pad(text):
"""
补齐为8的倍数
"""
ext_byte_count = len(text) % 8
if ext_byte_count == 0:
return text
add_byte_count = 8 - ext_byte_count
return text + ' ' * add_byte_count
def tobase64(encrypt_data):
"""
base64
"""
return base64.b64encode(encrypt_data)
# 1. must be 16/24 bytes, 约定好
secret_key = 'a' * 24
# 2. 表单数据获取拼json, 或者其他格式, 需要和engine约定好
data = {
'app_code': 'test',
'auth_token': 'xxxxxxxxxx',
'mac': '10:dd:b1:ff:fe:37:cd:90,10:dd:b1:ff:fe:37:cd:90,10:dd:b1:ff:fe:37:cd:90'
}
data_string = json.dumps(data)
data_string = pad(data_string)
print 'before encrypt: ', data_string
# 3. 加密
# use triple des
des3 = DES3.new(secret_key, mode=DES3.MODE_CBC, IV=secret_key[:8])
# des3 = DES3.new(secret_key)
encrypt_data = des3.encrypt(data_string)
print "after encrypt:", encrypt_data
# 4. 给用户的, 再base64, 因为加密后存在很多特殊的字符
raw_base64 = tobase64(encrypt_data)
print "tobase64: ", raw_base64
# 5. 示例, 解密
# note: 反向解开不能用同一个对象
raw_data = base64.b64decode(raw_base64)
des32 = DES3.new(secret_key, mode=DES3.MODE_CBC, IV=secret_key[:8])
# des32 = DES3.new(secret_key)
raw_base64 = des32.decrypt(raw_data)
print "after deencrypt: ", json.loads(raw_base64)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment