# Ecrypt Decrypt GOlang Vuejs
## Golang
lib/encrypt.go
```
package lib
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
)
func Encrypt(unencrypted string, key string) (string, error) {
keyByte := []byte(key)
plainText := []byte(unencrypted)
plainText, err := Pad(plainText, aes.BlockSize)
if err != nil {
return "", fmt.Errorf(`plainText: "%s" has error`, plainText)
}
if len(plainText)%aes.BlockSize != 0 {
err := fmt.Errorf(`plainText: "%s" has the wrong block size`, plainText)
return "", err
}
block, err := aes.NewCipher(keyByte)
if err != nil {
return "", err
}
cipherText := make([]byte, aes.BlockSize+len(plainText))
iv := cipherText[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherText[aes.BlockSize:], plainText)
return fmt.Sprintf("%x", cipherText), nil
}
// Decrypt decrypts cipher text string into plain text string
func Decrypt(encrypted string, key string) (string, error) {
keyByte := []byte(key)
cipherText, _ := hex.DecodeString(encrypted)
block, err := aes.NewCipher(keyByte)
if err != nil {
panic(err)
}
if len(cipherText) < aes.BlockSize {
panic("cipherText too short")
}
iv := cipherText[:aes.BlockSize]
cipherText = cipherText[aes.BlockSize:]
if len(cipherText)%aes.BlockSize != 0 {
panic("cipherText is not a multiple of the block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(cipherText, cipherText)
cipherText, _ = Unpad(cipherText, aes.BlockSize)
fmt.Sprintf("cipherText: %s", cipherText)
return fmt.Sprintf("%s", cipherText), nil
}
func Pad(buf []byte, size int) ([]byte, error) {
bufLen := len(buf)
padLen := size - bufLen%size
padded := make([]byte, bufLen+padLen)
copy(padded, buf)
for i := 0; i < padLen; i++ {
padded[bufLen+i] = byte(padLen)
}
return padded, nil
}
func Unpad(padded []byte, size int) ([]byte, error) {
if len(padded)%size != 0 {
return nil, errors.New("pkcs7: Padded value wasn't in correct size.")
}
bufLen := len(padded) - int(padded[len(padded)-1])
buf := make([]byte, bufLen)
copy(buf, padded[:bufLen])
return buf, nil
}
```
# usage in controller
```
func (ap AccessPlaceController) GetAll(c *gin.Context) {
datas, err := ap.service.GetAll()
if err != nil {
ap.logger.Zap.Error(err)
}
if os.Getenv("ENCRYPT_DATA") == "true" {
fmt.Println("data will be encrypt => ", datas)
requestData, _ := json.Marshal(datas)
fmt.Println("request data Marshal => ", string(requestData))
encrypted, _ := lib.Encrypt(string(requestData), os.Getenv("KEY_ENCRYPT"))
fmt.Println("data decrypted", encrypted)
lib.ReturnToJson(c, 200, "200", "Inquiry data berhasil", encrypted)
} else if os.Getenv("ENCRYPT_DATA") == "false" {
lib.ReturnToJson(c, 200, "200", "Inquiry data berhasil", datas)
}
}
```
# usage request response with encrypt decrypt
```
func (asset AssetController) GetAssetElastic(c *gin.Context) {
request := models.AssetRequestElastic{}
if os.Getenv("ENCRYPT_DATA") == "true" {
data := models.Decrypt{}
if err := c.Bind(&data); err != nil {
asset.logger.Zap.Error(err)
lib.ReturnToJson(c, 200, "400", "Input Tidak Sesuai: "+err.Error(), "")
return
}
dataDecrypt, err := lib.Decrypt(data.Data, os.Getenv("KEY_ENCRYPT"))
// fmt.Println(err.Error())
if err != nil {
lib.ReturnToJson(c, 200, "500", "Request Encrypted Required", "")
}
json.Unmarshal([]byte(dataDecrypt), &request)
} else if os.Getenv("ENCRYPT_DATA") == "false" {
if err := c.Bind(&request); err != nil {
asset.logger.Zap.Error(err)
lib.ReturnToJson(c, 200, "400", "Input Tidak Sesuai: "+err.Error(), "")
return
}
}
fmt.Println("request get elastic => ", request)
pagination, datas, err := asset.service.GetAssetElastic(request)
if err != nil {
asset.logger.Zap.Error(err)
lib.ReturnToJson(c, 200, "500", "Internal Error", "")
return
}
if datas == nil {
lib.ReturnToJson(c, 200, "404", "Data Tidak Ditemukan", "")
return
}
if len(datas) == 0 {
asset.logger.Zap.Error(err)
lib.ReturnToJson(c, 200, "404", "Data Tidak Ditemukan", "")
return
}
fmt.Println("ENCRYPT_DATA", os.Getenv("ENCRYPT_DATA"))
if os.Getenv("ENCRYPT_DATA") == "true" {
fmt.Println("data will be encrypt => ", datas)
var requestData []byte
if requestData, err = json.Marshal(datas); err != nil {
fmt.Println("Error marshalling datas => ", err.Error())
}
encrypted, _ := lib.Encrypt(string(requestData), os.Getenv("KEY_ENCRYPT"))
fmt.Println("data successfully encrypted", encrypted)
lib.ReturnToJsonWithPaginate(c, 200, "200", "Inquiry data berhasil", encrypted, pagination)
} else if os.Getenv("ENCRYPT_DATA") == "false" {
lib.ReturnToJsonWithPaginate(c, 200, "200", "Inquiry data berhasil", datas, pagination)
}
}
```
# Vuejs
nuxt.config.js
```
plugins: [
{ src: '~/plugins/helpers.js' },
],
```
plugins/helpers.js
```
export default function ({ state }, inject) {
const helpers = {
encrypt(payload) {
const crypto = require('crypto')
// const algorithm = 'aes-256-cbc'
const key = process.env.KEY_ENCRYPT
// crypto.randomBytes(32)
const iv = crypto.randomBytes(16)
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv)
let encrypted = cipher.update(payload)
encrypted = Buffer.concat([encrypted, cipher.final()])
// this.$helpers.log('encrypted.toString(hex) =>', encrypted.toString('hex'))
// this.$helpers.log('iv => ', iv.toString('hex'))
// return {
// iv: iv.toString('hex'),
// encryptedData: encrypted.toString('hex'),
// }
return iv.toString('hex') + encrypted.toString('hex')
},
decrypt(payload) {
const crypto = require('crypto')
// const algorithm = 'aes-256-cbc'
const key = process.env.KEY_ENCRYPT
// crypto.randomBytes(32)
let iv = crypto.randomBytes(16)
const iV = payload.substr(0, 32)
const ct = payload.substr(32)
iv = Buffer.from(iV, 'hex')
const encryptedText = Buffer.from(ct, 'hex')
const decipher = crypto.createDecipheriv(
'aes-256-cbc',
Buffer.from(key),
iv
)
let decrypted = decipher.update(encryptedText)
decrypted = Buffer.concat([decrypted, decipher.final()])
// this.$helpers.log('decrypted.toString()=>', decrypted.toString())
return decrypted.toString()
},
log(payload) {
if (process.env.LOG) {
// this.$helpers.log('%c%s', payload, 'color: green;')
// this.$helpers.log('\x1B[44m', '\x1B[37m', payload, '\x1B[0m')
// console.log('%c ' + payload + ' ', 'background: #fff; color: #000')
console.log(payload)
}
},
}
inject('helpers', helpers)
}
```
usage
```
async getDataDetailElastic({ commit, state }, payload) {
let data = {
query: {
match: {
// id: payload,
document_id: payload,
},
},
}
if (process.env.ENCRYPT === 'true') {
const dataString = JSON.stringify(data)
const encrypted = this.$helpers.encrypt(dataString)
data = {
data: encrypted,
}
}
this.$helpers.log('cek get detail ', data)
await this.$api
.post('asset/getAssetElastic', data)
.then((response) => {
if (process.env.ENCRYPT === 'true') {
const realData = this.$helpers.decrypt(response.data.data)
const data = JSON.parse(realData)
commit('ASIGN_DATA_DETAIL', data[0])
} else {
commit('ASIGN_DATA_DETAIL', response.data.data[0])
}
})
.catch((err) => {
this.$helpers.log('get data Detail ', err)
})
},
```