- Inital commit.

This commit is contained in:
Naoriel Sa' Rocí 2024-05-31 19:47:03 +02:00
commit 9b833779dd
14 changed files with 635 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*.log
.vscode/

8
CHANGELOG.md Normal file
View File

@ -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.

9
IDataCryptor.go Normal file
View File

@ -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)
}

9
LICENSE Normal file
View File

@ -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.

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# git.sa-roci.de/oss/go_encryptedstring
A module for serialisable encrypted strings.

90
defaultDataCryptor.go Normal file
View File

@ -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
}

View File

@ -0,0 +1,12 @@
package encryptedstring
import (
"testing"
)
func TestNewDefaultDataCryptor(t *testing.T) {
t.Cleanup(cleanup)
NewDefaultDataCryptor()
startup()
NewDefaultDataCryptor()
}

176
encryptedString.go Normal file
View File

@ -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
}

212
encryptedString_test.go Normal file
View File

@ -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 := "<EncryptedString>" + expected + "</EncryptedString>"
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 = "<EncryptedString>" + expected + "</EncryptedString>"
testData = "<<EncryptedString>" + expected + "</EncryptedString>"
err = xml.Unmarshal([]byte(testData), es)
if err == nil {
t.Log("XML Unmarshalling 1 succeeded unexpectedly\n")
t.Fail()
}
testData = "<EncryptedString>" + expected + "</EncryptString>"
err = xml.Unmarshal([]byte(testData), es)
if err == nil {
t.Log("XML Unmarshalling 2 succeeded unexpectedly\n")
t.Fail()
}
testData = "<EncryptedString>" + expected[1:] + "</EncryptedString>"
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 = "<EncryptedString><EncryptedString>" + expected + "</EncryptString></EncryptString>"
err = xml.Unmarshal([]byte(testData), es)
if err == nil {
t.Log("XML Unmarshalling 4 succeeded unexpectedly\n")
t.Fail()
}
cleanup()
}

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module git.sa-roci.de/oss/go_encryptedstring
go 1.18

View File

@ -0,0 +1,9 @@
{
"folders": [
{
"name": "git.sa-roci.de/oss/go_encryptedstring",
"path": "."
}
],
"settings": {}
}

74
helpers.go Normal file
View File

@ -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
}

7
setHidden.go Normal file
View File

@ -0,0 +1,7 @@
// +build !windows
package encryptedstring
func setHidden(path string) error {
return nil
}

21
setHidden_windows.go Normal file
View File

@ -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
}