jplaui / gnark_lib

Apache License 2.0
0 stars 0 forks source link

About the operation of AES128 circuit #1

Open doubiliu opened 2 months ago

doubiliu commented 2 months ago

I wrote a simple test for AES128. But the operation result is wrong

`func TestAESGCMCircuit(t *testing.T) {

source := rand.NewSource(time.Now().UnixNano())
rand := rand.New(source)
privKey, err := ecies.GenerateKey(rand, crypto.S256(), nil)
if err != nil {
    return
}
//m := []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}

var px fp.Element
px.SetInterface(privKey.PublicKey.X)
var py fp.Element
py.SetInterface(privKey.PublicKey.Y)
Pub := secp256k1.G1Affine{
    px,
    py,
}
RawKey := Pub.RawBytes()
m := RawKey[:]
M_bytes := make([]frontend.Variable, len(m))
for i := 0; i < len(m); i++ {
    M_bytes[i] = m[i]
}

hasher := sha3.New256()
hasher.Write(RawKey[:])
expected := hasher.Sum(nil)
keyBytes := [16]frontend.Variable{}
for i := 0; i < len(keyBytes); i++ {
    keyBytes[i] = expected[i]
}

ciphertext, nonce := AesGcmEncrypt(expected[:16], m)
t.Logf("out aesencrypt,m:%x", m)
t.Logf("out aesencrypt,ciphertext:%x", ciphertext)
t.Logf("out aesencrypt,nonce:%x", nonce)
Ciphertext_bytes := make([]frontend.Variable, len(ciphertext))
for i := 0; i < len(ciphertext); i++ {
    Ciphertext_bytes[i] = ciphertext[i]
}
var ChunkIndex int
if len(ciphertext)%16 == 0 {
    ChunkIndex = len(ciphertext) / 16
} else {
    ChunkIndex = len(ciphertext)/16 + 1
}
nonce_bytes := [12]frontend.Variable{}
for i := 0; i < len(nonce); i++ {
    nonce_bytes[i] = nonce[i]
}

circuit := GCMWrapper{
    PlainChunks:  make([]frontend.Variable, len(M_bytes)),
    CipherChunks: make([]frontend.Variable, len(Ciphertext_bytes)),
}
witness := GCMWrapper{
    Key:          keyBytes,
    PlainChunks:  M_bytes,
    Iv:           nonce_bytes,
    ChunkIndex:   ChunkIndex,
    CipherChunks: Ciphertext_bytes,
}

assert := test.NewAssert(t)
err = test.IsSolved(&circuit, &witness, ecc.BN254.ScalarField())
assert.NoError(err)

}`

doubiliu commented 2 months ago

result: 14:51:00 DBG running circuit in test engine aes128_gcm_test.go:204: Error Trace: Error: Received unexpected error: [assertIsEqual] 14 == 191 circom2.(*GCM).Assert aes128_gcm_test.go:93 circom2.(*GCMWrapper).Define aes128_gcm_test.go:50 Test: TestAESGCMCircuit --- FAIL: TestAESGCMCircuit (1497.83s)

doubiliu commented 2 months ago

The AESGCM encryption I use externally is the standard library

`

func AesGcmEncrypt(key []byte, plaintext []byte) (ciphertext, nonce []byte) { block, err := aes.NewCipher(key) if err != nil { panic(err.Error()) } nonce = make([]byte, 12) if _, err := io.ReadFull(random.Reader, nonce); err != nil { panic(err.Error()) } aesgcm, err := cipher.NewGCM(block) if err != nil { panic(err.Error()) } ciphertext = aesgcm.Seal(nil, nonce, plaintext, nil) return }

`