Skip to content

Instantly share code, notes, and snippets.

@brunoksato
Created March 12, 2017 06:22
Show Gist options
  • Save brunoksato/9dff88fc2c8ea3c57296b105ea3442b5 to your computer and use it in GitHub Desktop.
Save brunoksato/9dff88fc2c8ea3c57296b105ea3442b5 to your computer and use it in GitHub Desktop.
var KEY_CRIPTY = []byte("@E#%_323E5%DMG!(332GG()!")
// encrypt string to base64 crypto using AES
func encrypt(key []byte, text string) string {
plaintext := []byte(text)
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println(err)
}
// The IV needs to be unique, but not secure. Therefore it's common to
// include it at the beginning of the ciphertext.
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
fmt.Println(err)
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
// convert to base64
return base64.URLEncoding.EncodeToString(ciphertext)
}
// decrypt from base64 to decrypted string
func decrypt(key []byte, cryptoText string) string {
ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println(err)
}
// The IV needs to be unique, but not secure. Therefore it's common to
// include it at the beginning of the ciphertext.
if len(ciphertext) < aes.BlockSize {
fmt.Println("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
// XORKeyStream can work in-place if the two arguments are the same.
stream.XORKeyStream(ciphertext, ciphertext)
return fmt.Sprintf("%s", ciphertext)
}
//example model
package model
type UserBank struct {
Model
Name string `json:"name,omitempty" sql:"not null"`
Type string `json:"type,omitempty" sql:"not null"`
Agency string `json:"agency,omitempty" sql:"not null"`
Number string `json:"number,omitempty" sql:"not null"`
}
func (ub UserBank) EncryptBank() UserBank {
ub.Name = encrypt(KEY_CRIPTY, ub.Name)
ub.Type = encrypt(KEY_CRIPTY, ub.Type)
ub.Agency = encrypt(KEY_CRIPTY, ub.Agency)
ub.Number = encrypt(KEY_CRIPTY, ub.Number)
return ub
}
func (ub UserBank) DecryptBank() UserBank {
ub.Name = decrypt(KEY_CRIPTY, ub.Name)
ub.Type = decrypt(KEY_CRIPTY, ub.Type)
ub.Agency = decrypt(KEY_CRIPTY, ub.Agency)
ub.Number = decrypt(KEY_CRIPTY, ub.Number)
return ub
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment