Skip to content

Commit

Permalink
crypto package updated
Browse files Browse the repository at this point in the history
  • Loading branch information
Rajan Joshi committed Feb 20, 2020
1 parent cf94c68 commit e5fd5da
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
28 changes: 27 additions & 1 deletion crypto/decryption.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,36 @@ import (
"crypto/cipher"
"encoding/base64"
"errors"
"strconv"
"strings"
)

// Decrypt function is used to decrypt the string
func Decrypt(securemess string) (decodedmess string, err error) {
if len(strings.TrimSpace(securemess)) == 0 {
return "", errors.New("string is empty")
}
decodedStr := strings.Split(securemess, strconv.Itoa(encV1)+"||")
if len(decodedStr) == 2 {
ver, err := strconv.Atoi(decodedStr[0])
if err != nil {
return "", err
}
switch ver {
case encV1:
decodedmess, err = decrypt1(decodedStr[1])
if err != nil {
return "", err
}
default:
return "", errors.New("invalid encryption")
}
}

return decodedmess, nil
}

func decrypt1(securemess string) (string, error) {
cipherText, err := base64.URLEncoding.DecodeString(securemess)
if err != nil {
return "", err
Expand All @@ -33,6 +59,6 @@ func Decrypt(securemess string) (decodedmess string, err error) {
// XORKeyStream can work in-place if the two arguments are the same.
stream.XORKeyStream(cipherText, cipherText)

decodedmess = string(cipherText)
decodedmess := string(cipherText)
return decodedmess, nil
}
4 changes: 3 additions & 1 deletion crypto/decryption_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package crypto

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -17,7 +18,8 @@ func TestDecrypt(t *testing.T) {
assert.Equal(t, TestString, actual)
})
t.Run("failure decryption", func(t *testing.T) {
_, err := Decrypt(TestString)
str := fmt.Sprintf("%d%s%s", encV1, "||", TestString)
_, err := Decrypt(str)
assert.NotNil(t, err)
})
}
13 changes: 12 additions & 1 deletion crypto/encryption.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,23 @@ import (
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"io"
"strconv"
"strings"
)

var cipherKey = []byte("0123456789012345")

const (
encV1 = 1
)

//Encrypt function is used to encrypt the string
func Encrypt(message string) (encmess string, err error) {
if len(strings.TrimSpace(message)) == 0 {
return "", errors.New("string is empty")
}
plainText := []byte(message)

block, err := aes.NewCipher(cipherKey)
Expand All @@ -32,5 +42,6 @@ func Encrypt(message string) (encmess string, err error) {

//returns to base64 encoded string
encmess = base64.URLEncoding.EncodeToString(cipherText)
return encmess, nil
finalEnc := strconv.Itoa(encV1) + "||" + encmess //fmt.Sprintf("%d%s%s", encV1, "||", encmess)
return finalEnc, nil
}

0 comments on commit e5fd5da

Please sign in to comment.