star/aes/aes.go
2024-03-17 18:19:44 +08:00

132 lines
2.5 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package aes
import (
"errors"
"fmt"
"io"
"os"
"b612.me/starcrypto"
"b612.me/staros"
)
func EncodeStr(str string, key []byte) (string, error) {
if len(key) < 16 {
key = starcrypto.Md5(key)
} else {
key = key[:len(key)/16*16]
if len(key) > 32 {
key = key[:32]
}
}
ensdata, err := starcrypto.CustomEncryptAesCFB([]byte(str), key)
if err != nil {
return "", err
}
return starcrypto.Base64Encode(ensdata), nil
}
func DecodeStr(str string, key []byte) (string, error) {
if len(key) < 16 {
key = starcrypto.Md5(key)
} else {
key = key[:len(key)/16*16]
}
strtmp, err := starcrypto.Base64Decode(str)
if err != nil {
return "", err
}
p, err := starcrypto.CustomDecryptAesCFB(strtmp, key)
return string(p), err
}
func EncodeFile(fpath, out string, key []byte) error {
if len(key) < 16 {
key = starcrypto.Md5(key)
} else {
key = key[:len(key)/16*16]
}
if !staros.Exists(fpath) {
return errors.New("SrcFile Not Exists")
}
fpsrc, err := os.Open(fpath)
if err != nil {
return err
}
defer fpsrc.Close()
fpdst, err := os.Create(out)
if err != nil {
return err
}
defer fpdst.Close()
bufsize := 1024 * 1024 //1MB
stat, _ := fpsrc.Stat()
buf := make([]byte, bufsize)
var sumAll int64
for {
n, err := fpsrc.Read(buf)
if err != nil && err != io.EOF {
return err
}
fmt.Printf("已完成:%.2f%%\r", float64(sumAll)/float64(stat.Size())*100)
sumAll += int64(n)
if n > 0 {
encodeBytes, err := starcrypto.CustomEncryptAesCFBNoBlock(buf[:n], key, key)
if err != nil {
return err
}
fpdst.Write(encodeBytes)
}
if err == io.EOF {
fmt.Print("已完成100% \n")
break
}
}
return nil
}
func DecodeFile(fpath, out string, key []byte) error {
if len(key) < 16 {
key = starcrypto.Md5(key)
} else {
key = key[:len(key)/16*16]
}
if !staros.Exists(fpath) {
return errors.New("SrcFile Not Exists")
}
fpsrc, err := os.Open(fpath)
if err != nil {
return err
}
defer fpsrc.Close()
fpdst, err := os.Create(out)
if err != nil {
return err
}
defer fpdst.Close()
bufsize := 1024 * 1024 //1MB
stat, _ := fpsrc.Stat()
buf := make([]byte, bufsize)
var sumAll int64
for {
n, err := fpsrc.Read(buf)
if err != nil && err != io.EOF {
return err
}
fmt.Printf("已完成:%.2f%%\r", float64(sumAll)/float64(stat.Size())*100)
sumAll += int64(n)
if n > 0 {
encodeBytes, err := starcrypto.CustomDecryptAesCFBNoBlock(buf[:n], key, key)
if err != nil {
return err
}
fpdst.Write(encodeBytes)
}
if err == io.EOF {
fmt.Print("已完成100% \n")
break
}
}
return nil
}