GO與Java的DES ECB加解密演算法互換

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

Java預設DES演算法使用DES/ECB/PKCS5Padding工作方式,在GO語言中因為ECB的脆弱性,DES的ECB模式是故意不放出來的,但實際情況中有時我們並不需要那麼安全,以下程式碼完成與java預設DES演算法的互連,為了能更好的與各種語言互連,建議在java中還是明確指明工作模式,如:DES/CBC/PKCS5Padding

package mainimport ("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 := 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, 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 := 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)]}


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.