Add TLEP to gotell

This commit is contained in:
qowevisa 2024-06-04 19:19:11 +03:00
parent 605e1acf17
commit db9d9bcf44
22 changed files with 1536 additions and 0 deletions

2
tlep/Makefile Normal file
View File

@ -0,0 +1,2 @@
tarball:
tar -czvf tlep.tar.gz --exclude=*.tar.gz --exclude=*.prof --exclude=*.pdf --exclude=tlep ./*

158
tlep/chaos/main.go Normal file
View File

@ -0,0 +1,158 @@
package chaos
import (
"crypto/rand"
"encoding/binary"
"log"
)
// Define parameters for the Lorenz attractor.
const sigma = 10
const rho = 28
const beta = 8.0 / 3.0
// The function that represents the Lorenz system of equations.
func lorenz(x, y, z float64) (float64, float64, float64) {
dx := sigma * (y - x)
dy := x*(rho-z) - y
dz := x*y - beta*z
return dx, dy, dz
}
// The Runge-Kutta method (4th order) for a single step.
func (c *ChaosSystem) step() (float64, float64, float64) {
x := c.X
y := c.Y
z := c.Z
if c.Debug {
log.Printf("In stepping Old vals : x = %f ; y = %f ; z = %f\n", x, y, z)
}
h := c.H
k1x, k1y, k1z := lorenz(x, y, z)
k2x, k2y, k2z := lorenz(x+h*k1x/2, y+h*k1y/2, z+h*k1z/2)
k3x, k3y, k3z := lorenz(x+h*k2x/2, y+h*k2y/2, z+h*k2z/2)
k4x, k4y, k4z := lorenz(x+h*k3x, y+h*k3y, z+h*k3z)
// Combine the slopes and update the positions.
newX := x + h*(k1x+2*k2x+2*k3x+k4x)/6
newY := y + h*(k1y+2*k2y+2*k3y+k4y)/6
newZ := z + h*(k1z+2*k2z+2*k3z+k4z)/6
if c.Debug {
log.Printf("In stepping New vals : x = %f ; y = %f ; z = %f\n", newX, newY, newZ)
}
c.X = newX
c.Y = newY
c.Z = newZ
return newX, newY, newZ
}
type ChaosSystem struct {
Version int
X float64
Y float64
Z float64
H float64
Debug bool
XMult float64
YMult float64
ZMult float64
}
func CreateNewChaosSystem() *ChaosSystem {
var _c ChaosSystem
_c.Version = LATEST_VERSION
return &_c
}
func (c *ChaosSystem) Init(x, y, z, h float64) {
c.X = x
c.Y = y
c.Z = z
c.H = h
c.Debug = false
c.Version = LATEST_VERSION
}
func randomFloat64() (float64, error) {
var b [8]byte
if _, err := rand.Read(b[:]); err != nil {
return 0, err
}
return float64(binary.LittleEndian.Uint64(b[:])) / (1 << 64), nil
}
func (c *ChaosSystem) InitRandom() error {
x, err := randomFloat64()
if err != nil {
return err
}
y, err := randomFloat64()
if err != nil {
return err
}
z, err := randomFloat64()
if err != nil {
return err
}
c.Init(x, y, z, 0.1)
return nil
}
func (c *ChaosSystem) Burn(h uint) {
var i uint
for i = 0; i < h; i++ {
c.step()
}
}
func (c *ChaosSystem) SetMults(xM, yM, zM float64) {
c.XMult = xM
c.YMult = yM
c.ZMult = zM
}
func (c *ChaosSystem) ToggleDebug() {
c.Debug = !c.Debug
}
func (c *ChaosSystem) getByteVal() uint8 {
var xM, yM, zM float64
if c.XMult != 0 {
xM = c.XMult
} else {
xM = 13
}
if c.YMult != 0 {
yM = c.YMult
} else {
yM = 19
}
if c.ZMult != 0 {
zM = c.ZMult
} else {
zM = 11
}
hash := func(val float64, mult float64) uint8 {
scaledVal := val * mult * mult
// Convert to an int and take the bits we're interested in
intVal := int(scaledVal * scaledVal * scaledVal)
// XOR the parts of the integer to spread out the impact
return uint8((intVal>>8)^intVal) & 0xFF
}
xVal := hash(c.X, xM)
yVal := hash(c.Y, yM)
zVal := hash(c.Z, zM)
return xVal ^ yVal ^ zVal
}
func (c *ChaosSystem) GetPassword(lenght uint) []byte {
var i uint
var ret []byte
for i = 0; i < lenght; i++ {
c.step()
ret = append(ret, c.getByteVal())
}
return ret
}

40
tlep/chaos/tr.go Normal file
View File

@ -0,0 +1,40 @@
package chaos
import (
"bytes"
"encoding/gob"
"errors"
)
const (
LATEST_VERSION = 1
)
var (
invalidVersion = errors.New("Version is incopatible")
)
func (c *ChaosSystem) Bytes() ([]byte, error) {
var buf bytes.Buffer
encoder := gob.NewEncoder(&buf)
err := encoder.Encode(c)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func GetFromBytes(data []byte) (*ChaosSystem, error) {
var cs ChaosSystem
buf := bytes.NewBuffer(data)
decoder := gob.NewDecoder(buf)
err := decoder.Decode(&cs)
if err != nil {
return nil, err
}
if cs.Version != LATEST_VERSION {
return nil, invalidVersion
}
return &cs, nil
}

72
tlep/ecdh/main.go Normal file
View File

@ -0,0 +1,72 @@
package ecdh
import (
"crypto/ecdh"
"crypto/rand"
"errors"
)
var Curve = ecdh.P521()
var ERROR_SharedNotComputed = errors.New("Shared secret is not computed!")
type ECDHConnection struct {
privateKey *ecdh.PrivateKey
otherPublicKey *ecdh.PublicKey
sharedSecret []byte
}
func CreateNewConnection() (*ECDHConnection, error) {
privKey, err := generatePrivKey()
if err != nil {
return nil, err
}
return &ECDHConnection{
privateKey: privKey,
}, nil
}
func (c *ECDHConnection) GetMyPublicKeyBytes() []byte {
return c.privateKey.PublicKey().Bytes()
}
func (c *ECDHConnection) AcceptOtherPubKeyBytes(pubBytes []byte) error {
pubKey, err := Curve.NewPublicKey(pubBytes)
if err != nil {
return err
}
c.otherPublicKey = pubKey
shared, err := c.privateKey.ECDH(pubKey)
if err != nil {
return err
}
c.sharedSecret = shared
return nil
}
func (c *ECDHConnection) GetShared() ([]byte, error) {
if len(c.sharedSecret) == 0 {
return nil, ERROR_SharedNotComputed
}
return c.sharedSecret, nil
}
func generatePrivKey() (*ecdh.PrivateKey, error) {
privateKey, err := Curve.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
return privateKey, err
}
func AreKeysEqual(a, b []byte) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}

62
tlep/encrypt/aes.go Normal file
View File

@ -0,0 +1,62 @@
package encrypt
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
)
var tooShort = errors.New("Too Short")
type Message struct {
Data []byte
}
// NOTE: should use only 32 byte key
// key can be derived via hkdf package
func Encrypt(plaintext, key []byte) (*Message, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
ciphertext := gcm.Seal(nil, nonce, plaintext, nil)
return &Message{
Data: append(nonce, ciphertext...),
}, nil
}
// NOTE: should use only 32 byte key
// key can be derived via hkdf package
func Decrypt(ciphertext, key []byte) (*Message, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, tooShort
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return &Message{
Data: plaintext,
}, nil
}

7
tlep/errors.go Normal file
View File

@ -0,0 +1,7 @@
package tlep
import "errors"
var (
IS_NIL = errors.New("Is nil")
)

12
tlep/gmyerr/wrapper.go Normal file
View File

@ -0,0 +1,12 @@
package gmyerr
import (
"fmt"
)
func WrapPrefix(prefix string, err error) error {
if err == nil {
return nil
}
return fmt.Errorf("%s: %w", prefix, err)
}

22
tlep/hkdf/main.go Normal file
View File

@ -0,0 +1,22 @@
package hkdf
import (
"crypto/sha256"
"golang.org/x/crypto/hkdf"
)
func DeriveAESKeyFromLongKeyAndInfo(shared, info []byte) ([]byte, error) {
// Create reader for HKDF
hash := sha256.New
salt := []byte("EIZBq3CdxfeaGxZ2Zj7QIIhExgbhkdhDW4ePrDheEaEFmzRYdJqrYnddAGk5pqWq")
// Contextual information
hkdf := hkdf.New(hash, shared, salt, info)
// Generate and return the key
aesKey := make([]byte, 32)
if _, err := hkdf.Read(aesKey); err != nil {
return nil, err
}
return aesKey, nil
}

83
tlep/json.go Normal file
View File

@ -0,0 +1,83 @@
package tlep
import (
"encoding/json"
"fmt"
"git.qowevisa.me/Qowevisa/gotell/tlep/gmyerr"
"io"
"os"
)
const (
TLEPDirName = "tlep"
)
func (t *TLEP) getFileName() string {
return fmt.Sprintf("%s/%s.tlep", TLEPDirName, t.Name)
}
// don't care for errors for now
func canOpenDir(dirname string) bool {
dir, err := os.Open(dirname)
if err != nil {
// TODO check for errors
return false
}
stat, err := dir.Stat()
if err != nil {
// TODO check for errors
return false
}
return stat.IsDir()
}
func (t *TLEP) SaveToFile() error {
canI := canOpenDir(TLEPDirName)
if !canI {
err := os.Mkdir(TLEPDirName, 0755)
if err != nil {
return gmyerr.WrapPrefix("os.Mkdir", err)
}
}
s, err := json.Marshal(t)
if err != nil {
return gmyerr.WrapPrefix("json.Marshal", err)
}
file, err := os.Create(t.getFileName())
defer file.Close()
if err != nil {
return gmyerr.WrapPrefix("os.Create", err)
}
_, err = file.Write(s)
if err != nil {
return gmyerr.WrapPrefix("file.Write", err)
}
return nil
}
func LoadFromFileByName(name string) (*TLEP, error) {
var t TLEP
t.Name = name
file, err := os.Open(t.getFileName())
defer file.Close()
if err != nil {
return nil, gmyerr.WrapPrefix("os.Create", err)
}
var result []byte
buf := make([]byte, 10240)
for {
n, err := file.Read(buf)
if err == io.EOF {
break
}
if err != nil {
return nil, gmyerr.WrapPrefix("file.Write", err)
}
result = append(result, buf[:n]...)
}
err = json.Unmarshal(result, &t)
if err != nil {
return nil, gmyerr.WrapPrefix("json.Unmarshal", err)
}
return &t, nil
}

66
tlep/main.go Normal file
View File

@ -0,0 +1,66 @@
package tlep
import (
"fmt"
)
func main() {
tlep1, err := InitTLEP("user2")
if err != nil {
panic(err)
}
err = tlep1.CBESInitRandom()
if err != nil {
panic(err)
}
keyA, err := tlep1.ECDHGetPublicKey()
if err != nil {
panic(err)
}
tlep2, err := InitTLEP("user1")
if err != nil {
panic(err)
}
keyB, err := tlep2.ECDHGetPublicKey()
if err != nil {
panic(err)
}
// Acception
err = tlep1.ECDHApplyOtherKeyBytes(keyB)
if err != nil {
panic(err)
}
err = tlep2.ECDHApplyOtherKeyBytes(keyA)
if err != nil {
panic(err)
}
// First EA encryption
fmt.Printf("TLEP1 CBES specs: %#v\n", tlep1.CBES)
cbesSpecs, err := tlep1.CBESGetBytes()
if err != nil {
panic(err)
}
encryptedCBESSpecs, err := tlep1.EncryptMessageEA(cbesSpecs)
if err != nil {
panic(err)
}
realSpecs, err := tlep2.DecryptMessageEA(encryptedCBESSpecs)
if err != nil {
panic(err)
}
tlep2.CBESSetFromBytes(realSpecs)
fmt.Printf("TLEP2 CBES specs: %#v\n", tlep2.CBES)
// Second layer CAFEA encryption
someMsg := "lol real msg i don't wanna joke xdd"
fmt.Printf("Sending %s to TLEP2\n", someMsg)
encryptedMsg, err := tlep1.EncryptMessageCAFEA([]byte(someMsg))
if err != nil {
panic(err)
}
fmt.Printf("Encrypted Message = %v\n", encryptedMsg)
decryptedMsg, err := tlep2.DecryptMessageCAFEA(encryptedMsg)
if err != nil {
panic(err)
}
fmt.Printf("Getting %s on TLEP2 from TLEP1\n", decryptedMsg)
}

View File

@ -0,0 +1,72 @@
package monkeylang
import (
"fmt"
"git.qowevisa.me/Qowevisa/gotell/tlep/gmyerr"
"os"
"time"
)
// don't care for errors for now
func canOpenDir(dirname string) bool {
dir, err := os.Open(dirname)
if err != nil {
// TODO check for errors
return false
}
stat, err := dir.Stat()
if err != nil {
// TODO check for errors
return false
}
return stat.IsDir()
}
func GetDictionaryForUser(user string, getStat bool) (*Dictionary, error) {
canI := canOpenDir(DictsDirName)
if !canI {
err := os.Mkdir(DictsDirName, 0755)
if err != nil {
return nil, gmyerr.WrapPrefix("os.Mkdir", err)
}
}
exists, err := DoesDictExists(user)
if err != nil {
return nil, gmyerr.WrapPrefix("parser.DoWeCanLoadDict", err)
}
if !exists {
if getStat {
fmt.Println("Dictionary can't be find. Creating...")
}
befCreat := time.Now()
dict, err := CreateNewDictionary()
if err != nil {
return nil, gmyerr.WrapPrefix("lang.CreateNewDictionary", err)
}
if getStat {
fmt.Println("Creation time is ", time.Now().Sub(befCreat))
fmt.Println("Saving to file...")
}
befSave := time.Now()
err = SaveToFile(*dict, user)
if err != nil {
return nil, gmyerr.WrapPrefix("parser.SaveToFile", err)
}
if getStat {
fmt.Println("Saving time is ", time.Now().Sub(befSave))
}
return dict, nil
}
if getStat {
fmt.Println("Dictionary can be find. Loading...")
}
befLoad := time.Now()
dict, err := LoadFromFile(user)
if err != nil {
return nil, gmyerr.WrapPrefix("parser.LoadFromFile", err)
}
if getStat {
fmt.Println("Loading time is ", time.Now().Sub(befLoad))
}
return dict, nil
}

124
tlep/monkeylang/dict.go Normal file
View File

@ -0,0 +1,124 @@
package monkeylang
import (
"crypto/rand"
"crypto/sha512"
"encoding/base32"
"fmt"
"git.qowevisa.me/Qowevisa/gotell/tlep/monkeylang/myerr"
"git.qowevisa.me/Qowevisa/gotell/tlep/shuffle"
"strings"
)
const (
VERSION_1 = 1 + iota
)
const LATEST_VERSION = VERSION_1
type WORD_VAL uint16
const DICT_LEN = 0x010000
type Dictionary struct {
Values [DICT_LEN]WORD_VAL
Words [DICT_LEN]string
}
func CreateNewDictionary() (*Dictionary, error) {
var d Dictionary
dummyKey := make([]byte, DICT_LEN)
n, err := rand.Read(dummyKey)
if err != nil {
return nil, err
}
if n != len(dummyKey) {
return nil, myerr.INTERNAL_ERROR
}
for i := 0; i < DICT_LEN; i++ {
d.Values[i] = WORD_VAL(i)
}
newVals := shuffle.Shuffle(d.Values[:], dummyKey)
if len(newVals) != len(d.Values) {
return nil, myerr.INTERNAL_ERROR
}
for i, nv := range newVals {
d.Values[i] = nv
}
words := GenerateStrongWords(DICT_LEN)
for i, word := range words {
d.Words[i] = word
}
return &d, nil
}
func (d *Dictionary) GetFirstWords(n int) []string {
return d.Words[:n]
}
func (d *Dictionary) GetFirstValues(n int) []WORD_VAL {
return d.Values[:n]
}
func allUniqueT[T comparable](strings []T) (int, bool) {
notUnique := 0
seen := make(map[T]struct{})
for _, s := range strings {
if _, ok := seen[s]; ok {
notUnique++
}
seen[s] = struct{}{}
}
return notUnique, notUnique == 0
}
func (d *Dictionary) GetStat() string {
stt := fmt.Sprintf("D Words Len : %d\n", len(d.Values))
mNU, mIAU := allUniqueT(d.Words[:])
stt += fmt.Sprintf("D Meanings Not Unique : %d ; %t\n", mNU, mIAU)
wNU, wIAU := allUniqueT(d.Values[:])
stt += fmt.Sprintf("D Words Not Unique : %d ; %t\n", wNU, wIAU)
return stt
}
func (d *Dictionary) GetFingerprint() string {
mm := strings.Join(d.Words[:], ".")
var ww []byte
for _, w := range d.Values {
ww = append(ww, byte(w>>8), byte(w))
}
ww = append(ww, []byte(mm)...)
hash := sha512.Sum512(ww)
fingerprint := make([]byte, base32.StdEncoding.EncodedLen(len(hash)))
base32.StdEncoding.Encode(fingerprint, hash[:])
return string(fingerprint[:])
}
func (d *Dictionary) GetFingerprintBytes() []byte {
mm := strings.Join(d.Words[:], ".")
var ww []byte
for _, w := range d.Values {
ww = append(ww, byte(w>>8), byte(w))
}
ww = append(ww, []byte(mm)...)
hash := sha512.Sum512(ww)
fingerprint := make([]byte, base32.StdEncoding.EncodedLen(len(hash)))
base32.StdEncoding.Encode(fingerprint, hash[:])
return fingerprint[:]
}
func (d *Dictionary) GetFingerprintWithInfo(info string) string {
mm := strings.Join(d.Words[:], ".")
var ww []byte
for _, w := range d.Values {
ww = append(ww, byte(w>>8), byte(w))
}
ww = append(ww, []byte(mm)...)
ww = append(ww, []byte(info)...)
hash := sha512.Sum512(ww)
fingerprint := make([]byte, base32.StdEncoding.EncodedLen(len(hash)))
base32.StdEncoding.Encode(fingerprint, hash[:])
return string(fingerprint[:])
}

76
tlep/monkeylang/json.go Normal file
View File

@ -0,0 +1,76 @@
package monkeylang
import (
"encoding/json"
"fmt"
"git.qowevisa.me/Qowevisa/gotell/tlep/gmyerr"
"io"
"os"
)
const (
DictsDirName = "mklgs"
)
const extension = ".dict.mklg"
func getFileName(prefix string) string {
return fmt.Sprintf("%s/%s%s",
DictsDirName, prefix, extension,
)
}
func SaveToFile(d Dictionary, prefix string) error {
s, err := json.Marshal(d)
if err != nil {
return gmyerr.WrapPrefix("json.Marshal", err)
}
file, err := os.Create(getFileName(prefix))
defer file.Close()
if err != nil {
return gmyerr.WrapPrefix("os.Create", err)
}
_, err = file.Write(s)
if err != nil {
return gmyerr.WrapPrefix("file.Write", err)
}
return nil
}
func DoesDictExists(prefix string) (bool, error) {
file, err := os.Open(getFileName(prefix))
defer file.Close()
if os.IsNotExist(err) {
return false, nil
}
if err != nil {
return true, gmyerr.WrapPrefix("os.Open", err)
}
return true, nil
}
func LoadFromFile(prefix string) (*Dictionary, error) {
var d Dictionary
file, err := os.Open(getFileName(prefix))
defer file.Close()
if err != nil {
return nil, gmyerr.WrapPrefix("os.Create", err)
}
var result []byte
buf := make([]byte, 10240)
for {
n, err := file.Read(buf)
if err == io.EOF {
break
}
if err != nil {
return nil, gmyerr.WrapPrefix("file.Write", err)
}
result = append(result, buf[:n]...)
}
err = json.Unmarshal(result, &d)
if err != nil {
return nil, gmyerr.WrapPrefix("json.Unmarshal", err)
}
return &d, nil
}

73
tlep/monkeylang/lang.go Normal file
View File

@ -0,0 +1,73 @@
package monkeylang
import (
"math/rand"
)
var vowels = []string{"a", "e", "i", "o", "u", "ai", "ei", "oi", "ou", "au"}
var consonants = []string{"b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "qu", "r", "s", "t", "v", "w", "x", "y", "z"}
var consonantClusters = []string{"bl", "br", "ch", "cl", "cr", "dr", "fl", "fr", "gl", "gr", "pl", "pr", "sc", "sh", "sk", "sl", "sm", "sn", "sp", "st", "str", "sw", "th", "tr", "wh", "wr"}
var consonants2 = []string{"b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "qu", "r", "s", "t", "v", "w", "x", "y", "z", "bl", "br", "ch", "cl", "cr", "dr", "fl", "fr", "gl", "gr", "pl", "pr", "sc", "sh", "sk", "sl", "sm", "sn", "sp", "st", "str", "sw", "th", "tr", "wh", "wr"}
var syllablePatterns = []string{"CV", "CVC", "VC"}
func randomElement(choices []string) string {
return choices[rand.Intn(len(choices))]
}
func generateSyllable() string {
pattern := randomElement(syllablePatterns)
syllable := ""
for _, char := range pattern {
switch char {
case 'C':
syllable += randomElement(consonants2)
case 'V':
syllable += randomElement(vowels)
}
}
return syllable
}
func generateWord(syllableCount int) string {
word := ""
for i := 0; i < syllableCount; i++ {
word += generateSyllable()
}
return word
}
func GenerateRandomWords(numWords, minSyllables, maxSyllables int) []string {
words := make([]string, numWords)
seen := make(map[string]bool)
i := 0
for i < numWords {
syllableCount := rand.Intn(maxSyllables-minSyllables+1) + minSyllables
tmpWord := generateWord(syllableCount)
_, saw := seen[tmpWord]
if saw {
continue
}
words[i] = tmpWord
i++
seen[tmpWord] = true
}
return words
}
func GenerateRandom_NON_UNIQUE_Words(numWords, minSyllables, maxSyllables int) []string {
words := make([]string, numWords)
for i := 0; i < numWords; i++ {
syllableCount := rand.Intn(maxSyllables-minSyllables+1) + minSyllables
words[i] = generateWord(syllableCount)
}
return words
}
func GenerateSimpleWords(numWords int, unique bool) []string {
return GenerateRandomWords(numWords, 2, 3)
}
func GenerateStrongWords(numWords int) []string {
return GenerateRandomWords(numWords, 2, 3)
}

View File

@ -0,0 +1,10 @@
package myerr
import (
"errors"
)
var (
INTERNAL_ERROR = errors.New("Internal error")
UNIQUENESS_ERROR = errors.New("Are not unique")
)

6
tlep/purpose.ntx Normal file
View File

@ -0,0 +1,6 @@
Three Lock Encryption Protocol
This is a protocol of most inefficient encryption algorithm for most secure message tranfser.
It is paranoidal and maybe diabolical.
Monkey Chaos Ecdh
MECHA

20
tlep/shuffle/fast_shfl.go Normal file
View File

@ -0,0 +1,20 @@
package shuffle
import "math/rand"
func FastShuffle[T Numeric](ar []T, key []byte) []T {
if len(key) < 4 {
return ar
}
var seed int64
seed = int64(key[0])
seed += int64(key[1]) << 8
seed += int64(key[2]) << 16
seed += int64(key[3]) << 24
r := rand.New(rand.NewSource(seed))
r.Shuffle(len(ar), func(i, j int) {
j = rand.Intn(i + 1)
ar[i], ar[j] = ar[j], ar[i]
})
return ar
}

View File

@ -0,0 +1,102 @@
package shuffle
import (
"crypto/rand"
"fmt"
"log"
"math/big"
)
const (
n = 5
samplesNum = 300000
)
func factorial(n int) *big.Int {
return factorial_body(n, big.NewInt(1))
}
func factorial_body(n int, acc *big.Int) *big.Int {
if n == 0 {
return acc
}
acc.Mul(acc, big.NewInt(int64(n)))
return factorial_body(n-1, acc)
}
func ChiSquare(obs, exp []float64) (float64, error) {
if len(obs) != len(exp) {
return 0, BENCHMARK_LEN_DN_MATCH
}
var result float64
result = 0
for i, a := range obs {
b := exp[i]
if a == 0 && b == 0 {
continue
}
result += (a - b) * (a - b) / b
}
return result, nil
}
func bigChiSquare(observed []int, expected *big.Float) *big.Float {
chiSquare := big.NewFloat(0)
for _, obs := range observed {
obsFloat := big.NewFloat(float64(obs))
diff := new(big.Float).Sub(obsFloat, expected)
squaredDiff := new(big.Float).Mul(diff, diff)
term := new(big.Float).Quo(squaredDiff, expected)
chiSquare.Add(chiSquare, term)
}
return chiSquare
}
func GetBenchmarkN() int {
return n
}
func GetBenchmarkForShuffle[T Numeric](alg ShuffleNumericAlg[T], keyLen int, fullDebug bool) error {
perms := map[[n]T]int{}
for i := 0; i < samplesNum; i++ {
if fullDebug {
log.Printf("Running %d sample\n", i)
}
arr := [n]T{zeroValue[T]()}
for i := 0; i < n; i++ {
arr[i] = T(i)
}
//
dummyKey := make([]byte, keyLen)
keyN, err := rand.Read(dummyKey)
if err != nil {
return err
}
if keyN != len(dummyKey) {
return BENCHMARK_INTERNAL_ERROR
}
alg(arr[:], dummyKey)
//
perms[arr]++
}
fact := factorial(n)
factFloat := new(big.Float).SetInt(fact)
// Calculate expected value
samplesFloat := big.NewFloat(float64(samplesNum))
expectedBig := new(big.Float).Quo(samplesFloat, factFloat)
if fullDebug {
log.Printf("expectedBig is %f\n", expectedBig)
log.Printf("factorial is %d\n", factorial(n))
}
observed := make([]int, 0, len(perms))
for _, count := range perms {
// log.Printf("Getting count from perm = %d\n", count)
observed = append(observed, count)
}
val := bigChiSquare(observed, expectedBig)
fmt.Printf("Chi-Square value: %s\n", val.Text('f', 10))
return nil
}

8
tlep/shuffle/myerr.go Normal file
View File

@ -0,0 +1,8 @@
package shuffle
import "errors"
var (
BENCHMARK_INTERNAL_ERROR = errors.New("Internal error")
BENCHMARK_LEN_DN_MATCH = errors.New("Lengths do not match")
)

149
tlep/shuffle/shfl.go Normal file
View File

@ -0,0 +1,149 @@
package shuffle
func allActive(ar []bool) bool {
for _, b := range ar {
if b == false {
return false
}
}
return true
}
func haveTrue(ar []bool) int {
c := 0
for _, b := range ar {
if b {
c++
}
}
return c
}
func hashIndex(x, i int) int {
return 13*x + 11*i
}
func zeroValue[T comparable]() T {
var zero T
return zero
}
type Numeric interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
~float32 | ~float64
}
type ShuffleAlg[T comparable] func([]T, []byte) []T
type ShuffleNumericAlg[T Numeric] func([]T, []byte) []T
type ShuffleNumericAlgWOChanging[T Numeric] func([]T, []byte) []T
func Shuffle[T comparable](msg []T, simmetricKey []byte) []T {
// L HAS to be the lenght of the bytes, not runes
l := len(msg)
var i int
//
var ar []T
i = 0
for {
if i == l {
break
}
ar = append(ar, zeroValue[T]())
i++
}
//
i = 0
var activIdx []bool
for {
if i == l {
break
}
activIdx = append(activIdx, false)
i++
}
//
c := 0
sL := len(simmetricKey)
passCounter := 0
for {
if allActive(activIdx) {
break
}
// main part
var newIdx int
hashI := 0
for {
newIdx = hashIndex(int(simmetricKey[c]), hashI) % l
if activIdx[newIdx] {
hashI++
} else {
break
}
}
newB := msg[newIdx]
ar[passCounter] = newB
activIdx[newIdx] = true
c++
if c == sL {
c = 0
}
passCounter++
}
return ar
}
func Unshuffle[T comparable](msg []T, simmetricKey []byte) []T {
// L HAS to be the lenght of the bytes, not runes
l := len(msg)
var i int
//
var ar []T
i = 0
for {
if i == l {
break
}
ar = append(ar, zeroValue[T]())
i++
}
//
i = 0
var activIdx []bool
for {
if i == l {
break
}
activIdx = append(activIdx, false)
i++
}
//
c := 0
sL := len(simmetricKey)
passCounter := 0
for {
if allActive(activIdx) {
break
}
// main part
var newIdx int
hashI := 0
for {
newIdx = hashIndex(int(simmetricKey[c]), hashI) % l
if activIdx[newIdx] {
hashI++
} else {
break
}
}
newB := msg[passCounter]
ar[newIdx] = newB
activIdx[newIdx] = true
c++
if c == sL {
c = 0
}
passCounter++
}
return ar
}

365
tlep/system.go Normal file
View File

@ -0,0 +1,365 @@
package tlep
import (
"errors"
"git.qowevisa.me/Qowevisa/gotell/tlep/chaos"
"git.qowevisa.me/Qowevisa/gotell/tlep/ecdh"
"git.qowevisa.me/Qowevisa/gotell/tlep/encrypt"
"git.qowevisa.me/Qowevisa/gotell/tlep/gmyerr"
"git.qowevisa.me/Qowevisa/gotell/tlep/hkdf"
"git.qowevisa.me/Qowevisa/gotell/tlep/monkeylang"
"git.qowevisa.me/Qowevisa/gotell/tlep/shuffle"
)
type TLEPLevel uint8
var (
TLEP_LEVEL_NO_CONNECTION TLEPLevel = 0
TLEP_LEVEL_ECDH TLEPLevel = 1
TLEP_LEVEL_ECDH_CBES TLEPLevel = 2
TLEP_LEVEL_ECDH_CBES_MKLG TLEPLevel = 3
)
// Three Layer Encryption Protocol schema
type TLEP struct {
// Security Layer Level
SLLevel TLEPLevel
Name string
// Elliptic-Curve Diffie-Hellman
ECDHConnection *ecdh.ECDHConnection
// Chaos-Based Encryption System
CBES *chaos.ChaosSystem
// MonKeyLanG Dictionary
MKLGDict *monkeylang.Dictionary
}
func InitTLEP(name string) (*TLEP, error) {
var t TLEP
t.Name = name
conn, err := ecdh.CreateNewConnection()
if err != nil {
return nil, gmyerr.WrapPrefix("ecdh.CreateNewConnection", err)
}
t.ECDHConnection = conn
cbes := chaos.CreateNewChaosSystem()
t.CBES = cbes
t.SLLevel = TLEP_LEVEL_NO_CONNECTION
return &t, nil
}
func (t *TLEP) ECDHGetPublicKey() ([]byte, error) {
if t.ECDHConnection == nil {
return nil, gmyerr.WrapPrefix("t.ECDHConnection", IS_NIL)
}
ar := t.ECDHConnection.GetMyPublicKeyBytes()
return ar, nil
}
func (t *TLEP) ECDHApplyOtherKeyBytes(otherKey []byte) error {
if t.ECDHConnection == nil {
return gmyerr.WrapPrefix("t.ECDHConnection", IS_NIL)
}
err := t.ECDHConnection.AcceptOtherPubKeyBytes(otherKey)
if err != nil {
return gmyerr.WrapPrefix("t.ECDHConnection.AcceptOtherPubKeyBytes", err)
}
t.SLLevel = TLEP_LEVEL_ECDH
return nil
}
func (t *TLEP) CBESInitRandom() error {
if t.CBES == nil {
return gmyerr.WrapPrefix("t.CBES", IS_NIL)
}
err := t.CBES.InitRandom()
if err != nil {
return gmyerr.WrapPrefix("t.CBES.InitRandom", IS_NIL)
}
t.SLLevel = TLEP_LEVEL_ECDH_CBES
return nil
}
func (t *TLEP) CBESGetBytes() ([]byte, error) {
if t.CBES == nil {
return nil, gmyerr.WrapPrefix("t.CBES", IS_NIL)
}
return t.CBES.Bytes()
}
func (t *TLEP) CBESSetFromBytes(bytes []byte) error {
newCBES, err := chaos.GetFromBytes(bytes)
if err != nil {
return gmyerr.WrapPrefix("chaos.GetFromBytes", err)
}
t.CBES = newCBES
t.SLLevel = TLEP_LEVEL_ECDH_CBES
return nil
}
func (t *TLEP) CBESGetPassword(passLen uint) ([]byte, error) {
if t.CBES == nil {
return nil, gmyerr.WrapPrefix("t.CBES", IS_NIL)
}
return t.CBES.GetPassword(passLen), nil
}
func (t *TLEP) EncryptMessageEA(message []byte) ([]byte, error) {
if t.ECDHConnection == nil {
return nil, gmyerr.WrapPrefix("t.ECDHConnection", IS_NIL)
}
shared, err := t.ECDHConnection.GetShared()
if errors.Is(err, ecdh.ERROR_SharedNotComputed) {
return nil, ecdh.ERROR_SharedNotComputed
}
aesKey, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(shared, []byte("ECDH_BASE"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
msg, err := encrypt.Encrypt(message, aesKey)
if err != nil {
return nil, gmyerr.WrapPrefix("encrypt.Encrypt", err)
}
return msg.Data, nil
}
func (t *TLEP) DecryptMessageEA(message []byte) ([]byte, error) {
if t.ECDHConnection == nil {
return nil, gmyerr.WrapPrefix("t.ECDHConnection", IS_NIL)
}
shared, err := t.ECDHConnection.GetShared()
if errors.Is(err, ecdh.ERROR_SharedNotComputed) {
return nil, ecdh.ERROR_SharedNotComputed
}
aesKey, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(shared, []byte("ECDH_BASE"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
msg, err := encrypt.Decrypt(message, aesKey)
if err != nil {
return nil, gmyerr.WrapPrefix("encrypt.Decrypt", err)
}
return msg.Data, nil
}
func (t *TLEP) CanIUseEA() (bool, error) {
if t.ECDHConnection == nil {
return false, gmyerr.WrapPrefix("t.ECDHConnection", IS_NIL)
}
_, err := t.ECDHConnection.GetShared()
if errors.Is(err, ecdh.ERROR_SharedNotComputed) {
return false, ecdh.ERROR_SharedNotComputed
}
return t.SLLevel > TLEP_LEVEL_ECDH, nil
}
func (t *TLEP) EncryptMessageCAFEA(message []byte) ([]byte, error) {
// First Layer Encryption
if t.ECDHConnection == nil {
return nil, gmyerr.WrapPrefix("t.ECDHConnection", IS_NIL)
}
shared, err := t.ECDHConnection.GetShared()
if errors.Is(err, ecdh.ERROR_SharedNotComputed) {
return nil, ecdh.ERROR_SharedNotComputed
}
aesKey, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(shared, []byte("CAFEA_ENCRYPTION_ECDH"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// First Layer Encryption
msg, err := encrypt.Encrypt(message, aesKey)
if err != nil {
return nil, gmyerr.WrapPrefix("encrypt.Encrypt", err)
}
// Second Layer Encryption
cbesLongKey, err := t.CBESGetPassword(512)
if err != nil {
return nil, gmyerr.WrapPrefix("t.CBESGetPassword", err)
}
aesKey2, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(cbesLongKey, []byte("CAFEA_ENCRYPTION_CBES"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// Second Layer Encryption
msg2, err := encrypt.Encrypt(msg.Data, aesKey2)
if err != nil {
return nil, gmyerr.WrapPrefix("encrypt.Encrypt", err)
}
return msg2.Data, nil
}
func (t *TLEP) DecryptMessageCAFEA(message []byte) ([]byte, error) {
// Second Layer Decryption
cbesLongKey, err := t.CBESGetPassword(512)
if err != nil {
return nil, gmyerr.WrapPrefix("t.CBESGetPassword", err)
}
aesKey2, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(cbesLongKey, []byte("CAFEA_ENCRYPTION_CBES"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// Second Layer Decryption
msg2, err := encrypt.Decrypt(message, aesKey2)
if err != nil {
return nil, gmyerr.WrapPrefix("encrypt.Decrypt", err)
}
// First Layer Decryption
if t.ECDHConnection == nil {
return nil, gmyerr.WrapPrefix("t.ECDHConnection", IS_NIL)
}
shared, err := t.ECDHConnection.GetShared()
if errors.Is(err, ecdh.ERROR_SharedNotComputed) {
return nil, ecdh.ERROR_SharedNotComputed
}
aesKey, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(shared, []byte("CAFEA_ENCRYPTION_ECDH"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// First Layer Decryption
msg, err := encrypt.Decrypt(msg2.Data, aesKey)
if err != nil {
return nil, gmyerr.WrapPrefix("encrypt.Decrypt", err)
}
return msg.Data, nil
}
// Monkeylang ECDH Shuffle CHaos-based AES-256-GCM
func (t *TLEP) EncryptMessageMESCHA(message []byte) ([]byte, error) {
// First Layer Key
if t.ECDHConnection == nil {
return nil, gmyerr.WrapPrefix("t.ECDHConnection", IS_NIL)
}
shared, err := t.ECDHConnection.GetShared()
if errors.Is(err, ecdh.ERROR_SharedNotComputed) {
return nil, ecdh.ERROR_SharedNotComputed
}
// First Layer Encryption
aesKey, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(shared, []byte("MESCHA_ENCRYPTION_ECDH"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// First Layer Encryption
msg, err := encrypt.Encrypt(message, aesKey)
if err != nil {
return nil, gmyerr.WrapPrefix("encrypt.Encrypt", err)
}
// First Layer Shuffle
shfKey, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(shared, []byte("MESCHA_SHUFFLE_ECDH"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// First Layer Shuffle
shuffledMsg := shuffle.Shuffle(msg.Data, shfKey)
// Second Layer Key
cbesLongKey, err := t.CBESGetPassword(512)
if err != nil {
return nil, gmyerr.WrapPrefix("t.CBESGetPassword", err)
}
// Second Layer Encryption
aesKey2, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(cbesLongKey, []byte("MESCHA_ENCRYPTION_CBES"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// Second Layer Encryption
msg2, err := encrypt.Encrypt(shuffledMsg, aesKey2)
if err != nil {
return nil, gmyerr.WrapPrefix("encrypt.Encrypt", err)
}
// Second Layer Shuffle
shfKey2, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(cbesLongKey, []byte("MESCHA_SHUFFLE_CBES"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// Second Layer Shuffle
shuffledMsg2 := shuffle.Shuffle(msg2.Data, shfKey2)
// Third Layer Key
mklgPrint := t.MKLGDict.GetFingerprintBytes()
// Third Layer Encryption
aesKey3, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(mklgPrint, []byte("MESCHA_ENCRYPTION_MKLG"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// Third Layer Encryption
msg3, err := encrypt.Encrypt(shuffledMsg2, aesKey3)
if err != nil {
return nil, gmyerr.WrapPrefix("encrypt.Encrypt", err)
}
// Third Layer Shuffle
shfKey3, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(mklgPrint, []byte("MESCHA_SHUFFLE_MKLG"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// Third Layer Shuffle
shuffledMsg3 := shuffle.Shuffle(msg3.Data, shfKey3)
return shuffledMsg3, nil
}
// Monkeylang ECDH Shuffle CHaos-based AES-256-GCM
func (t *TLEP) DecryptMessageMESCHA(message []byte) ([]byte, error) {
// Third Layer Key
mklgPrint := t.MKLGDict.GetFingerprintBytes()
// Third Layer Shuffle
shfKey3, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(mklgPrint, []byte("MESCHA_SHUFFLE_MKLG"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// Third Layer Shuffle
unshuffledMsg3 := shuffle.Unshuffle(message, shfKey3)
// Third Layer Decryption
aesKey3, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(mklgPrint, []byte("MESCHA_ENCRYPTION_MKLG"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// Third Layer Decryption
msg3, err := encrypt.Decrypt(unshuffledMsg3, aesKey3)
if err != nil {
return nil, gmyerr.WrapPrefix("encrypt.Decrypt", err)
}
// Second Layer Key
cbesLongKey, err := t.CBESGetPassword(512)
if err != nil {
return nil, gmyerr.WrapPrefix("t.CBESGetPassword", err)
}
// Second Layer Shuffle
shfKey2, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(cbesLongKey, []byte("MESCHA_SHUFFLE_CBES"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// Second Layer Shuffle
unshuffledMsg2 := shuffle.Unshuffle(msg3.Data, shfKey2)
// Second Layer Decryption
aesKey2, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(cbesLongKey, []byte("MESCHA_ENCRYPTION_CBES"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// Second Layer Decryption
msg2, err := encrypt.Decrypt(unshuffledMsg2, aesKey2)
if err != nil {
return nil, gmyerr.WrapPrefix("encrypt.Decrypt", err)
}
// First Layer Key
if t.ECDHConnection == nil {
return nil, gmyerr.WrapPrefix("t.ECDHConnection", IS_NIL)
}
shared, err := t.ECDHConnection.GetShared()
if errors.Is(err, ecdh.ERROR_SharedNotComputed) {
return nil, ecdh.ERROR_SharedNotComputed
}
// First Layer Shuffle
shfKey, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(shared, []byte("MESCHA_SHUFFLE_ECDH"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// First Layer Shuffle
unshuffledMsg := shuffle.Unshuffle(msg2.Data, shfKey)
// First Layer Decryption
aesKey, err := hkdf.DeriveAESKeyFromLongKeyAndInfo(shared, []byte("MESCHA_ENCRYPTION_ECDH"))
if err != nil {
return nil, gmyerr.WrapPrefix("hkdf.DeriveAESKeyFromLongKeyAndInfo", err)
}
// First Layer Decryption
msg, err := encrypt.Decrypt(unshuffledMsg, aesKey)
if err != nil {
return nil, gmyerr.WrapPrefix("encrypt.Decrypt", err)
}
return msg.Data, nil
}

7
tlep/working.ntx Normal file
View File

@ -0,0 +1,7 @@
create a way to convert WORD into float
integrate mklg with some parts
create communication scheme using ECHD + AES + digital signatures + shuffle + mklg changes + CBES
CBES = Chaos-Based-Encryption-Scheme