diff --git a/main.go b/main.go index 06ab7d0..ab8c688 100644 --- a/main.go +++ b/main.go @@ -1 +1,25 @@ package main + +import ( + "fmt" + + "git.send.nrw/sendnrw/sendnrwlib/netcrypto" + "git.send.nrw/sendnrw/sendnrwlib/netproto" +) + +func main() { + key, _ := netcrypto.AES_GenerateKey() + fmt.Println(netcrypto.AES_KeyToString(key)) + enc, _ := netcrypto.AES_Encrypt("test", key) + fmt.Println(enc) + dec, _ := netcrypto.AES_Decrypt(enc, key) + fmt.Println(dec) + + a := netproto.GenerateNetworkProtocol(netproto.GenerateMainHeader(1, "A", netproto.GenerateEHT1("127.0.0.1", "", ""), netproto.GenerateEHT2("8.8.8.8", "", "80"), netproto.GenerateEHT3("JSON", "0", "0")), "") + fmt.Println(a) + b, _ := netproto.ToJSON(a) + fmt.Println(b) + netproto.FromJSON(b, &a) + fmt.Println(a) + +} diff --git a/crypto/crypto.go b/netcrypto/netcrypto.go similarity index 90% rename from crypto/crypto.go rename to netcrypto/netcrypto.go index 94e2488..60f6aad 100644 --- a/crypto/crypto.go +++ b/netcrypto/netcrypto.go @@ -1,4 +1,4 @@ -package crypto +package netcrypto import ( "crypto/aes" @@ -27,6 +27,28 @@ func VerifyToken(token, storedHash string) bool { return HashToken(token) == storedHash } +// Generiert einen zufälligen 32-Byte-Schlüssel für AES-256 +func AES_GenerateKey() ([]byte, error) { + key := make([]byte, 32) // 32 Bytes für AES-256 + _, err := rand.Read(key) + if err != nil { + return nil, fmt.Errorf("Fehler beim Generieren des Schlüssels: %v", err) + } + return key, nil +} + +func AES_KeyToString(key []byte) string { + return base64.StdEncoding.EncodeToString(key) +} + +func AES_StringToKey(base64Key string) ([]byte, error) { + key, err := base64.StdEncoding.DecodeString(base64Key) + if err != nil { + return nil, fmt.Errorf("Fehler beim Decodieren des Schlüssels: %v", err) + } + return key, nil +} + // Verschlüsselt einen JSON-String mit AES-GCM func AES_Encrypt(jsonString string, key []byte) (string, error) { // Erstelle einen AES-Block diff --git a/netproto/netproto.go b/netproto/netproto.go index 4565aaa..f8ddfd2 100644 --- a/netproto/netproto.go +++ b/netproto/netproto.go @@ -2,6 +2,7 @@ package netproto import ( "encoding/base64" + "encoding/json" ) type MainHeader struct { @@ -121,6 +122,18 @@ func DecodeBase64(input string) (string, error) { return string(d), nil } +func ToJSON(input interface{}) (string, error) { + b, err := json.Marshal(input) + if err != nil { + return "", err + } + return string(b), nil +} + +func FromJSON(input string, output interface{}) error { + return json.Unmarshal([]byte(input), output) +} + type ExtensionHeader struct { Type uint8 `json:"type"` Meta map[string]string `json:"meta"`