package Seeder import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "crypto/rsa" "crypto/sha512" "encoding/pem" "hash" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" "github.com/gofrs/uuid" ) // EncryptWithPublicKey encrypts data with public key func encryptWithPublicKey(msg []byte, pub *rsa.PublicKey) []byte { var ( hash hash.Hash ) hash = sha512.New() ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pub, msg, nil) if err != nil { panic(err) } return ciphertext } func PKCS5Padding(ciphertext []byte, blockSize int, after int) []byte { var ( padding int padtext []byte ) padding = (blockSize - len(ciphertext)%blockSize) padtext = bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } func seedMessage(primaryUser, secondaryUser Models.User, threadID uuid.UUID, i int) error { var ( messageKey Models.Message messageData Models.MessageData block cipher.Block mode cipher.BlockMode pemBlock *pem.Block plaintext string ciphertext []byte bKey []byte bIV []byte bPlaintext []byte err error ) plaintext = "Test Message" bKey = make([]byte, 32) _, err = rand.Read(bKey) if err != nil { panic(err) } bIV = make([]byte, 16) _, err = rand.Read(bIV) if err != nil { panic(err) } bPlaintext = PKCS5Padding([]byte(plaintext), aes.BlockSize, len(plaintext)) pemBlock = &pem.Block{ Type: "AES KEY", Bytes: bKey, } block, err = aes.NewCipher(bKey) if err != nil { panic(err) } ciphertext = make([]byte, len(bPlaintext)) mode = cipher.NewCBCEncrypter(block, bIV) mode.CryptBlocks(ciphertext, bPlaintext) messageData = Models.MessageData{ Data: ciphertext, } messageKey = Models.Message{ UserID: primaryUser.ID, MessageData: messageData, MessageType: "sender", RelationalUserId: encryptWithPublicKey(secondaryUser.ID.Bytes(), decodedPublicKey), SymmetricKey: string(pem.EncodeToMemory(pemBlock)), } return Database.CreateMessage(&messageKey) } func SeedMessages() { var ( primaryUser Models.User secondaryUser Models.User threadID uuid.UUID i int err error ) primaryUser, err = Database.GetUserByUsername("testUser") if err != nil { panic(err) } secondaryUser, err = Database.GetUserByUsername("testUser2") if err != nil { panic(err) } threadID, err = uuid.NewV4() if err != nil { panic(err) } for i = 0; i <= 20; i++ { err = seedMessage(primaryUser, secondaryUser, threadID, i) if err != nil { panic(err) } } }