From 9b833779dded66b52805d13742671fe86396afd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Naoriel=20Sa=27=20Roc=C3=AD?= Date: Fri, 31 May 2024 19:47:03 +0200 Subject: [PATCH] - Inital commit. --- .gitignore | 2 + CHANGELOG.md | 8 ++ IDataCryptor.go | 9 ++ LICENSE | 9 ++ README.md | 3 + defaultDataCryptor.go | 90 +++++++++++++ defaultDataCryptor_test.go | 12 ++ encryptedString.go | 176 +++++++++++++++++++++++++ encryptedString_test.go | 212 ++++++++++++++++++++++++++++++ go.mod | 3 + go_encryptedstring.code-workspace | 9 ++ helpers.go | 74 +++++++++++ setHidden.go | 7 + setHidden_windows.go | 21 +++ 14 files changed, 635 insertions(+) create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 IDataCryptor.go create mode 100644 LICENSE create mode 100644 README.md create mode 100644 defaultDataCryptor.go create mode 100644 defaultDataCryptor_test.go create mode 100644 encryptedString.go create mode 100644 encryptedString_test.go create mode 100644 go.mod create mode 100644 go_encryptedstring.code-workspace create mode 100644 helpers.go create mode 100644 setHidden.go create mode 100644 setHidden_windows.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1b76cbb --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.log +.vscode/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..77ec6c9 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,8 @@ +# git.sa-roci.de/oss/go_encryptedstring Release notes + +All notable changes to this project will be documented in this file. +This project adheres to [Semantic Versioning](http://semver.org/). + +## v. 0.0.1 + +- Initial Release. diff --git a/IDataCryptor.go b/IDataCryptor.go new file mode 100644 index 0000000..258bc1d --- /dev/null +++ b/IDataCryptor.go @@ -0,0 +1,9 @@ +package encryptedstring + +type IDataCryptor interface { + // Encrypt tries to encrypt the given binary with the appropriate cipher. + Encrypt(binary []byte) (encrypted []byte, err error) + + // Decrypt tries to decrypt the given binary with the appropriate cipher. + Decrypt(binary []byte) (decrypted []byte, err error) +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..973b652 --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2024 Sa RocĂ­ Solutions + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ac805da --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# git.sa-roci.de/oss/go_encryptedstring + +A module for serialisable encrypted strings. diff --git a/defaultDataCryptor.go b/defaultDataCryptor.go new file mode 100644 index 0000000..bceb11e --- /dev/null +++ b/defaultDataCryptor.go @@ -0,0 +1,90 @@ +package encryptedstring + +import ( + "crypto/rand" + "os" + "path" +) + +const ( + // EncryptionKeyFileName is the name of the file for storage of the en-/decryption key + EncryptionKeyFileName = ".esk" +) + +type defaultDataCryptor struct { + encryptionKey []byte +} + +func (ddc *defaultDataCryptor) keyByte(index int) byte { + index = index % len(ddc.encryptionKey) + return ddc.encryptionKey[index] +} + +func (ddc *defaultDataCryptor) xorCrypt(in []byte) (out []byte) { + out = make([]byte, 0) + for i := 0; i < len(in); i++ { + out = append(out, in[i]^ddc.keyByte(i)) + } + return out +} + +// Encrypt tries to encrypt the given binary with the appropriate cipher. +func (ddc *defaultDataCryptor) Encrypt(binary []byte) (encrypted []byte, err error) { + return ddc.xorCrypt(binary), nil +} + +// Decrypt tries to decrypt the given binary with the appropriate cipher. +func (ddc *defaultDataCryptor) Decrypt(binary []byte) (decrypted []byte, err error) { + return ddc.xorCrypt(binary), nil +} + +func (ddc *defaultDataCryptor) init() (err error) { + // Get the startup directory path + dir := getLocalPath() + if _, err := os.Stat(dir); err != nil { + os.MkdirAll(dir, os.ModePerm) + } + + // Check for the key-file + keyFilePath := path.Join(dir, EncryptionKeyFileName) + _, err = os.Stat(keyFilePath) + if err == nil { + // Read the file + if ddc.encryptionKey, err = os.ReadFile(keyFilePath); err == nil { + // We got the key! + return + } + } + + // Create a new key-file + ddc.encryptionKey = make([]byte, 1024) + _, err = rand.Read(ddc.encryptionKey) + if err != nil { + return + } + + var keyFile *os.File + if keyFile, err = os.Create(keyFilePath); err == nil { + _, err = keyFile.Write(ddc.encryptionKey) + if err == nil { + err = keyFile.Sync() + } + keyFile.Close() + } + if err == nil { + err = setHidden(keyFilePath) + } + return +} + +// NewDefaultDataCryptor creates a new XOR-based +// IDataCryptor-interface the key of which is situated +// in a file called '.esk' in the startup directory of +// the application. +func NewDefaultDataCryptor() IDataCryptor { + ddc := &defaultDataCryptor{} + if err := ddc.init(); err != nil { + panic(err) + } + return ddc +} diff --git a/defaultDataCryptor_test.go b/defaultDataCryptor_test.go new file mode 100644 index 0000000..df4b8e0 --- /dev/null +++ b/defaultDataCryptor_test.go @@ -0,0 +1,12 @@ +package encryptedstring + +import ( + "testing" +) + +func TestNewDefaultDataCryptor(t *testing.T) { + t.Cleanup(cleanup) + NewDefaultDataCryptor() + startup() + NewDefaultDataCryptor() +} diff --git a/encryptedString.go b/encryptedString.go new file mode 100644 index 0000000..98d418a --- /dev/null +++ b/encryptedString.go @@ -0,0 +1,176 @@ +package encryptedstring + +import ( + "encoding/hex" + "encoding/xml" + "fmt" + "strings" +) + +// IPotentiallyUnencrypted describes an interface for a struct which was potentially not encrypted +type IPotentiallyUnencrypted interface { + // WasUnencrypted determines wheter the value was set from data marked as unencrypted + WasUnencrypted() bool +} + +// EncryptedString is a string wrapper which will en-/decrypt the actual value upon (un)marshalling +type EncryptedString struct { + data string +} + +// New returns a new EncryptedString instance with a specific value +func New(value string) EncryptedString { + es := EncryptedString{} + es.encrypt(value) + return es +} + +// Value returns the current value +func (es EncryptedString) Value() string { + if decrypted, err := es.decrypt(); err == nil { + return decrypted + } + return "" +} + +// String implements the fmt.Stringer interface +func (es EncryptedString) String() string { + if es.WasUnencrypted() { + if data, err := getEncryptionProvider().Encrypt([]byte(es.data)); err == nil { + return defaultIdentifier + hex.EncodeToString(data) + } + } else if strings.HasPrefix(es.data, defaultIdentifier) { + return es.data + } + return "" +} + +// SetValue sets the current value +func (es *EncryptedString) SetValue(newValue string) { + es.encrypt(newValue) +} + +// WasUnencrypted determines wheter the value was set from data marked as unencrypted +func (es EncryptedString) WasUnencrypted() bool { + return !strings.HasPrefix(es.data, defaultIdentifier) +} + +// MarshalJSON satisfies the json.Marshaler interface +func (es EncryptedString) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf("\"%s\"", es.String())), nil +} + +// UnmarshalJSON satisfies the json.Unmarshaler interface +func (es *EncryptedString) UnmarshalJSON(data []byte) error { + cleanData, ok := unquoteBytes(data) + if ok { + es.data = string(cleanData) + if _, err := es.decrypt(); err == nil { + return nil + } + } + return fmt.Errorf("'%s' cannot be unmarshalled from JSON", string(data)) +} + +// MarshalXML satisfies the xml.Marshaler interface +func (es EncryptedString) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + err := e.EncodeToken(start) + if nil != err { + return err + } + stringValue := es.String() + err = e.EncodeToken(xml.CharData([]byte(stringValue))) + if nil != err { + return err + } + err = e.EncodeToken(xml.EndElement{ + Name: start.Name, + }) + if nil != err { + return err + } + return e.Flush() +} + +// UnmarshalXML satisfies the xml.Unmarshaler interface +func (es *EncryptedString) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { + var ( + token xml.Token + err error + ) + +Loop: + for { + if token, err = d.Token(); err != nil { + return err + } + + if token == nil { + break + } + + switch se := token.(type) { + case xml.StartElement: + return fmt.Errorf("bad XML syntax") + case xml.CharData: + stringData := strings.Trim(string(se), " \t\r\n") + if 0 < len(stringData) { + es.data = stringData + if _, err = es.decrypt(); err != nil { + return err + } + } + case xml.EndElement: + break Loop + } + } + + return nil +} + +// MarshalText satisfies the TextMarshaler interface +func (es EncryptedString) MarshalText() (text []byte, err error) { + return []byte(es.String()), nil +} + +// UnmarshalText satisfies the TextUnmarshaler interface +func (es *EncryptedString) UnmarshalText(text []byte) error { + es.data = string(text) + if _, err := es.decrypt(); err != nil { + return err + } + return nil +} + +func (es *EncryptedString) encrypt(value string) { + payload := []byte(value) + additionalBytes := len(payload) % 16 + for i := 0; i < additionalBytes; i++ { + payload = append(payload, 0) + } + if encrypted, err := getEncryptionProvider().Encrypt(payload); err == nil { + es.data = defaultIdentifier + hex.EncodeToString(encrypted) + } +} + +func (es *EncryptedString) decrypt() (decrypted string, err error) { + if strings.HasPrefix(es.data, defaultIdentifier) { + var payload []byte + payload, err = hex.DecodeString(es.data[len(defaultIdentifier):]) + if err == nil { + if unencrypted, err := getEncryptionProvider().Decrypt(payload); err == nil { + for len(unencrypted) > 0 { + if unencrypted[len(unencrypted)-1] == 0 { + unencrypted = unencrypted[:len(unencrypted)-1] + } else { + break + } + } + decrypted = string(unencrypted) + } + } + } else { + decrypted = es.data + } + return +} diff --git a/encryptedString_test.go b/encryptedString_test.go new file mode 100644 index 0000000..7ae1bc2 --- /dev/null +++ b/encryptedString_test.go @@ -0,0 +1,212 @@ +package encryptedstring + +import ( + "encoding/xml" + "fmt" + "os" + "path" + "testing" +) + +var keyFilePath string + +func startup() (err error) { + dir := getLocalPath() + if _, err := os.Stat(dir); err != nil { + os.MkdirAll(dir, os.ModePerm) + } + keyFilePath = path.Join(dir, EncryptionKeyFileName) + encryptionKey := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} + doCreate := false + _, err = os.Stat(keyFilePath) + if err == nil { + err = os.Remove(keyFilePath) + doCreate = err == nil + } else { + doCreate = true + } + if doCreate { + err = os.WriteFile(keyFilePath, encryptionKey, os.ModePerm) + } else { + err = fmt.Errorf("unable to create custom keyfile") + } + return +} + +func cleanup() { + _, err := os.Stat(keyFilePath) + if err == nil { + os.Remove(keyFilePath) + } +} + +func TestEncryptedString(t *testing.T) { + if startup() != nil { + t.Log("test initialisation failed.\n") + cleanup() + t.FailNow() + } + + // Basic tests + es := &EncryptedString{} + es.SetValue("testData") + if es.Value() != "testData" { + t.Log("value retrieval failed\n") + cleanup() + t.FailNow() + } + expected := "$!|7567707041677369090a010203040506" + if encrypted := es.String(); encrypted != expected { + t.Logf("Expected '%s' but got '%s'\n", expected, encrypted) + t.Fail() + } + + // JSON Marshalling + marshalled, err := es.MarshalJSON() + if err == nil { + if string(marshalled) != "\""+expected+"\"" { + t.Logf("JSON Marshalling failed: Expected '%s' but got '%s'\n", "\""+expected+"\"", string(marshalled)) + t.Fail() + } + } else { + t.Logf("JSON Marshalling failed: %s\n", err) + t.Fail() + } + if !t.Failed() { + marshalled[len(marshalled)-19]++ + newValue := "testDatq" + if err := es.UnmarshalJSON(marshalled); err != nil { + t.Logf("JSON Unmarshalling failed: %s\n", err) + t.Fail() + } else if es.Value() != newValue { + t.Logf("JSON Unmarshalling failed: Expected '%s' but got '%s'", "\""+newValue+"\"\n", es.Value()) + t.Fail() + } + } + + // XML Marshalling + tmp := New("testData") + es = &tmp + expectedXML := "" + expected + "" + marshalled, err = xml.Marshal(es) + if err != nil { + t.Logf("XML Marshalling failed: %s\n", err) + t.Fail() + } else if string(marshalled) != expectedXML { + t.Logf("XML Marshalling failed: Expected '%s' but got '%s'\n", expectedXML, string(marshalled)) + t.Fail() + } + if !t.Failed() { + marshalled[34]++ + newValue := "testDatq" + if err := xml.Unmarshal(marshalled, &es); err != nil { + t.Logf("JSON Unmarshalling failed: %s\n", err) + t.Fail() + } else if es.Value() != newValue { + t.Logf("JSON Unmarshalling failed: Expected '%s' but got '%s'\n", "\""+newValue+"\"", es.Value()) + t.Fail() + } + } + + // Text Marshalling + es.SetValue("testData") + marshalled, err = es.MarshalText() + if err == nil { + if string(marshalled) != expected { + t.Logf("Text Marshalling failed: Expected '%s' but got '%s'\n", expected, string(marshalled)) + t.Fail() + } + } else { + t.Logf("Text Marshalling failed: %s\n", err) + t.Fail() + } + if !t.Failed() { + marshalled[len(marshalled)-18]++ + newValue := "testDatq" + if err := es.UnmarshalText(marshalled); err != nil { + t.Logf("Text Unmarshalling failed: %s\n", err) + t.Fail() + } else if es.Value() != newValue { + t.Logf("Text Unmarshalling failed: Expected '%s' but got '%s'\n", newValue, es.Value()) + t.Fail() + } + } + + marshalled = []byte("unencrypted") + expected = "unencrypted" + if err := es.UnmarshalText(marshalled); err != nil { + t.Logf("Text Unmarshalling of unencrypted value failed: %s\n", err) + t.Fail() + } else if es.Value() != expected { + t.Logf("Text Unmarshalling of unencrypted value failed: Expected '%s' but got '%s'\n", expected, es.Value()) + t.Fail() + } + if !es.WasUnencrypted() { + t.Logf("Text Unmarshalling of unencrypted value failed: was unencrypted flag is missing\n") + t.Fail() + } + + cleanup() +} + +func TestEncryptedStringFailures(t *testing.T) { + if startup() != nil { + t.Log("test initialisation failed.\n") + cleanup() + t.FailNow() + } + + es := &EncryptedString{} + es.SetValue("testData") + expected := "$!|7567707041677369" + + err := es.UnmarshalJSON([]byte(expected + "\"")) + if err == nil { + t.Log("JSON Unmarshalling 1 succeeded unexpectedly\n") + t.Fail() + } + + testData := "A" + expected[1:] + err = es.UnmarshalJSON([]byte("\"" + testData + "\"")) + if err != nil { + t.Log("JSON Unmarshalling 2 failed unexpectedly\n") + t.Fail() + } else if result := es.Value(); result != testData { + t.Logf("JSON Unmarshalling 2 yielded '%s' instead of '%s'\n", result, testData) + t.Fail() + } + + // testData = "" + expected + "" + testData = "<" + expected + "" + err = xml.Unmarshal([]byte(testData), es) + if err == nil { + t.Log("XML Unmarshalling 1 succeeded unexpectedly\n") + t.Fail() + } + + testData = "" + expected + "" + err = xml.Unmarshal([]byte(testData), es) + if err == nil { + t.Log("XML Unmarshalling 2 succeeded unexpectedly\n") + t.Fail() + } + + testData = "" + expected[1:] + "" + err = xml.Unmarshal([]byte(testData), es) + if err != nil { + t.Log("XML Unmarshalling 3 failed unexpectedly\n") + t.Fail() + } else if result := es.Value(); result != expected[1:] { + t.Logf("XML Unmarshalling 3 yielded '%s' instead of '%s'\n", result, expected[1:]) + t.Fail() + } + + testData = "" + expected + "" + err = xml.Unmarshal([]byte(testData), es) + if err == nil { + t.Log("XML Unmarshalling 4 succeeded unexpectedly\n") + t.Fail() + } + + cleanup() +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..5f3cd8f --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.sa-roci.de/oss/go_encryptedstring + +go 1.18 diff --git a/go_encryptedstring.code-workspace b/go_encryptedstring.code-workspace new file mode 100644 index 0000000..8312b28 --- /dev/null +++ b/go_encryptedstring.code-workspace @@ -0,0 +1,9 @@ +{ + "folders": [ + { + "name": "git.sa-roci.de/oss/go_encryptedstring", + "path": "." + } + ], + "settings": {} +} \ No newline at end of file diff --git a/helpers.go b/helpers.go new file mode 100644 index 0000000..c058e48 --- /dev/null +++ b/helpers.go @@ -0,0 +1,74 @@ +package encryptedstring + +import ( + "errors" + "os" + "path/filepath" + "strings" + "sync" +) + +const ( + // defaultIdentifier is the prefix for an encrypted representation of an actual string value + defaultIdentifier = "$!|" +) + +var ( + encryptionProviderMutex sync.Mutex + encryptionProvider IDataCryptor +) + +// Init initialises the global IDataCryptor instance, if it has not +// been set (or used and hence been initalised with a default). +func Init(idc IDataCryptor) (err error) { + encryptionProviderMutex.Lock() + defer encryptionProviderMutex.Unlock() + if encryptionProvider != nil { + return errors.New("encryptionProvider already defined") + } + encryptionProvider = idc + return +} + +func getEncryptionProvider() IDataCryptor { + encryptionProviderMutex.Lock() + defer encryptionProviderMutex.Unlock() + if encryptionProvider == nil { + encryptionProvider = NewDefaultDataCryptor() + } + return encryptionProvider +} + +func getWorkingDirectory() (workingDirectory string) { + workingDirectory = "." + fullexecpath, err := os.Executable() + if err == nil { + workingDirectory, _ = filepath.Split(fullexecpath) + workingDirectory = getOSIndependentPath(workingDirectory) + } + return +} + +// getOSIndependentPath transforms Windows-native paths into Linux-compatible ones. +func getOSIndependentPath(path string) string { + if len(path) == 0 { + return "" + } + return strings.ReplaceAll(strings.ReplaceAll(path, "\\", "/"), "//", "/") +} + +// getLocalPath returns the path to the local startup directory +func getLocalPath() string { + local := getWorkingDirectory() + if !strings.HasSuffix(local, "/") { + local += "/" + } + return getOSIndependentPath(local) +} + +func unquoteBytes(s []byte) (t []byte, ok bool) { + if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' { + return + } + return s[1 : len(s)-1], true +} diff --git a/setHidden.go b/setHidden.go new file mode 100644 index 0000000..cdf65f5 --- /dev/null +++ b/setHidden.go @@ -0,0 +1,7 @@ +// +build !windows + +package encryptedstring + +func setHidden(path string) error { + return nil +} diff --git a/setHidden_windows.go b/setHidden_windows.go new file mode 100644 index 0000000..c7e4995 --- /dev/null +++ b/setHidden_windows.go @@ -0,0 +1,21 @@ +// +build windows + +package encryptedstring + +import ( + "syscall" +) + +func setHidden(path string) error { + filenameW, err := syscall.UTF16PtrFromString(path) + if err != nil { + return err + } + + err = syscall.SetFileAttributes(filenameW, syscall.FILE_ATTRIBUTE_HIDDEN) + if err != nil { + return err + } + + return nil +}