Skip to content

Commit

Permalink
Improvements on crypto
Browse files Browse the repository at this point in the history
  • Loading branch information
berkkirtay committed Aug 31, 2024
1 parent a746759 commit 18830f7
Show file tree
Hide file tree
Showing 7 changed files with 150 additions and 64 deletions.
7 changes: 5 additions & 2 deletions src/commands/room_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func HandleCreateRoom(command []string) {
func HandleText(command string) {
url := assignedPeer.Address + "/room/messages"
var message room.Message = room.CreateMessage(
room.WithText(cryptography.Encrypt(command, currentRoom.HandshakeKey)),
room.WithText(cryptography.EncryptAES(command, currentRoom.RoomMasterKey)),
room.WithIsEncrypted(true))
body, err := json.Marshal(message)
if err != nil {
Expand Down Expand Up @@ -107,6 +107,9 @@ func joinRoom(roomId string, roomPassword string) {
return
}
currentRoom = room
currentRoom.RoomMasterKey = cryptography.DecryptRSA(
currentRoom.RoomMasterKey, currentUser.Signature.PrivateKey)

fmt.Printf("Joined the room. You will talk with:\n")
roomUsers = make(map[string]user.User)
for _, userId := range room.Members {
Expand Down Expand Up @@ -183,7 +186,7 @@ func fetchLastMessageId() int64 {

func buildAReadableText(message room.Message) string {
if message.IsEncrypted {
return cryptography.Decrypt(message.Text, currentRoom.HandshakeKey)
return cryptography.DecryptAES(message.Text, currentRoom.RoomMasterKey)
} else {
return message.Text
}
Expand Down
157 changes: 113 additions & 44 deletions src/infra/cryptography/cryptography_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,91 +7,160 @@ import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
b64 "encoding/base64"
"encoding/pem"
"io"
"math"
"math/big"
"strconv"
"time"

"github.com/zenazn/pkcs7pad"
)

const p float64 = 23
const g float64 = 5

var publicKey string
var privateKey string

func InitializeService() {
// rand.Prime()
}
const (
RSA_KEY_SIZE = 2048
)

// TODO area.
func CreateDefaultCrypto(keyPair string, values ...interface{}) *Signature {
hash, nonce := generateHash(values)
return CreateSignature(WithPublicKey(keyPair),
func CreateDefaultCrypto(values ...string) *Signature {
hash := GenerateSHA256([]string(values))
nonce := int64(12312) // TODO
privateKey, publicKey := GenerateKeyPair()
return CreateSignature(
WithPublicKey(publicKey),
WithPrivateKey(privateKey),
WithHash(hash),
WithNonce(nonce),
WithSign(generateSignature(keyPair, hash)),
WithSign(generateSignature(privateKey, hash)),
WithTimestamp(time.Now().Format(time.RFC1123)))
}

func generateHash(values []interface{}) (string, int64) {
return values[0].(string), 1
func generateSignature(privateKey string, data string) string {
decodedKey, err := b64.StdEncoding.DecodeString(privateKey)
if err != nil {
panic(err)
}
decodedBlock, _ := pem.Decode(decodedKey)

key, err := x509.ParsePKCS1PrivateKey(decodedBlock.Bytes)
if err != nil {
panic(err)
}
calculatedHash := sha256.Sum256([]byte(data))
signature, err := rsa.SignPKCS1v15(
rand.Reader,
key,
crypto.SHA256,
calculatedHash[:],
)
if err != nil {
panic(err)
}
return b64.StdEncoding.EncodeToString(signature)
}

func VerifySignature(data string, signature string, publicKey string) {
return
}

func generateSignature(keyPair string, hash string) string {
return hash
func GenerateSHA256(values []string) string {
sha256 := crypto.SHA256.New()
for _, value := range values {
sha256.Write([]byte(value))
}

hash := sha256.Sum(nil)[0:16]
encodedHash := b64.StdEncoding.EncodeToString(hash)
return encodedHash
}

func GenerateARandomMasterSecret() string {
sha256 := crypto.SHA256.New()
randValue, err := rand.Int(rand.Reader, big.NewInt(32))
if err != nil {
panic(err)
}
return GenerateSHA256([]string{strconv.FormatInt(randValue.Int64(), 10)})
}

sha256.Write([]byte(strconv.FormatInt(randValue.Int64(), 10)))
randomSecret := sha256.Sum([]byte("secret"))[0:16]
func EnrichMasterSecret(secret string, hash string) string {
randValue, err := rand.Int(rand.Reader, big.NewInt(32))
if err != nil {
panic(err)
}
return GenerateSHA256(
[]string{
strconv.FormatInt(randValue.Int64(), 10),
secret,
hash},
)
}

encodedSecret := b64.StdEncoding.EncodeToString([]byte(randomSecret))
return encodedSecret
func GenerateKeyPair(salts ...string) (string, string) {
keyPair, err := rsa.GenerateKey(rand.Reader, RSA_KEY_SIZE)
if err != nil {
panic(err)
}

err = keyPair.Validate()
if err != nil {
panic(err)
}

encodedPrivateKey := b64.StdEncoding.EncodeToString(
pem.EncodeToMemory(&pem.Block{Bytes: x509.MarshalPKCS1PrivateKey(keyPair)}))

encodedPublicKey := b64.StdEncoding.EncodeToString(
pem.EncodeToMemory(&pem.Block{Bytes: x509.MarshalPKCS1PublicKey(&keyPair.PublicKey)}))
return encodedPrivateKey, encodedPublicKey
}

func ServerSideDiffieHelmanKeyExhange(
clientSecret string) []string {
computedSecretOfClient, err := strconv.Atoi(clientSecret)
func EncryptRSA(data string, publicKey string) string {
decodedKey, err := b64.StdEncoding.DecodeString(publicKey)
if err != nil {
panic(err)
}
decodedBlock, _ := pem.Decode(decodedKey)

key, err := x509.ParsePKCS1PublicKey(decodedBlock.Bytes)
if err != nil {
panic(err)
}
computedSecretOfServer, err := strconv.Atoi(privateKey)
ciperText, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, key, []byte(data), nil)
if err != nil {
panic(err)
}
commonSecretKey := math.Mod(math.Pow(float64(computedSecretOfClient), float64(computedSecretOfServer)), p)
serverSecret := math.Mod(math.Pow(g, float64(computedSecretOfServer)), p)
return []string{strconv.FormatFloat(commonSecretKey, 'f', -1, 64), strconv.FormatFloat(serverSecret, 'f', -1, 64)}
return b64.StdEncoding.EncodeToString(ciperText)
}

func PeerToPeerDiffieHelmanKeyExhange(p float64, g float64, privateKeys ...string) []string {
combinedKeys := []string{}
columns := []float64{}
for _, privateKey := range privateKeys {
secret, err := strconv.Atoi(privateKey)
if err != nil {
panic(err)
}
columns = append(columns, math.Mod(math.Pow(g, float64(secret)), p))
}
return combinedKeys
func DecryptRSA(data string, privateKey string) string {
decodedData, err := b64.StdEncoding.DecodeString(data)
if err != nil {
panic(err)
}
decodedKey, err := b64.StdEncoding.DecodeString(privateKey)
if err != nil {
panic(err)
}
decodedBlock, _ := pem.Decode(decodedKey)
key, err := x509.ParsePKCS1PrivateKey(decodedBlock.Bytes)
if err != nil {
panic(err)
}
plainText, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, key, decodedData, nil)
if err != nil {
panic(err)
}
return string(plainText)
}

/*
* Encryption functions take a string (preferably as base64) as input
* and returns an encrypted/decrypted string conventionally.
* and returns an encrypted/decrypted string conventionally.
*/
func Encrypt(message string, key string) string {
func EncryptAES(message string, key string) string {
decodedKey, _ := b64.StdEncoding.DecodeString(key)
encryptor, err := aes.NewCipher(decodedKey)
if err != nil {
Expand All @@ -110,7 +179,7 @@ func Encrypt(message string, key string) string {
return b64.StdEncoding.EncodeToString(ciphertext)
}

func Decrypt(cipherText string, key string) string {
func DecryptAES(cipherText string, key string) string {
decodedCipherText, _ := b64.StdEncoding.DecodeString(cipherText)
decodedKey, _ := b64.StdEncoding.DecodeString(key)
decryptor, err := aes.NewCipher(decodedKey)
Expand Down
18 changes: 13 additions & 5 deletions src/infra/cryptography/signature.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
package cryptography

type Signature struct {
Sign string `json:"sign,omitempty" bson:"sign,omitempty"`
PublicKey string `json:"publicKey,omitempty" bson:"publicKey,omitempty"`
Nonce int64 `json:"nonce,omitempty" bson:"nonce,omitempty"`
Timestamp string `json:"timestamp,omitempty" bson:"timestamp,omitempty"`
Hash string `json:"hash,omitempty" bson:"hash,omitempty"`
Sign string `json:"sign,omitempty" bson:"sign,omitempty"`
PublicKey string `json:"publicKey,omitempty" bson:"publicKey,omitempty"`
PrivateKey string `json:"privateKey,omitempty" bson:"privateKey,omitempty"`
Nonce int64 `json:"nonce,omitempty" bson:"nonce,omitempty"`
Timestamp string `json:"timestamp,omitempty" bson:"timestamp,omitempty"`
Hash string `json:"hash,omitempty" bson:"hash,omitempty"`
}

type SignatureOption func(Signature) Signature
Expand All @@ -26,6 +27,13 @@ func WithPublicKey(publicKey string) SignatureOption {
}
}

func WithPrivateKey(privateKey string) SignatureOption {
return func(signature Signature) Signature {
signature.PrivateKey = privateKey
return signature
}
}

func WithNonce(nonce int64) SignatureOption {
return func(signature Signature) Signature {
signature.Nonce = nonce
Expand Down
2 changes: 1 addition & 1 deletion src/p2p/broadcast.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import (
const (
LOCAL_BROADCAST_ADDRESS string = "224.0.0.1:9999"
NETWORK_NAME string = "udp4"
MAX_BROADCAST_AMOUNT int = 5
MAX_BROADCAST_AMOUNT int = 1
ADDRESS_FORMAT string = HTTP + "%s" + PORT + API
)

Expand Down
10 changes: 1 addition & 9 deletions src/services/room/room.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ type Room struct {
Signature *cryptography.Signature `json:"signature,omitempty" bson:"signature,omitempty"`
Audit *audit.Audit `json:"audit,omitempty" bson:"audit,omitempty"`
DiffieHelmanKeys map[string]string `json:"-"`
RoomMasterKey string `json:"-"`
HandshakeKey string `json:"handshakeKey,omitempty" bson:"handshakeKey,omitempty"`
RoomMasterKey string `json:"roomMasterKey,omitempty" bson:"roomMasterKey,omitempty`
}

type RoomOption func(Room) Room
Expand Down Expand Up @@ -95,13 +94,6 @@ func WithRoomMasterKey(roomMasterKey string) RoomOption {
}
}

func WithHandshakeKey(handshakeKey string) RoomOption {
return func(room Room) Room {
room.HandshakeKey = handshakeKey
return room
}
}

func CreateDefaultRoom() Room {
return Room{}
}
Expand Down
17 changes: 15 additions & 2 deletions src/services/room/room_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"main/infra/cryptography"
"main/infra/store"
"main/services/audit"
"main/services/user"
"slices"
"strconv"
"time"
Expand Down Expand Up @@ -39,6 +40,7 @@ func GetRooms(id string, size string) []Room {
if cur != nil && err == nil {
cur.Decode(&room)
room.Password = ""
room.RoomMasterKey = ""
rooms = append(rooms, room)
}
} else {
Expand All @@ -62,6 +64,7 @@ func GetRooms(id string, size string) []Room {
panic(err)
}
currentRoom.Password = ""
currentRoom.RoomMasterKey = ""
rooms = append(rooms, currentRoom)
}
}
Expand All @@ -88,7 +91,12 @@ func PostRoom(room Room) Room {
WithCapacity(room.Capacity),
WithMembers([]string{}),
WithRoomMasterKey(cryptography.GenerateARandomMasterSecret()),
WithSignature(nil),
WithSignature(cryptography.CreateDefaultCrypto(
room.Name,
room.Info,
room.Password,
room.RoomMasterKey,
)),
WithAudit(audit.CreateAuditForRoom()))

repository.InsertOne(createdRoom)
Expand Down Expand Up @@ -117,7 +125,10 @@ func JoinRoom(id string, room Room, userId string) Room {
cur.Decode(&actualRoom)
}

user := user.GetUser(userId, "")

if slices.Contains(actualRoom.Members, userId) {
actualRoom.RoomMasterKey = cryptography.EncryptRSA(actualRoom.RoomMasterKey, user.Signature.PublicKey)
return actualRoom
}

Expand All @@ -132,8 +143,8 @@ func JoinRoom(id string, room Room, userId string) Room {

// masterSecret := cryptography.ServerSideDiffieHelmanKeyExhange(userHandshakeKey)
// actualRoom.DiffieHelmanKeys[userId] = masterSecret[0]
actualRoom.HandshakeKey = actualRoom.RoomMasterKey

//actualRoom.RoomMasterKey = cryptography.EnrichMasterSecret(actualRoom.RoomMasterKey, user.Signature.Hash)
actualRoom.Members = append(actualRoom.Members, userId)
actualRoom.Audit.LastOnlineDate = time.Now().Format(time.RFC1123)
actualRoom.Audit.NumberOfActions += 1
Expand All @@ -143,6 +154,8 @@ func JoinRoom(id string, room Room, userId string) Room {
return CreateDefaultRoom()
}
// SendAMessage(id, userId, buildAMessage(room, userId, CreateMessage(WithText("Greetings! I just joined."))))
//TODO encrypt with users key pair :)
actualRoom.RoomMasterKey = cryptography.EncryptRSA(actualRoom.RoomMasterKey, user.Signature.PublicKey)
return actualRoom
}

Expand Down
3 changes: 2 additions & 1 deletion src/services/user/user_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,15 @@ func buildUser(user User) User {
res.Decode(&lastRecord)
newUserId, _ = strconv.Atoi(lastRecord.Id)
}
cryptography.GenerateKeyPair()
return CreateUser(
WithId(strconv.Itoa(newUserId+1)),
WithName(user.Name),
WithPassword(user.Password),
WithRole(user.Role),
WithSignature(cryptography.CreateDefaultCrypto(
"keyPair",
user.Name,
user.Password,
user.Role)),
WithActions(nil),
WithAudit(user.Audit))
Expand Down

0 comments on commit 18830f7

Please sign in to comment.