Skip to content

Instantly share code, notes, and snippets.

@cosmos-sajal
Created October 26, 2023 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cosmos-sajal/993933c2ac2c505202547d0c4c518999 to your computer and use it in GitHub Desktop.
Save cosmos-sajal/993933c2ac2c505202547d0c4c518999 to your computer and use it in GitHub Desktop.
Encrypt using AES CBC
func encryptKYCData(plainText string) string {
// refer this - https://chat.openai.com/share/1f7f6ca1-23fb-45c3-9fb1-88c42efb9880
password := []byte(os.Getenv("ENCRYPTION_KEY"))
// pad the plaintext if it is not a muliple of aes.BlockSize
plainTextBytes := []byte(plainText)
padLength := aes.BlockSize - len(plainTextBytes)%aes.BlockSize
padding := bytes.Repeat([]byte{byte(padLength)}, padLength)
plainTextBytes = append(plainTextBytes, padding...)
cipherText := make([]byte, len(plainTextBytes))
// create an Initialization Vector of random 16 bytes
iv := make([]byte, 16)
_, err := rand.Read(iv)
if err != nil {
return ""
}
// using sha256 hash to generate an hashed key, then
// encode it using base64 encoding and take the first 32 bytes
hash := sha256.New()
hash.Write([]byte(password))
hashBytes := hash.Sum(nil)
key := base64.StdEncoding.EncodeToString(hashBytes)[:32]
// create a cipher block using this IV and key generated previously
block, err := aes.NewCipher([]byte(key))
if err != nil {
return ""
}
cipher := cipher.NewCBCEncrypter(block, iv)
cipher.CryptBlocks(cipherText, plainTextBytes)
return hex.EncodeToString(iv) + ":" + hex.EncodeToString(cipherText)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment