密码学-3DES
3DES加密算法
3DES加密算法的使用與DES的用法基本相同,使用方法如下:
package mainimport ("bytes""crypto/des""crypto/cipher""fmt""encoding/base64")//補碼func PKCS5Padding(ciphertext []byte, blocksize int) []byte {padding := blocksize - len(ciphertext)%blocksizepadtext := bytes.Repeat([]byte{byte(padding)}, padding)return append(ciphertext, padtext...)}//3DES加密func TripleDescrypt(origData []byte, key []byte) []byte {//3DES的秘鑰長度必須為24位block, _ := des.NewTripleDESCipher(key)//補碼origData = PKCS5Padding(origData, block.BlockSize())//設置加密模式blockMode := cipher.NewCBCEncrypter(block, key[:8])//創建密文數組,加密crypted := make([]byte, len(origData))blockMode.CryptBlocks(crypted, origData)return crypted}//解密func TipleDesDecrypt(crypted, key []byte) [] byte {block, _ := des.NewTripleDESCipher(key)blockMode := cipher.NewCBCDecrypter(block, key[:8])origData := make([]byte, len(crypted))blockMode.CryptBlocks(origData, crypted)origData = PKCS5UnPadding(origData)return origData}//去碼func PKCS5UnPadding(origData []byte) []byte {length := len(origData)// 去掉最后一個字節 unpadding 次unpadding := int(origData[length-1])return origData[:(length - unpadding)]}func main() {//長度為24bytekey := []byte("123456789012345678901234")a := base64.StdEncoding.EncodeToString(TripleDescrypt([]byte("hello world"), key))//加密fmt.Println(a)}總結