Generate new key when nonce reaches max value

https://github.com/XTLS/Xray-core/pull/4952#issuecomment-3179685937
This commit is contained in:
RPRX
2025-08-12 14:50:44 +00:00
committed by GitHub
parent ec1cc35188
commit 5c61142048
3 changed files with 58 additions and 51 deletions

View File

@@ -1,15 +1,20 @@
package encryption
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"strconv"
"github.com/xtls/xray-core/common/errors"
"golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/hkdf"
)
func encodeHeader(b []byte, l int) {
var MaxNonce = bytes.Repeat([]byte{255}, 12)
func EncodeHeader(b []byte, l int) {
b[0] = 23
b[1] = 3
b[2] = 3
@@ -17,10 +22,10 @@ func encodeHeader(b []byte, l int) {
b[4] = byte(l)
}
func decodeHeader(b []byte) (int, error) {
func DecodeHeader(b []byte) (int, error) {
if b[0] == 23 && b[1] == 3 && b[2] == 3 {
l := int(b[3])<<8 | int(b[4])
if l < 17 || l > 17000 { // TODO
if l < 17 || l > 17000 { // TODO: TLSv1.3 max length
return 0, errors.New("invalid length in record's header: " + strconv.Itoa(l))
}
return l, nil
@@ -28,24 +33,23 @@ func decodeHeader(b []byte) (int, error) {
return 0, errors.New("invalid record's header")
}
func newAead(c byte, k []byte) (aead cipher.AEAD) {
func NewAead(c byte, secret, salt, info []byte) (aead cipher.AEAD) {
key := make([]byte, 32)
hkdf.New(sha256.New, secret, salt, info).Read(key)
if c&1 == 1 {
block, _ := aes.NewCipher(k)
block, _ := aes.NewCipher(key)
aead, _ = cipher.NewGCM(block)
} else {
aead, _ = chacha20poly1305.New(k)
aead, _ = chacha20poly1305.New(key)
}
return
}
func increaseNonce(nonce []byte) {
func IncreaseNonce(nonce []byte) {
for i := range 12 {
nonce[11-i]++
if nonce[11-i] != 0 {
break
}
if i == 11 {
// TODO
}
}
}