Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ZanderZhang
Forked from cuixin/des.go
Created December 13, 2019 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZanderZhang/dda8e79c404e9f386a40b73d773fdba5 to your computer and use it in GitHub Desktop.
Save ZanderZhang/dda8e79c404e9f386a40b73d773fdba5 to your computer and use it in GitHub Desktop.
des ecb mode in golang
package main
import (
"bytes"
"crypto/des"
"errors"
)
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)]
}
func ZeroPadding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{0}, padding)
return append(ciphertext, padtext...)
}
func ZeroUnPadding(origData []byte) []byte {
return bytes.TrimFunc(origData,
func(r rune) bool {
return r == rune(0)
})
}
func DesEncrypt(src, key []byte) ([]byte, error) {
block, err := des.NewCipher(key)
if err != nil {
return nil, err
}
bs := block.BlockSize()
src = ZeroPadding(src, bs)
// src = PKCS5Padding(src, bs)
if len(src)%bs != 0 {
return nil, errors.New("Need a multiple of the blocksize")
}
out := make([]byte, len(src))
dst := out
for len(src) > 0 {
block.Encrypt(dst, src[:bs])
src = src[bs:]
dst = dst[bs:]
}
return out, nil
}
func DesDecrypt(src, key []byte) ([]byte, error) {
block, err := des.NewCipher(key)
if err != nil {
return nil, err
}
out := make([]byte, len(src))
dst := out
bs := block.BlockSize()
if len(src)%bs != 0 {
return nil, errors.New("crypto/cipher: input not full blocks")
}
for len(src) > 0 {
block.Decrypt(dst, src[:bs])
src = src[bs:]
dst = dst[bs:]
}
out = ZeroUnPadding(out)
// out = PKCS5UnPadding(out)
return out, nil
}
package main
import (
"fmt"
"testing"
)
func TestDesEncrypt(t *testing.T) {
key := []byte("5e8487e6")
origtext := []byte("hello world123563332")
erytext, err := DesEncrypt(origtext, key)
if err != nil {
t.Fatal(err)
}
fmt.Printf("%v\n", erytext)
destext, err2 := DesDecrypt(erytext, key)
if err2 != nil {
t.Fatal(err2)
}
fmt.Println(string(destext))
fmt.Println(len(origtext), len(string(destext)))
fmt.Println(string(origtext) == string(destext))
}
go test . -v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment