Java默认DES算法使用DES/ECB/PKCS5Padding工作方式,在GO语言中因为ECB的脆弱性,DES的ECB模式是故意不放出来的,但实际情况中有时我们并不需要那么安全,以下代码完成与java默认DES算法的互通,为了能更好的与各种语言互通,建议在java中还是明确指明工作模式,如:DES/CBC/PKCS5Padding
package main import ( "bytes" "crypto/des" "errors" "log" ) func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) log.Println("程序开始....") key := []byte{0xD5, 0x92, 0x86, 0x02, 0x2A, 0x0B, 0x3E, 0x64} data := []byte("hello world") out, _ := MyEncrypt(data, key) log.Println("加密后:", out) out, _ = MyDecrypt(out, key) log.Println("解密后:", string(out)) } func MyEncrypt(data, key []byte) ([]byte, error) { block, err := des.NewCipher(key) if err != nil { return nil, err } bs := block.BlockSize() data = PKCS5Padding(data, bs) if len(data)%bs != 0 { return nil, errors.New("Need a multiple of the blocksize") } out := make([]byte, len(data)) dst := out for len(data) > 0 { block.Encrypt(dst, data[:bs]) data = data[bs:] dst = dst[bs:] } return out, nil } func MyDecrypt(data []byte, key []byte) ([]byte, error) { block, err := des.NewCipher(key) if err != nil { return nil, err } bs := block.BlockSize() if len(data)%bs != 0 { return nil, errors.New("crypto/cipher: input not full blocks") } out := make([]byte, len(data)) dst := out for len(data) > 0 { block.Decrypt(dst, data[:bs]) data = data[bs:] dst = dst[bs:] } out = PKCS5UnPadding(out) return out, nil } 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)] }
版权声明:本文为博主原创文章,未经博主允许不得转载。
有疑问加站长微信联系(非本文作者)