Encrypt encrypts data with given password by AES-128-CBC PKCS#7, iv will be placed at head of cipher data.
(in, password []byte)
| 35 | // Encrypt encrypts data with given password by AES-128-CBC PKCS#7, iv will be placed |
| 36 | // at head of cipher data. |
| 37 | func Encrypt(in, password []byte) (out []byte, err error) { |
| 38 | // keyE will be 128 bits, so aes.NewCipher(keyE) will return |
| 39 | // AES-128 Cipher. |
| 40 | keyE := symmetric.KeyDerivation(password, salt[:])[:16] |
| 41 | paddedIn := crypto.AddPKCSPadding(in) |
| 42 | // IV + padded cipher data |
| 43 | out = make([]byte, aes.BlockSize+len(paddedIn)) |
| 44 | |
| 45 | // as IV length must equal block size, iv length should be 128 bits |
| 46 | iv := out[:aes.BlockSize] |
| 47 | if _, err = io.ReadFull(rand.Reader, iv); err != nil { |
| 48 | return nil, err |
| 49 | } |
| 50 | |
| 51 | // start encryption, as keyE and iv are generated properly, there should |
| 52 | // not be any error |
| 53 | block, _ := aes.NewCipher(keyE) |
| 54 | |
| 55 | mode := cipher.NewCBCEncrypter(block, iv) |
| 56 | mode.CryptBlocks(out[aes.BlockSize:], paddedIn) |
| 57 | |
| 58 | return out, nil |
| 59 | } |
| 60 | |
| 61 | // Decrypt decrypts data with given password by AES-128-CBC PKCS#7. iv will be read from |
| 62 | // the head of raw. |