2022-02-05 02:00:34 +00:00
|
|
|
package romulus_go
|
2022-02-05 01:45:46 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
const abytes int = 16
|
|
|
|
const keysize int = 16
|
|
|
|
const noncesize int = 16
|
|
|
|
|
|
|
|
func Encrypt(key []byte, plaintext []byte, additionalData []byte) ([]byte, error) {
|
|
|
|
|
2022-02-06 03:22:15 +00:00
|
|
|
if len(key) < keysize {
|
|
|
|
return nil, errors.New("Failed to encrypt")
|
|
|
|
}
|
|
|
|
|
2022-02-05 01:45:46 +00:00
|
|
|
cipher := make([]byte, len(plaintext)+abytes+noncesize)
|
2022-02-05 02:58:28 +00:00
|
|
|
var cipherlen uint64 = (uint64)(len(cipher))
|
2022-02-05 01:45:46 +00:00
|
|
|
nonce := genNonce()
|
|
|
|
ret := romulus_m_encrypt(
|
|
|
|
cipher[noncesize:],
|
|
|
|
&cipherlen,
|
|
|
|
plaintext,
|
|
|
|
(uint64)(len(plaintext)),
|
|
|
|
additionalData,
|
|
|
|
(uint64)(len(additionalData)),
|
|
|
|
nil,
|
|
|
|
nonce,
|
|
|
|
key[:keysize],
|
|
|
|
)
|
|
|
|
|
|
|
|
if ret != 0 {
|
2022-02-06 03:22:15 +00:00
|
|
|
return nil, errors.New("Failed to encrypt")
|
2022-02-05 01:45:46 +00:00
|
|
|
}
|
|
|
|
copy(cipher, nonce)
|
2022-02-05 02:58:28 +00:00
|
|
|
return cipher[:(int)(cipherlen)+noncesize], nil
|
2022-02-05 01:45:46 +00:00
|
|
|
}
|
|
|
|
|
2022-02-06 03:22:15 +00:00
|
|
|
func Decrypt(key []byte, ciphertext []byte, additionalData []byte) (plaintext []byte, auth bool, err error) {
|
2022-02-05 01:45:46 +00:00
|
|
|
|
2022-02-06 03:22:15 +00:00
|
|
|
if len(ciphertext) <= noncesize || len(key) < keysize {
|
|
|
|
return nil, false, errors.New("Failed to decrypt")
|
|
|
|
}
|
|
|
|
|
|
|
|
defer func() {
|
2022-02-07 00:17:28 +00:00
|
|
|
if r := recover(); r != nil {
|
|
|
|
err = errors.New("Recovered from panic in decrypt")
|
|
|
|
auth = false
|
|
|
|
}
|
2022-02-06 03:22:15 +00:00
|
|
|
}()
|
|
|
|
|
|
|
|
plaintext = make([]byte, len(ciphertext))
|
2022-02-05 02:58:28 +00:00
|
|
|
var plaintextLen uint64 = (uint64)(len(plaintext))
|
2022-02-05 01:45:46 +00:00
|
|
|
ret := romulus_m_decrypt(
|
|
|
|
plaintext,
|
|
|
|
&plaintextLen,
|
|
|
|
nil,
|
|
|
|
ciphertext[noncesize:],
|
|
|
|
(uint64)(len(ciphertext)-noncesize),
|
|
|
|
additionalData,
|
|
|
|
(uint64)(len(additionalData)),
|
|
|
|
ciphertext[:noncesize],
|
|
|
|
key[:keysize],
|
|
|
|
)
|
2022-02-06 03:22:15 +00:00
|
|
|
|
2022-02-05 01:45:46 +00:00
|
|
|
if ret == -1 {
|
|
|
|
return nil, false, errors.New("Failed to authenticate")
|
|
|
|
} else if ret != 0 {
|
|
|
|
return nil, false, errors.New("Failed to decrypt")
|
|
|
|
}
|
|
|
|
|
2022-02-05 02:24:34 +00:00
|
|
|
return plaintext[:plaintextLen], true, nil
|
2022-02-05 01:45:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func genNonce() []byte {
|
|
|
|
buf := make([]byte, noncesize)
|
|
|
|
rand.Read(buf)
|
|
|
|
return buf
|
|
|
|
}
|