10-08 1,711 views
http://www.iteye.com/topic/1122076/
package main
import(
"crypto/des"
"crypto/cipher"
"fmt"
"bytes"
)
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
// 3DES加密 key=3x8=24bit
func TripleDesEncrypt(origData, key []byte) ([]byte, error) {
block, err := des.NewTripleDESCipher(key)
if err != nil {
return nil, err
}
origData = PKCS5Padding(origData, block.BlockSize())
// origData = ZeroPadding(origData, block.BlockSize())
blockMode := cipher.NewCBCEncrypter(block, key[:8])
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
// 3DES解密
func TripleDesDecrypt(crypted, key []byte) ([]byte, error) {
block, err := des.NewTripleDESCipher(key)
if err != nil {
return nil, err
}
blockMode := cipher.NewCBCDecrypter(block, key[:8])
origData := make([]byte, len(crypted))
// origData := crypted
blockMode.CryptBlocks(origData, crypted)
origData = PKCS5UnPadding(origData)
// origData = ZeroUnPadding(origData)
return origData, nil
}
func DesEncrypt(origData, key []byte) ([]byte, error) {
block, err := des.NewCipher(key)
if err != nil {
return nil, err
}
origData = PKCS5Padding(origData, block.BlockSize())
// origData = ZeroPadding(origData, block.BlockSize())
blockMode := cipher.NewCBCEncrypter(block, key)
crypted := make([]byte, len(origData))
// 根据CryptBlocks方法的说明,如下方式初始化crypted也可以
// crypted := origData
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
//des解密 key=8bit
func DesDecrypt(crypted, key []byte) ([]byte, error) {
block, err := des.NewCipher(key)
if err != nil {
return nil, err
}
blockMode := cipher.NewCBCDecrypter(block, key)
//origData := make([]byte, len(crypted))
origData := crypted
blockMode.CryptBlocks(origData, crypted)
//origData = PKCS5UnPadding(origData)
origData = PKCS5UnPadding(origData)
return origData, nil
}
func main() {
origData := "aaaaaaaaaaaaahejlwjeoioiuweroihihichy568yeiwehri"
key := "12345678"
crypted, err := DesEncrypt([]byte(origData), []byte(key))
if err != nil {
fmt.Println(err)
}else{
// fmt.Printf("crypted = %s\n", crypted)
fmt.Printf("crypted = %X\n", crypted)
}
dedata, err1 := DesDecrypt([]byte(crypted), []byte(key))
if err1 != nil {
fmt.Println(err1)
}else{
// fmt.Printf("crypted = %s\n", crypted)
fmt.Printf("dedata = %s\n", dedata)
}
key = "123456781234567812345678"
crypted, err = TripleDesEncrypt([]byte(origData), []byte(key))
if err != nil {
fmt.Println(err)
}else{
// fmt.Printf("crypted = %s\n", crypted)
fmt.Printf("crypted = %X\n", crypted)
}
dedata2, err2 := TripleDesDecrypt([]byte(crypted), []byte(key))
if err2 != nil {
fmt.Println(err2)
}else{
// fmt.Printf("crypted = %s\n", crypted)
fmt.Printf("dedata2 = %s\n", dedata2)
}
}