This is a creation in Article, where the information may have evolved or changed.
The Java default DES algorithm uses the des/ecb/pkcs5padding mode of operation, in the go language because of the ECB's fragility, des's ECB model is deliberately not released, but in reality sometimes we do not need to be so safe, The following code completes the interoperability with the Java default DES algorithm, in order to better communicate with various languages, it is suggested in Java or explicitly indicate the working mode, such as: des/cbc/pkcs5padding
Package Mainimport ("bytes" "Crypto/des" "Errors" "Log") func main () {log. SetFlags (log. Lstdflags | Log. Lshortfile) log. PRINTLN ("program starts ...") Key: = []byte{0xd5, 0x92, 0x86, 0x02, 0x2A, 0x0B, 0x3e, 0x64}data: = []byte ("Hello World") out, _: = Mye Ncrypt (data, key) log. PRINTLN ("After encryption:", out) out, _ = Mydecrypt (out, key) log. Println ("Decrypted:", 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: = Outfor len (data) > 0 {block. Encrypt (DST, data[:bs]) data = DATA[BS:]DST = Dst[bs:]}return out, nil}func mydecrypt (data []byte, Key []byte] ([]byte, err OR) {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: = Outfor 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)%blocksizepadtext: = 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)]}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.