-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencrypt.cpp
More file actions
51 lines (42 loc) · 1.55 KB
/
encrypt.cpp
File metadata and controls
51 lines (42 loc) · 1.55 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
//
// Created by buffer on 2022/1/8.
//
#include "encrypt.h"
void XSalsa20poly1305Encrypter::encrypt(char *dst, size_t dlen, char *src, size_t slen, unsigned char *nonce) {
crypto_box_easy_afternm(reinterpret_cast<unsigned char *>(dst), reinterpret_cast<const unsigned char *>(src), slen,
nonce, shared_key_);
}
void XSalsa20poly1305Encrypter::decrypt(char *dst, size_t dlen, char *src, size_t slen, unsigned char *nonce) {
crypto_box_open_easy_afternm(reinterpret_cast<unsigned char *>(dst), reinterpret_cast<const unsigned char *>(src),
slen, nonce, shared_key_);
}
XSalsa20poly1305Encrypter::XSalsa20poly1305Encrypter(unsigned char *shared_key, size_t slen) {
memmove(shared_key_, shared_key, slen);
initNonce(nonce, crypto_box_NONCEBYTES, false);
maxNonce(max_nonce, crypto_box_NONCEBYTES, false);
}
XSalsa20poly1305Encrypter::~XSalsa20poly1305Encrypter() {
memset(shared_key_, 0, crypto_box_curve25519xsalsa20poly1305_BEFORENMBYTES);
}
void increaseNonce(unsigned char *nonce, size_t len) {
for (int i = len - 1; i >= 0; i--) {
nonce[i]++;
if (nonce[i] > 0) {
break;
}
}
}
void initNonce(unsigned char *initNonce, int nonceSize, bool initiator) {
sodium_memzero(initNonce, nonceSize);
if (!initiator) {
initNonce[0] |= 128;
}
}
void maxNonce(unsigned char *maxNonce, int nonceSize, bool initiator) {
for (int i=0; i<nonceSize; i++) {
maxNonce[i] = 255;
}
if(initiator) {
maxNonce[0] &= 127;
}
}