golang 3DES 암호화

2689 단어 golang
key,iv 스스로 설정
결과가 입력 표시를 정상적으로 인쇄할 수 있도록 모두base64 처리를 거쳤다
 
* TripleDES.go
package auth

import (
	"bytes"
	"crypto/cipher"
	"crypto/des"
	"encoding/base64"
)

type TripleDES struct {
	key string
	iv  string
}

// @ref: https://blog.csdn.net/xiaoxiao_haiyan/article/details/81320350
func (this *TripleDES) Encrypt(plain string) (string, error) {
	key := []byte(this.key)
	iv := []byte(this.iv)

	block, err := des.NewTripleDESCipher(key)
	if err != nil {
		return "", err
	}
	input := []byte(plain)
	// input = PKCS5Padding(input, block.BlockSize())
	blockMode := cipher.NewOFB(block, iv)
	crypted := make([]byte, len(input))
	blockMode.XORKeyStream(crypted, input)

	return base64.StdEncoding.EncodeToString(crypted), err
}

func (this *TripleDES) Decrypt(secret string) (string, error) {
	key := []byte(this.key)
	iv := []byte(this.iv)

	crypted, err := base64.StdEncoding.DecodeString(secret)
	if err != nil {
		return "", err
	}
	block, err := des.NewTripleDESCipher(key)
	if err != nil {
		return "", err
	}
	blockMode := cipher.NewOFB(block, iv)
	origData := make([]byte, len(crypted))
	blockMode.XORKeyStream(origData, crypted)
	// origData = PKCS5UnPadding(origData)
	return string(origData), 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  
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

* TripleDES_test.go
package auth

import (
	"strings"
	"testing"
)

func TestTripleDES_Encrypt(t *testing.T) {
	input := "11111"
	key := "\x8a\xbe\x1e\x3f..."
	iv := "\x8a\xbe\x1e\x3f\xab\xb0\x90\xe8"
	des := TripleDES{key: key, iv: iv}

	output, err := des.Encrypt(input)
	if err != nil {
		t.Errorf(err.Error())
	}
	t.Log(output)

	if output != "VMtLmys=" {
		t.Fail()
	}
}

func TestTripleDES_Decrypt(t *testing.T) {
	input := "FY8OxXQKh4I="
	key := "\x8a\xbe\x1e\x3f..."
	iv := "\x8a\xbe\x1e\x3f\xab\xb0\x90\xe8"
	des := TripleDES{key: key, iv: iv}

	output, err := des.Decrypt(input)
	if err != nil {
		t.Errorf(err.Error())
	}
	t.Log(output)

	if strings.Compare(output, "putongj3") != 0 {
		t.Fail()
	}
}

참고 자료:https://blog.csdn.net/xiaoxiao_haiyan/article/details/81320350

 


사용자 암호 해독


https://blog.csdn.net/fareast_mzh/article/details/88395311비밀 문장

좋은 웹페이지 즐겨찾기