1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| import ( "bytes" "crypto/des" "errors" )
func DESedeECBEncrypt(origData, key []byte) ([]byte, error) { tkey := make([]byte, 24, 24) copy(tkey, key) k1 := tkey[:8] k2 := tkey[8:16] k3 := tkey[16:]
buf1, err := encrypt(origData, k1) if err != nil { return nil, err } buf2, err := decrypt(buf1, k2) if err != nil { return nil, err } out, err := encrypt(buf2, k3) if err != nil { return nil, err } return out, nil }
func DESedeECBDecrypt(crypted, key []byte) ([]byte, error) { tkey := make([]byte, 24, 24) copy(tkey, key) k1 := tkey[:8] k2 := tkey[8:16] k3 := tkey[16:] buf1, err := decrypt(crypted, k3) if err != nil { return nil, err } buf2, err := encrypt(buf1, k2) if err != nil { return nil, err } out, err := decrypt(buf2, k1) if err != nil { return nil, err } return out, nil }
func encrypt(origData, key []byte) ([]byte, error) { if len(origData) < 1 || len(key) < 1 { return nil, errors.New("wrong data or key") } block, err := des.NewCipher(key) if err != nil { return nil, err } bs := block.BlockSize() if len(origData)%bs != 0 { return nil, errors.New("wrong padding") } out := make([]byte, len(origData)) dst := out for len(origData) > 0 { block.Encrypt(dst, origData[:bs]) origData = origData[bs:] dst = dst[bs:] } return out, nil }
func decrypt(crypted, key []byte) ([]byte, error) { if len(crypted) < 1 || len(key) < 1 { return nil, errors.New("wrong data or key") } block, err := des.NewCipher(key) if err != nil { return nil, err } out := make([]byte, len(crypted)) dst := out bs := block.BlockSize() if len(crypted)%bs != 0 { return nil, errors.New("wrong crypted size") }
for len(crypted) > 0 { block.Decrypt(dst, crypted[:bs]) crypted = crypted[bs:] dst = dst[bs:] }
return out, nil }
|