Sobes.tech
Senior

How have you used data encryption? In what situations and for what data?

sobes.tech AI

Answer from AI

Data encryption is used to protect confidential information stored in databases and transmitted between services. Main scenarios include:

  • Storing passwords and secrets — user passwords are stored as salted hashes, and secret keys and tokens are stored in encrypted form.
  • Encrypting personal data — such as credit card numbers, passport details, addresses, so that data is inaccessible in case of leaks.
  • Encrypting backups — to protect backups from unauthorized access.
  • Encrypting traffic — TLS for data protection during transmission.

Example: for encrypting database fields, symmetric encryption like AES can be used. Data is encrypted before saving and decrypted when reading.

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "io"
)

func encrypt(plaintext []byte, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }
    ciphertext := make([]byte, aes.BlockSize+len(plaintext))
    iv := ciphertext[:aes.BlockSize]
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        return nil, err
    }
    stream := cipher.NewCFBEncrypter(block, iv)
    stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
    return ciphertext, nil
}

Thus, encryption helps ensure data security at various stages of their lifecycle.