Created
January 16, 2014 01:52
-
-
Save lintianzhi/8448460 to your computer and use it in GitHub Desktop.
aes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"crypto/aes" | |
"crypto/cipher" | |
"encoding/hex" | |
"path/filepath" | |
"io/ioutil" | |
"os" | |
) | |
func PKCS7Padding(b []byte) []byte { | |
if extra := len(b)%aes.BlockSize; extra != 0 { | |
padNum := aes.BlockSize - extra | |
bitCode := byte(padNum) | |
for i := 0; i < padNum; i++ { | |
b = append(b, bitCode) | |
} | |
} | |
return b | |
} | |
func cryp(dstf, srcf string, mode cipher.BlockMode) (err error) { | |
src, err := os.Open(srcf) | |
if err != nil { | |
return | |
} | |
defer src.Close() | |
b, err := ioutil.ReadAll(src) | |
if err != nil { | |
return | |
} | |
b = PKCS7Padding(b) | |
out := make([]byte, len(b)) | |
mode.CryptBlocks(out, b) | |
err = ioutil.WriteFile(dstf, out, 0600) | |
return | |
} | |
var ( | |
key = []byte("examplekey123456") | |
inDir = "test/" | |
outDir = "prefix/" | |
dDir = "deprefix/" | |
) | |
func crpytDir(path, desDir string, mode cipher.BlockMode) { | |
err := filepath.Walk(path, func(fpath string, info os.FileInfo, err error) error { | |
if info == nil { | |
return err | |
} | |
if info.IsDir() { | |
return nil | |
} | |
fmt.Println(fpath) | |
return cryp(desDir+info.Name(), fpath, mode) | |
}) | |
if err != nil { | |
fmt.Println(err) | |
} | |
} | |
func main() { | |
block, err := aes.NewCipher(key) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
var iv [aes.BlockSize]byte | |
_, err = hex.Decode(iv[:], []byte("cfd80d18b1a842871608f71d8d37710f")) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
mode := cipher.NewCBCEncrypter(block, iv[:]) | |
crpytDir(inDir, outDir, mode) | |
mode = cipher.NewCBCDecrypter(block, iv[:]) | |
crpytDir(outDir, dDir, mode) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment