summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/Philipp15b/go-steam/cryptoutil/cryptoutil.go
blob: b44f8d2677cabef6b26b300bcf29a7880c40c9ac (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package cryptoutil

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

// Performs an encryption using AES/CBC/PKCS7
// with a random IV prepended using AES/ECB/None.
func SymmetricEncrypt(ciph cipher.Block, src []byte) []byte {
	// get a random IV and ECB encrypt it
	iv := make([]byte, aes.BlockSize, aes.BlockSize)
	_, err := rand.Read(iv)
	if err != nil {
		panic(err)
	}
	encryptedIv := make([]byte, aes.BlockSize, aes.BlockSize)
	newECBEncrypter(ciph).CryptBlocks(encryptedIv, iv)

	// pad it, copy the IV to the first 16 bytes and encrypt the rest with CBC
	encrypted := padPKCS7WithIV(src)
	copy(encrypted, encryptedIv)
	cipher.NewCBCEncrypter(ciph, iv).CryptBlocks(encrypted[aes.BlockSize:], encrypted[aes.BlockSize:])
	return encrypted
}

// Decrypts data from the reader using AES/CBC/PKCS7 with an IV
// prepended using AES/ECB/None. The src slice may not be used anymore.
func SymmetricDecrypt(ciph cipher.Block, src []byte) []byte {
	iv := src[:aes.BlockSize]
	newECBDecrypter(ciph).CryptBlocks(iv, iv)

	data := src[aes.BlockSize:]
	cipher.NewCBCDecrypter(ciph, iv).CryptBlocks(data, data)

	return unpadPKCS7(data)
}