2016-01-28 18:19:23 -05:00
|
|
|
package crypto
|
2016-01-29 07:22:31 -05:00
|
|
|
|
2016-01-28 18:19:23 -05:00
|
|
|
import (
|
2016-01-29 07:22:31 -05:00
|
|
|
"crypto/aes"
|
|
|
|
"crypto/cipher"
|
2016-01-28 18:19:23 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
type TunnelData [1024]byte
|
|
|
|
|
|
|
|
// A symetric key for encrypting tunnel messages
|
|
|
|
type TunnelKey [32]byte
|
2016-01-29 07:22:31 -05:00
|
|
|
|
2016-01-28 18:19:23 -05:00
|
|
|
// The initialization vector for a tunnel message
|
|
|
|
type TunnelIV []byte
|
|
|
|
|
|
|
|
type Tunnel struct {
|
2016-01-29 07:22:31 -05:00
|
|
|
layerKey cipher.Block
|
|
|
|
ivKey cipher.Block
|
2016-01-28 18:19:23 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewTunnelCrypto(layerKey, ivKey TunnelKey) (t *Tunnel, err error) {
|
2016-01-29 07:22:31 -05:00
|
|
|
|
|
|
|
t = new(Tunnel)
|
|
|
|
t.layerKey, err = aes.NewCipher(layerKey[:])
|
|
|
|
if err == nil {
|
|
|
|
t.ivKey, err = aes.NewCipher(ivKey[:])
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
// error happened we don't need t
|
|
|
|
t = nil
|
|
|
|
}
|
|
|
|
return
|
2016-01-28 18:19:23 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// encrypt tunnel data in place
|
|
|
|
func (t *Tunnel) Encrypt(td *TunnelData) {
|
2016-01-29 07:22:31 -05:00
|
|
|
data := *td
|
|
|
|
t.ivKey.Encrypt(data[16:1024], data[16:1024])
|
|
|
|
layerBlock := cipher.NewCBCEncrypter(t.layerKey, data[:16])
|
|
|
|
layerBlock.CryptBlocks(data[16:1024], data[16:1024])
|
|
|
|
t.ivKey.Encrypt(data[16:1024], data[16:1024])
|
2016-01-28 18:19:23 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Tunnel) Decrypt(td *TunnelData) {
|
2016-01-29 07:22:31 -05:00
|
|
|
data := *td
|
|
|
|
t.ivKey.Decrypt(data[16:1024], data[16:1024])
|
|
|
|
layerBlock := cipher.NewCBCDecrypter(t.layerKey, data[:16])
|
|
|
|
layerBlock.CryptBlocks(data[16:1024], data[16:1024])
|
|
|
|
t.ivKey.Decrypt(data[16:1024], data[16:1024])
|
2016-01-28 18:19:23 -05:00
|
|
|
}
|