菜单

admin
发布于 2024-06-26 / 128 阅读
0

golang des加密/解密

package main

import (
	"bytes"
	"crypto/des"
	"crypto/sha1"
	"encoding/base64"
	"errors"
	"fmt"
	"log"
)

// 模拟 java SHA1PRNG 处理
func sha1prng(keyBytes []byte, encryptLength int) ([]byte, error) {
	hashs := sha1Hash(sha1Hash(keyBytes))
	maxLen := len(hashs)
	realLen := encryptLength / 8
	if realLen > maxLen {
		return nil, errors.New("invalid length")
	}

	return hashs[0:realLen], nil
}

func sha1Hash(data []byte) []byte {
	h := sha1.New()
	h.Write(data)
	return h.Sum(nil)
}

func main() {
	// 定义 DES 密钥
	key, err := sha1prng([]byte(`hello world hello world`), 64)
	log.Printf("%v,%v\n", key, err)

	// 明文数据
	plaintext := []byte(`hello world`)
	data, _ := DesECBEncrypt(plaintext, key)
	ss := base64.StdEncoding.EncodeToString(data)
	fmt.Printf("encrypt:%s\n", ss)

	data, _ = DesECBDecrypt(data, key)
	fmt.Printf("decrypt:%s\n", data)
}

func DesECBEncrypt(data, key []byte) ([]byte, error) {
	//NewCipher创建一个新的加密块
	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 {
		//Encrypt加密第一个块,将其结果保存到dst
		block.Encrypt(dst, data[:bs])
		data = data[bs:]
		dst = dst[bs:]
	}
	return out, nil
}

func DesECBDecrypt(data, key []byte) ([]byte, error) {
	//NewCipher创建一个新的加密块
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	bs := block.BlockSize()
	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 {
		//Encrypt加密第一个块,将其结果保存到dst
		block.Decrypt(dst, data[:bs])
		data = data[bs:]
		dst = dst[bs:]
	}
	out = Pkcs5Padding(out, bs)
	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...)
}