tap-agent 0.7.0

Rust implementation of the Transaction Authorization Protocol (TAP)
Documentation
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
//! Local Agent Key implementation for the TAP Agent
//!
//! This module provides a concrete implementation of the AgentKey trait
//! for keys that are stored locally, either in memory or on disk.

use crate::agent_key::{
    AgentKey, DecryptionKey, EncryptionKey, JweAlgorithm, JweEncryption, JwsAlgorithm, SigningKey,
    VerificationKey,
};
use crate::did::{KeyType, VerificationMaterial};
use crate::error::{Error, Result};
use crate::key_manager::{Secret, SecretMaterial};
use crate::message::{EphemeralPublicKey, Jwe, JweProtected, Jws, JwsProtected, JwsSignature};
#[cfg(feature = "crypto-p256")]
use crate::message::{JweHeader, JweRecipient};
use aes_gcm::{AeadInPlace, Aes256Gcm, KeyInit, Nonce};
use async_trait::async_trait;
use base64::Engine;
#[cfg(feature = "crypto-ed25519")]
use ed25519_dalek::{Signer as Ed25519Signer, Verifier, VerifyingKey};
#[cfg(feature = "crypto-secp256k1")]
use k256::{ecdsa::Signature as Secp256k1Signature, ecdsa::SigningKey as Secp256k1SigningKey};
#[cfg(feature = "crypto-p256")]
use p256::ecdh::EphemeralSecret as P256EphemeralSecret;
#[cfg(feature = "crypto-p256")]
use p256::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
#[cfg(feature = "crypto-p256")]
use p256::EncodedPoint as P256EncodedPoint;
#[cfg(feature = "crypto-p256")]
use p256::PublicKey as P256PublicKey;
#[cfg(feature = "crypto-p256")]
use p256::{ecdsa::Signature as P256Signature, ecdsa::SigningKey as P256SigningKey};
#[cfg(any(
    feature = "crypto-ed25519",
    feature = "crypto-p256",
    feature = "crypto-secp256k1"
))]
use rand::{rngs::OsRng, RngCore};
use serde_json::Value;
use std::convert::TryFrom;
use std::sync::Arc;
use uuid::Uuid;

/// A local implementation of the AgentKey that stores the key material directly
#[derive(Debug, Clone)]
pub struct LocalAgentKey {
    /// The key's ID
    kid: String,
    /// The associated DID
    did: String,
    /// The secret containing the key material
    pub secret: Secret,
    /// The key type
    key_type: KeyType,
}

impl LocalAgentKey {
    /// Verify a JWS against this key
    pub async fn verify_jws(&self, jws: &crate::message::Jws) -> Result<Vec<u8>> {
        // Find the signature that matches our key ID
        let our_kid = crate::agent_key::AgentKey::key_id(self).to_string();
        let signature = jws
            .signatures
            .iter()
            .find(|s| s.get_kid() == Some(our_kid.clone()))
            .ok_or_else(|| {
                Error::Cryptography(format!("No signature found with kid: {}", our_kid))
            })?;

        // Parse the protected header to get the algorithm
        let protected = signature.get_protected_header().map_err(|e| {
            Error::Cryptography(format!("Failed to decode protected header: {}", e))
        })?;

        // Decode the signature (accept both base64 and base64url)
        let signature_bytes = crate::message::base64_decode_flexible(&signature.signature)
            .map_err(|e| Error::Cryptography(format!("Failed to decode signature: {}", e)))?;

        // Construct the signing input: {protected}.{payload}
        let signing_input = format!("{}.{}", signature.protected, jws.payload);

        // Verify the signature using the actual cryptographic verification
        let verified = self
            .verify_signature(signing_input.as_bytes(), &signature_bytes, &protected)
            .await?;

        if !verified {
            return Err(Error::Cryptography(
                "Signature verification failed".to_string(),
            ));
        }

        // Decode and return the payload (accept both base64 and base64url)
        let payload_bytes = crate::message::base64_decode_flexible(&jws.payload)
            .map_err(|e| Error::Cryptography(format!("Failed to decode payload: {}", e)))?;

        Ok(payload_bytes)
    }

    /// Unwrap a JWE to retrieve the plaintext using proper ECDH-ES+A256KW decryption
    pub async fn decrypt_jwe(&self, jwe: &crate::message::Jwe) -> Result<Vec<u8>> {
        // Use the proper JWE unwrapping implementation from DecryptionKey trait
        DecryptionKey::unwrap_jwe(self, jwe).await
    }

    /// Verify a signature against this key
    pub async fn verify(&self, payload: &[u8], signature: &[u8]) -> Result<()> {
        // Create a protected header with the appropriate algorithm
        let protected = JwsProtected {
            typ: "JWT".to_string(),
            alg: self.recommended_jws_alg().as_str().to_string(),
            kid: crate::agent_key::AgentKey::key_id(self).to_string(),
        };

        // Verify the signature
        let result = self
            .verify_signature(payload, signature, &protected)
            .await?;
        if result {
            Ok(())
        } else {
            Err(Error::Cryptography(
                "Signature verification failed".to_string(),
            ))
        }
    }

    /// Encrypt data to a JWK recipient using proper ECDH-ES+A256KW
    pub async fn encrypt_to_jwk(
        &self,
        plaintext: &[u8],
        recipient_jwk: &Value,
        protected_header: Option<JweProtected>,
    ) -> Result<Jwe> {
        #[cfg(feature = "crypto-p256")]
        {
            // 1. Generate random CEK (Content Encryption Key)
            let mut cek = [0u8; 32];
            OsRng.fill_bytes(&mut cek);

            // 2. Generate random IV for AES-GCM
            let mut iv_bytes = [0u8; 12];
            OsRng.fill_bytes(&mut iv_bytes);

            // 3. Generate ephemeral key pair for ECDH
            let ephemeral_secret = P256EphemeralSecret::random(&mut OsRng);
            let ephemeral_public_key = ephemeral_secret.public_key();

            // Convert ephemeral public key to JWK coordinates
            let point = ephemeral_public_key.to_encoded_point(false);
            let x_bytes = point.x().unwrap().to_vec();
            let y_bytes = point.y().unwrap().to_vec();
            let x_b64 = base64::engine::general_purpose::STANDARD.encode(&x_bytes);
            let y_b64 = base64::engine::general_purpose::STANDARD.encode(&y_bytes);

            let ephemeral_key = crate::message::EphemeralPublicKey::Ec {
                crv: "P-256".to_string(),
                x: x_b64,
                y: y_b64,
            };

            // 4. Extract recipient public key from JWK
            let recipient_x_b64 =
                recipient_jwk
                    .get("x")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| {
                        Error::Cryptography("Missing x coordinate in recipient JWK".to_string())
                    })?;
            let recipient_y_b64 =
                recipient_jwk
                    .get("y")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| {
                        Error::Cryptography("Missing y coordinate in recipient JWK".to_string())
                    })?;

            let recipient_x = base64::engine::general_purpose::STANDARD
                .decode(recipient_x_b64)
                .map_err(|e| Error::Cryptography(format!("Failed to decode x: {}", e)))?;
            let recipient_y = base64::engine::general_purpose::STANDARD
                .decode(recipient_y_b64)
                .map_err(|e| Error::Cryptography(format!("Failed to decode y: {}", e)))?;

            // Reconstruct recipient public key
            let mut recipient_point_bytes = vec![0x04]; // Uncompressed
            recipient_point_bytes.extend_from_slice(&recipient_x);
            recipient_point_bytes.extend_from_slice(&recipient_y);

            let recipient_encoded_point = P256EncodedPoint::from_bytes(&recipient_point_bytes)
                .map_err(|e| Error::Cryptography(format!("Invalid recipient point: {}", e)))?;

            let recipient_pk = P256PublicKey::from_encoded_point(&recipient_encoded_point);
            if recipient_pk.is_none().into() {
                return Err(Error::Cryptography(
                    "Invalid recipient public key".to_string(),
                ));
            }
            let recipient_pk = recipient_pk.unwrap();

            // 5. Perform ECDH
            let shared_secret = ephemeral_secret.diffie_hellman(&recipient_pk);
            let shared_bytes = shared_secret.raw_secret_bytes();

            // 6. Create protected header
            let apv_raw = Uuid::new_v4();
            let apv_b64 = base64::engine::general_purpose::STANDARD.encode(apv_raw.as_bytes());

            let protected = protected_header.unwrap_or_else(|| crate::message::JweProtected {
                epk: ephemeral_key,
                apv: apv_b64.clone(),
                apu: String::new(),
                typ: crate::message::DIDCOMM_ENCRYPTED.to_string(),
                enc: "A256GCM".to_string(),
                alg: "ECDH-ES+A256KW".to_string(),
            });

            // 7. Derive KEK using Concat KDF
            let apv_bytes = base64::engine::general_purpose::STANDARD
                .decode(&protected.apv)
                .unwrap_or_default();
            let kek =
                crate::crypto::derive_key_ecdh_es(shared_bytes.as_slice(), b"", &apv_bytes, 256)?;

            // 8. Wrap CEK with AES-KW
            let mut kek_array = [0u8; 32];
            kek_array.copy_from_slice(&kek);
            let wrapped_cek = crate::crypto::wrap_key_aes_kw(&kek_array, &cek)?;

            // 9. Encrypt plaintext with AES-GCM
            let cipher = Aes256Gcm::new_from_slice(&cek)
                .map_err(|e| Error::Cryptography(format!("Failed to create cipher: {}", e)))?;

            let nonce = Nonce::from_slice(&iv_bytes);
            let mut buffer = plaintext.to_vec();
            let tag = cipher
                .encrypt_in_place_detached(nonce, b"", &mut buffer)
                .map_err(|e| Error::Cryptography(format!("Encryption failed: {:?}", e)))?;

            // 10. Serialize protected header
            let protected_json = serde_json::to_string(&protected).map_err(|e| {
                Error::Serialization(format!("Failed to serialize protected header: {}", e))
            })?;
            let protected_b64 = base64::engine::general_purpose::STANDARD.encode(protected_json);

            // Get recipient kid from JWK if available
            let recipient_kid = recipient_jwk
                .get("kid")
                .and_then(|v| v.as_str())
                .unwrap_or("recipient-key")
                .to_string();

            // 11. Build JWE
            let jwe = crate::message::Jwe {
                ciphertext: base64::engine::general_purpose::STANDARD.encode(&buffer),
                protected: protected_b64,
                recipients: vec![crate::message::JweRecipient {
                    encrypted_key: base64::engine::general_purpose::STANDARD.encode(&wrapped_cek),
                    header: crate::message::JweHeader {
                        kid: recipient_kid,
                        sender_kid: Some(AgentKey::key_id(self).to_string()),
                    },
                }],
                tag: base64::engine::general_purpose::STANDARD.encode(tag),
                iv: base64::engine::general_purpose::STANDARD.encode(iv_bytes),
            };

            Ok(jwe)
        }

        #[cfg(not(feature = "crypto-p256"))]
        {
            let _ = (plaintext, recipient_jwk, protected_header);
            Err(Error::Cryptography(
                "P-256 encryption not available - enable crypto-p256 feature".to_string(),
            ))
        }
    }

    /// Create a new LocalAgentKey from a Secret and key type
    pub fn new(secret: Secret, key_type: KeyType) -> Self {
        let did = secret.id.clone();
        let kid = match &secret.secret_material {
            SecretMaterial::JWK { private_key_jwk } => {
                if let Some(kid) = private_key_jwk.get("kid").and_then(|k| k.as_str()) {
                    kid.to_string()
                } else {
                    // Generate default key ID based on DID method
                    if let Some(key_part) = did.strip_prefix("did:key:") {
                        // For did:key, extract the multibase key from the DID and use it as fragment
                        // did:key:z6Mk... -> did:key:z6Mk...#z6Mk...
                        format!("{}#{}", did, key_part)
                    } else if did.starts_with("did:web:") {
                        format!("{}#keys-1", did)
                    } else {
                        format!("{}#key-1", did)
                    }
                }
            }
        };

        Self {
            kid,
            did,
            secret,
            key_type,
        }
    }

    /// Generate a new Ed25519 key with the given key ID
    #[cfg(feature = "crypto-ed25519")]
    pub fn generate_ed25519(_kid: &str) -> Result<Self> {
        // Generate a new Ed25519 keypair
        let mut csprng = OsRng;
        let signing_key = ed25519_dalek::SigningKey::generate(&mut csprng);
        let verifying_key = VerifyingKey::from(&signing_key);

        // Extract public and private keys
        let public_key = verifying_key.to_bytes();
        let private_key = signing_key.to_bytes();

        // Create did:key identifier
        // Multicodec prefix for Ed25519: 0xed01
        let mut prefixed_key = vec![0xed, 0x01];
        prefixed_key.extend_from_slice(&public_key);

        // Encode the key with multibase (base58btc with 'z' prefix)
        let multibase_encoded = multibase::encode(multibase::Base::Base58Btc, &prefixed_key);
        let did = format!("did:key:{}", multibase_encoded);

        // Generate the proper verification method ID (did:key:z...#z...)
        let kid = format!("{}#{}", did, multibase_encoded);

        // Create the secret
        let secret = Secret {
            id: did.clone(),
            type_: crate::key_manager::SecretType::JsonWebKey2020,
            secret_material: SecretMaterial::JWK {
                private_key_jwk: serde_json::json!({
                    "kty": "OKP",
                    "kid": kid.clone(),
                    "crv": "Ed25519",
                    "x": base64::engine::general_purpose::STANDARD.encode(public_key),
                    "d": base64::engine::general_purpose::STANDARD.encode(private_key)
                }),
            },
        };

        Ok(Self {
            kid,
            did,
            secret,
            key_type: KeyType::Ed25519,
        })
    }

    /// Generate a new P-256 key with the given key ID
    #[cfg(feature = "crypto-p256")]
    pub fn generate_p256(_kid: &str) -> Result<Self> {
        // Generate a new P-256 keypair
        let mut rng = OsRng;
        let signing_key = p256::ecdsa::SigningKey::random(&mut rng);

        // Extract public and private keys
        let private_key = signing_key.to_bytes().to_vec();
        let public_key = signing_key
            .verifying_key()
            .to_encoded_point(false)
            .to_bytes();

        // Create did:key identifier
        // Multicodec prefix for P-256: 0x1200
        let mut prefixed_key = vec![0x12, 0x00];
        prefixed_key.extend_from_slice(&public_key);

        // Encode the key with multibase (base58btc with 'z' prefix)
        let multibase_encoded = multibase::encode(multibase::Base::Base58Btc, &prefixed_key);
        let did = format!("did:key:{}", multibase_encoded);

        // Generate the proper verification method ID (did:key:z...#z...)
        let kid = format!("{}#{}", did, multibase_encoded);

        // Extract x and y coordinates from public key
        let x = &public_key[1..33]; // Skip the first byte (0x04 for uncompressed)
        let y = &public_key[33..65];

        // Create the secret
        let secret = Secret {
            id: did.clone(),
            type_: crate::key_manager::SecretType::JsonWebKey2020,
            secret_material: SecretMaterial::JWK {
                private_key_jwk: serde_json::json!({
                    "kty": "EC",
                    "kid": kid.clone(),
                    "crv": "P-256",
                    "x": base64::engine::general_purpose::STANDARD.encode(x),
                    "y": base64::engine::general_purpose::STANDARD.encode(y),
                    "d": base64::engine::general_purpose::STANDARD.encode(&private_key)
                }),
            },
        };

        Ok(Self {
            kid,
            did,
            secret,
            key_type: KeyType::P256,
        })
    }

    /// Generate a new secp256k1 key with the given key ID
    #[cfg(feature = "crypto-secp256k1")]
    pub fn generate_secp256k1(_kid: &str) -> Result<Self> {
        // Generate a new secp256k1 keypair
        let mut rng = OsRng;
        let signing_key = k256::ecdsa::SigningKey::random(&mut rng);

        // Extract public and private keys
        let private_key = signing_key.to_bytes().to_vec();
        let public_key = signing_key
            .verifying_key()
            .to_encoded_point(false)
            .to_bytes();

        // Create did:key identifier
        // Multicodec prefix for secp256k1: 0xe701
        let mut prefixed_key = vec![0xe7, 0x01];
        prefixed_key.extend_from_slice(&public_key);

        // Encode the key with multibase (base58btc with 'z' prefix)
        let multibase_encoded = multibase::encode(multibase::Base::Base58Btc, &prefixed_key);
        let did = format!("did:key:{}", multibase_encoded);

        // Generate the proper verification method ID (did:key:z...#z...)
        let kid = format!("{}#{}", did, multibase_encoded);

        // Extract x and y coordinates from public key
        let x = &public_key[1..33]; // Skip the first byte (0x04 for uncompressed)
        let y = &public_key[33..65];

        // Create the secret
        let secret = Secret {
            id: did.clone(),
            type_: crate::key_manager::SecretType::JsonWebKey2020,
            secret_material: SecretMaterial::JWK {
                private_key_jwk: serde_json::json!({
                    "kty": "EC",
                    "kid": kid.clone(),
                    "crv": "secp256k1",
                    "x": base64::engine::general_purpose::STANDARD.encode(x),
                    "y": base64::engine::general_purpose::STANDARD.encode(y),
                    "d": base64::engine::general_purpose::STANDARD.encode(&private_key)
                }),
            },
        };

        Ok(Self {
            kid,
            did,
            secret,
            key_type: KeyType::Secp256k1,
        })
    }

    /// Extract the private key JWK from the secret
    fn private_key_jwk(&self) -> Result<&Value> {
        match &self.secret.secret_material {
            SecretMaterial::JWK { private_key_jwk } => Ok(private_key_jwk),
        }
    }

    /// Get the key type and curve from the private key JWK
    fn key_type_and_curve(&self) -> Result<(Option<&str>, Option<&str>)> {
        let jwk = self.private_key_jwk()?;
        let kty = jwk.get("kty").and_then(|v| v.as_str());
        let crv = jwk.get("crv").and_then(|v| v.as_str());
        Ok((kty, crv))
    }

    /// Convert the key to a complete JWK (including private key)
    pub fn to_jwk(&self) -> Result<Value> {
        Ok(self.private_key_jwk()?.clone())
    }
}

#[async_trait]
impl AgentKey for LocalAgentKey {
    fn key_id(&self) -> &str {
        &self.kid
    }

    fn public_key_jwk(&self) -> Result<Value> {
        let jwk = self.private_key_jwk()?;

        // Create a copy without the private key parts
        let mut public_jwk = serde_json::Map::new();

        // Copy all fields except 'd' (private key)
        for (key, value) in jwk
            .as_object()
            .ok_or_else(|| Error::Cryptography("Invalid JWK format: not an object".to_string()))?
        {
            if key != "d" {
                public_jwk.insert(key.clone(), value.clone());
            }
        }

        Ok(Value::Object(public_jwk))
    }

    fn did(&self) -> &str {
        &self.did
    }

    fn key_type(&self) -> &str {
        match self.key_type {
            #[cfg(feature = "crypto-ed25519")]
            KeyType::Ed25519 => "Ed25519",
            #[cfg(feature = "crypto-p256")]
            KeyType::P256 => "P-256",
            #[cfg(feature = "crypto-secp256k1")]
            KeyType::Secp256k1 => "secp256k1",
        }
    }
}

#[async_trait]
impl SigningKey for LocalAgentKey {
    async fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
        let (kty, crv) = self.key_type_and_curve()?;
        let jwk = self.private_key_jwk()?;

        match (kty, crv) {
            #[cfg(feature = "crypto-ed25519")]
            (Some("OKP"), Some("Ed25519")) => {
                // Extract the private key
                let private_key_base64 = jwk
                    .get("d")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| Error::Cryptography("Missing private key in JWK".to_string()))?;

                // Decode the private key from base64
                let private_key_bytes = base64::engine::general_purpose::STANDARD
                    .decode(private_key_base64)
                    .map_err(|e| {
                        Error::Cryptography(format!("Failed to decode private key: {}", e))
                    })?;

                // Ed25519 keys must be exactly 32 bytes
                if private_key_bytes.len() != 32 {
                    return Err(Error::Cryptography(format!(
                        "Invalid Ed25519 private key length: {}, expected 32 bytes",
                        private_key_bytes.len()
                    )));
                }

                // Create an Ed25519 signing key
                let signing_key =
                    match ed25519_dalek::SigningKey::try_from(private_key_bytes.as_slice()) {
                        Ok(key) => key,
                        Err(e) => {
                            return Err(Error::Cryptography(format!(
                                "Failed to create Ed25519 signing key: {:?}",
                                e
                            )))
                        }
                    };

                // Sign the message
                let signature = signing_key.sign(data);

                // Return the signature bytes
                Ok(signature.to_vec())
            }
            #[cfg(feature = "crypto-p256")]
            (Some("EC"), Some("P-256")) => {
                // Extract the private key (d parameter in JWK)
                let private_key_base64 =
                    jwk.get("d").and_then(|v| v.as_str()).ok_or_else(|| {
                        Error::Cryptography("Missing private key (d) in JWK".to_string())
                    })?;

                // Decode the private key from base64
                let private_key_bytes = base64::engine::general_purpose::STANDARD
                    .decode(private_key_base64)
                    .map_err(|e| {
                        Error::Cryptography(format!("Failed to decode P-256 private key: {}", e))
                    })?;

                // Create a P-256 signing key
                let signing_key = P256SigningKey::from_slice(&private_key_bytes).map_err(|e| {
                    Error::Cryptography(format!("Failed to create P-256 signing key: {:?}", e))
                })?;

                // Sign the message using ECDSA
                let signature: P256Signature = signing_key.sign(data);

                // Convert to raw bytes for JWS (R||S format, 64 bytes total)
                let signature_bytes = signature.to_bytes();
                Ok(signature_bytes.to_vec())
            }
            #[cfg(feature = "crypto-secp256k1")]
            (Some("EC"), Some("secp256k1")) => {
                // Extract the private key (d parameter in JWK)
                let private_key_base64 =
                    jwk.get("d").and_then(|v| v.as_str()).ok_or_else(|| {
                        Error::Cryptography("Missing private key (d) in JWK".to_string())
                    })?;

                // Decode the private key from base64
                let private_key_bytes = base64::engine::general_purpose::STANDARD
                    .decode(private_key_base64)
                    .map_err(|e| {
                        Error::Cryptography(format!(
                            "Failed to decode secp256k1 private key: {}",
                            e
                        ))
                    })?;

                // Create a secp256k1 signing key
                let signing_key =
                    Secp256k1SigningKey::from_slice(&private_key_bytes).map_err(|e| {
                        Error::Cryptography(format!(
                            "Failed to create secp256k1 signing key: {:?}",
                            e
                        ))
                    })?;

                // Sign the message using ECDSA
                let signature: Secp256k1Signature = signing_key.sign(data);

                // Convert to raw bytes for JWS (R||S format)
                let signature_bytes = signature.to_bytes();
                Ok(signature_bytes.to_vec())
            }
            // Handle unsupported key types
            _ => Err(Error::Cryptography(format!(
                "Unsupported key type for signing: kty={:?}, crv={:?}",
                kty, crv
            ))),
        }
    }

    fn recommended_jws_alg(&self) -> JwsAlgorithm {
        match self.key_type {
            #[cfg(feature = "crypto-ed25519")]
            KeyType::Ed25519 => JwsAlgorithm::EdDSA,
            #[cfg(feature = "crypto-p256")]
            KeyType::P256 => JwsAlgorithm::ES256,
            #[cfg(feature = "crypto-secp256k1")]
            KeyType::Secp256k1 => JwsAlgorithm::ES256K,
        }
    }

    async fn create_jws(
        &self,
        payload: &[u8],
        protected_header: Option<JwsProtected>,
    ) -> Result<Jws> {
        // Base64URL encode the payload (no padding) per RFC 7515
        let payload_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(payload);

        // Create the protected header if not provided, respecting the key type
        let protected = if let Some(mut header) = protected_header {
            // Override the algorithm to match the key type
            header.alg = self.recommended_jws_alg().as_str().to_string();
            // Only set kid if not already provided in the header
            if header.kid.is_empty() {
                header.kid = crate::agent_key::AgentKey::key_id(self).to_string();
            }
            header
        } else {
            JwsProtected {
                typ: crate::message::DIDCOMM_SIGNED.to_string(),
                alg: self.recommended_jws_alg().as_str().to_string(),
                kid: crate::agent_key::AgentKey::key_id(self).to_string(),
            }
        };

        // Serialize and encode the protected header
        let protected_json = serde_json::to_string(&protected).map_err(|e| {
            Error::Serialization(format!("Failed to serialize protected header: {}", e))
        })?;

        let protected_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(protected_json);

        // Create the signing input (protected.payload)
        let signing_input = format!("{}.{}", protected_b64, payload_b64);

        // Sign the input
        let signature = self.sign(signing_input.as_bytes()).await?;

        // Base64URL encode the signature (no padding) per RFC 7515
        let signature_value = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&signature);

        // Create the JWS with signature
        let jws = Jws {
            payload: payload_b64,
            signatures: vec![JwsSignature {
                protected: protected_b64,
                signature: signature_value,
            }],
        };

        Ok(jws)
    }
}

#[async_trait]
impl VerificationKey for LocalAgentKey {
    fn key_id(&self) -> &str {
        &self.kid
    }

    fn public_key_jwk(&self) -> Result<Value> {
        AgentKey::public_key_jwk(self)
    }

    async fn verify_signature(
        &self,
        payload: &[u8],
        signature: &[u8],
        protected_header: &JwsProtected,
    ) -> Result<bool> {
        let (kty, crv) = self.key_type_and_curve()?;
        let jwk = self.private_key_jwk()?;

        match (kty, crv, protected_header.alg.as_str()) {
            #[cfg(feature = "crypto-ed25519")]
            (Some("OKP"), Some("Ed25519"), "EdDSA") => {
                // Extract the public key
                let public_key_base64 = jwk.get("x").and_then(|v| v.as_str()).ok_or_else(|| {
                    Error::Cryptography("Missing public key (x) in JWK".to_string())
                })?;

                // Decode the public key from base64
                let public_key_bytes = base64::engine::general_purpose::STANDARD
                    .decode(public_key_base64)
                    .map_err(|e| {
                        Error::Cryptography(format!("Failed to decode public key: {}", e))
                    })?;

                // Ed25519 public keys must be exactly 32 bytes
                if public_key_bytes.len() != 32 {
                    return Err(Error::Cryptography(format!(
                        "Invalid Ed25519 public key length: {}, expected 32 bytes",
                        public_key_bytes.len()
                    )));
                }

                // Create an Ed25519 verifying key
                let verifying_key = match VerifyingKey::try_from(public_key_bytes.as_slice()) {
                    Ok(key) => key,
                    Err(e) => {
                        return Err(Error::Cryptography(format!(
                            "Failed to create Ed25519 verifying key: {:?}",
                            e
                        )))
                    }
                };

                // Verify the signature
                if signature.len() != 64 {
                    return Err(Error::Cryptography(format!(
                        "Invalid Ed25519 signature length: {}, expected 64 bytes",
                        signature.len()
                    )));
                }

                let mut sig_bytes = [0u8; 64];
                sig_bytes.copy_from_slice(signature);
                let ed_signature = ed25519_dalek::Signature::from_bytes(&sig_bytes);

                match verifying_key.verify(payload, &ed_signature) {
                    Ok(()) => Ok(true),
                    Err(_) => Ok(false),
                }
            }
            #[cfg(feature = "crypto-p256")]
            (Some("EC"), Some("P-256"), "ES256") => {
                // Extract the public key coordinates
                let x_b64 = jwk.get("x").and_then(|v| v.as_str()).ok_or_else(|| {
                    Error::Cryptography("Missing x coordinate in JWK".to_string())
                })?;
                let y_b64 = jwk.get("y").and_then(|v| v.as_str()).ok_or_else(|| {
                    Error::Cryptography("Missing y coordinate in JWK".to_string())
                })?;

                // Decode the coordinates
                let x_bytes = base64::engine::general_purpose::STANDARD
                    .decode(x_b64)
                    .map_err(|e| {
                        Error::Cryptography(format!("Failed to decode x coordinate: {}", e))
                    })?;
                let y_bytes = base64::engine::general_purpose::STANDARD
                    .decode(y_b64)
                    .map_err(|e| {
                        Error::Cryptography(format!("Failed to decode y coordinate: {}", e))
                    })?;

                // Create a P-256 encoded point from the coordinates
                let mut point_bytes = vec![0x04]; // Uncompressed point format
                point_bytes.extend_from_slice(&x_bytes);
                point_bytes.extend_from_slice(&y_bytes);

                let encoded_point = P256EncodedPoint::from_bytes(&point_bytes).map_err(|e| {
                    Error::Cryptography(format!("Failed to create P-256 encoded point: {}", e))
                })?;

                // This checks if the point is on the curve and returns the public key
                let public_key_opt = P256PublicKey::from_encoded_point(&encoded_point);
                if public_key_opt.is_none().into() {
                    return Err(Error::Cryptography("Invalid P-256 public key".to_string()));
                }
                let public_key = public_key_opt.unwrap();

                // Parse the signature from raw bytes (R||S format)
                let p256_signature = P256Signature::from_slice(signature).map_err(|e| {
                    Error::Cryptography(format!("Failed to parse P-256 signature: {:?}", e))
                })?;

                // Verify the signature using P-256 ECDSA
                let verifier = p256::ecdsa::VerifyingKey::from(public_key);
                match verifier.verify(payload, &p256_signature) {
                    Ok(()) => Ok(true),
                    Err(_) => Ok(false),
                }
            }
            #[cfg(feature = "crypto-secp256k1")]
            (Some("EC"), Some("secp256k1"), "ES256K") => {
                // Extract the public key coordinates
                let x_b64 = jwk.get("x").and_then(|v| v.as_str()).ok_or_else(|| {
                    Error::Cryptography("Missing x coordinate in JWK".to_string())
                })?;
                let y_b64 = jwk.get("y").and_then(|v| v.as_str()).ok_or_else(|| {
                    Error::Cryptography("Missing y coordinate in JWK".to_string())
                })?;

                // Decode the coordinates
                let x_bytes = base64::engine::general_purpose::STANDARD
                    .decode(x_b64)
                    .map_err(|e| {
                        Error::Cryptography(format!("Failed to decode x coordinate: {}", e))
                    })?;
                let y_bytes = base64::engine::general_purpose::STANDARD
                    .decode(y_b64)
                    .map_err(|e| {
                        Error::Cryptography(format!("Failed to decode y coordinate: {}", e))
                    })?;

                // Create a secp256k1 public key from the coordinates
                let mut point_bytes = vec![0x04]; // Uncompressed point format
                point_bytes.extend_from_slice(&x_bytes);
                point_bytes.extend_from_slice(&y_bytes);

                // Parse the verifying key from the SEC1 encoded point
                let verifier =
                    k256::ecdsa::VerifyingKey::from_sec1_bytes(&point_bytes).map_err(|e| {
                        Error::Cryptography(format!(
                            "Failed to create secp256k1 verifying key: {:?}",
                            e
                        ))
                    })?;

                // Parse the signature from raw bytes (R||S format)
                let k256_signature = Secp256k1Signature::from_slice(signature).map_err(|e| {
                    Error::Cryptography(format!("Failed to parse secp256k1 signature: {:?}", e))
                })?;

                // Verify the signature
                match verifier.verify(payload, &k256_signature) {
                    Ok(()) => Ok(true),
                    Err(_) => Ok(false),
                }
            }
            // Unsupported algorithm or key type combination
            _ => Err(Error::Cryptography(format!(
                "Unsupported key type/algorithm combination for verification: kty={:?}, crv={:?}, alg={}",
                kty, crv, protected_header.alg
            ))),
        }
    }
}

#[async_trait]
impl EncryptionKey for LocalAgentKey {
    async fn encrypt(
        &self,
        plaintext: &[u8],
        aad: Option<&[u8]>,
        _recipient_public_key: &dyn VerificationKey,
    ) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
        // We'll implement AES-GCM encryption with key derived from ECDH

        // 1. Generate a random content encryption key (CEK)
        let mut cek = [0u8; 32]; // 256-bit key for AES-GCM
        OsRng.fill_bytes(&mut cek);

        // 2. Generate IV for AES-GCM
        let mut iv_bytes = [0u8; 12]; // 96-bit IV for AES-GCM
        OsRng.fill_bytes(&mut iv_bytes);

        // 3. Encrypt the plaintext with AES-GCM
        let cipher = Aes256Gcm::new_from_slice(&cek)
            .map_err(|e| Error::Cryptography(format!("Failed to create AES-GCM cipher: {}", e)))?;

        // Create a nonce from the IV
        let nonce = Nonce::from_slice(&iv_bytes);

        // Encrypt the plaintext
        let mut buffer = plaintext.to_vec();
        let aad_bytes = aad.unwrap_or(b"");
        let tag = cipher
            .encrypt_in_place_detached(nonce, aad_bytes, &mut buffer)
            .map_err(|e| Error::Cryptography(format!("AES-GCM encryption failed: {}", e)))?;

        // Return ciphertext, IV, and tag
        Ok((buffer, iv_bytes.to_vec(), tag.to_vec()))
    }

    fn recommended_jwe_alg_enc(&self) -> (JweAlgorithm, JweEncryption) {
        // If we need special handling for P-256, we could implement it here
        // but for now keep it simple
        (JweAlgorithm::EcdhEsA256kw, JweEncryption::A256GCM)
    }

    async fn create_jwe(
        &self,
        plaintext: &[u8],
        recipients: &[Arc<dyn VerificationKey>],
        protected_header: Option<JweProtected>,
    ) -> Result<Jwe> {
        if recipients.is_empty() {
            return Err(Error::Validation(
                "No recipients specified for JWE".to_string(),
            ));
        }

        // 1. Generate a random content encryption key (CEK)
        let mut cek = [0u8; 32]; // 256-bit key for AES-GCM
        OsRng.fill_bytes(&mut cek);

        // 2. Generate IV for AES-GCM
        let mut iv_bytes = [0u8; 12]; // 96-bit IV for AES-GCM
        OsRng.fill_bytes(&mut iv_bytes);

        // 3. Generate an ephemeral key pair for ECDH
        #[cfg(feature = "crypto-p256")]
        let ephemeral_secret = P256EphemeralSecret::random(&mut OsRng);
        #[cfg(feature = "crypto-p256")]
        let ephemeral_public_key = ephemeral_secret.public_key();

        // 4. Convert the public key to coordinates for the header
        #[cfg(feature = "crypto-p256")]
        let point = ephemeral_public_key.to_encoded_point(false); // Uncompressed format
        #[cfg(feature = "crypto-p256")]
        let x_bytes = point.x().unwrap().to_vec();
        #[cfg(feature = "crypto-p256")]
        let y_bytes = point.y().unwrap().to_vec();

        // Base64 encode the coordinates for the ephemeral public key
        #[cfg(feature = "crypto-p256")]
        let x_b64 = base64::engine::general_purpose::STANDARD.encode(&x_bytes);
        #[cfg(feature = "crypto-p256")]
        let y_b64 = base64::engine::general_purpose::STANDARD.encode(&y_bytes);

        // Create the ephemeral public key structure
        #[cfg(feature = "crypto-p256")]
        let ephemeral_key = EphemeralPublicKey::Ec {
            crv: "P-256".to_string(),
            x: x_b64,
            y: y_b64,
        };
        #[cfg(not(feature = "crypto-p256"))]
        let ephemeral_key = EphemeralPublicKey::Ec {
            crv: "P-256".to_string(),
            x: "".to_string(),
            y: "".to_string(),
        };

        // 5. Create protected header
        let protected = protected_header.unwrap_or_else(|| {
            let (alg, enc) = self.recommended_jwe_alg_enc();
            JweProtected {
                epk: ephemeral_key,
                apv: base64::engine::general_purpose::STANDARD.encode(Uuid::new_v4().as_bytes()),
                apu: String::new(),
                typ: crate::message::DIDCOMM_ENCRYPTED.to_string(),
                enc: enc.as_str().to_string(),
                alg: alg.as_str().to_string(),
            }
        });

        // 6. Encrypt the plaintext with AES-GCM
        let cipher = Aes256Gcm::new_from_slice(&cek)
            .map_err(|e| Error::Cryptography(format!("Failed to create AES-GCM cipher: {}", e)))?;

        // Create a nonce from the IV
        let nonce = Nonce::from_slice(&iv_bytes);

        // Encrypt the plaintext
        let mut buffer = plaintext.to_vec();
        let tag = cipher
            .encrypt_in_place_detached(nonce, b"", &mut buffer)
            .map_err(|e| Error::Cryptography(format!("AES-GCM encryption failed: {}", e)))?;

        // 7. Process each recipient and create JWE
        #[cfg(not(feature = "crypto-p256"))]
        {
            let _ = (recipients, protected, buffer, tag, iv_bytes); // Suppress unused variable warnings
            return Err(Error::Cryptography(
                "P-256 encryption not available - enable crypto-p256 feature".to_string(),
            ));
        }

        #[cfg(feature = "crypto-p256")]
        {
            let mut jwe_recipients = Vec::with_capacity(recipients.len());

            for recipient in recipients {
                // Extract recipient's public key as JWK
                let recipient_jwk = recipient.public_key_jwk()?;

                // Extract key type and curve
                let kty = recipient_jwk.get("kty").and_then(|v| v.as_str());
                let crv = recipient_jwk.get("crv").and_then(|v| v.as_str());

                let encrypted_key = match (kty, crv) {
                    (Some("EC"), Some("P-256")) => {
                        // Extract the public key coordinates
                        let x_b64 =
                            recipient_jwk
                                .get("x")
                                .and_then(|v| v.as_str())
                                .ok_or_else(|| {
                                    Error::Cryptography(
                                        "Missing x coordinate in recipient JWK".to_string(),
                                    )
                                })?;
                        let y_b64 =
                            recipient_jwk
                                .get("y")
                                .and_then(|v| v.as_str())
                                .ok_or_else(|| {
                                    Error::Cryptography(
                                        "Missing y coordinate in recipient JWK".to_string(),
                                    )
                                })?;

                        let x_bytes = base64::engine::general_purpose::STANDARD
                            .decode(x_b64)
                            .map_err(|e| {
                                Error::Cryptography(format!("Failed to decode x coordinate: {}", e))
                            })?;
                        let y_bytes = base64::engine::general_purpose::STANDARD
                            .decode(y_b64)
                            .map_err(|e| {
                                Error::Cryptography(format!("Failed to decode y coordinate: {}", e))
                            })?;

                        // Create a P-256 encoded point from the coordinates
                        let mut point_bytes = vec![0x04]; // Uncompressed point format
                        point_bytes.extend_from_slice(&x_bytes);
                        point_bytes.extend_from_slice(&y_bytes);

                        let encoded_point =
                            P256EncodedPoint::from_bytes(&point_bytes).map_err(|e| {
                                Error::Cryptography(format!(
                                    "Failed to create P-256 encoded point: {}",
                                    e
                                ))
                            })?;

                        // This checks if the point is on the curve and returns the public key
                        let recipient_pk_opt = P256PublicKey::from_encoded_point(&encoded_point);
                        if recipient_pk_opt.is_none().into() {
                            return Err(Error::Cryptography(
                                "Invalid P-256 public key".to_string(),
                            ));
                        }
                        let recipient_pk = recipient_pk_opt.unwrap();

                        // Perform ECDH to derive a shared secret
                        let shared_secret = ephemeral_secret.diffie_hellman(&recipient_pk);
                        let shared_bytes = shared_secret.raw_secret_bytes();

                        // Derive KEK using Concat KDF per RFC 7518
                        // Use APV from protected header for consistency with decryption
                        let apv_bytes = base64::engine::general_purpose::STANDARD
                            .decode(&protected.apv)
                            .unwrap_or_default();
                        let kek = crate::crypto::derive_key_ecdh_es(
                            shared_bytes.as_slice(),
                            b"", // apu - empty for anonymous sender
                            &apv_bytes,
                            256, // 256 bits for AES-256-KW
                        )?;

                        // Wrap CEK with AES-KW per RFC 3394
                        let mut kek_array = [0u8; 32];
                        kek_array.copy_from_slice(&kek);

                        crate::crypto::wrap_key_aes_kw(&kek_array, &cek)?
                    }
                    // Handle other key types
                    _ => {
                        return Err(Error::Cryptography(format!(
                            "Unsupported recipient key type for encryption: kty={:?}, crv={:?}",
                            kty, crv
                        )));
                    }
                };

                // Add this recipient to the JWE
                jwe_recipients.push(JweRecipient {
                    encrypted_key: base64::engine::general_purpose::STANDARD.encode(encrypted_key),
                    header: JweHeader {
                        kid: (**recipient).key_id().to_string(),
                        sender_kid: Some(crate::agent_key::AgentKey::key_id(self).to_string()),
                    },
                });
            }

            // 8. Serialize and encode the protected header
            let protected_json = serde_json::to_string(&protected).map_err(|e| {
                Error::Serialization(format!("Failed to serialize protected header: {}", e))
            })?;

            let protected_b64 = base64::engine::general_purpose::STANDARD.encode(protected_json);

            // 9. Create the JWE
            let jwe = Jwe {
                ciphertext: base64::engine::general_purpose::STANDARD.encode(buffer),
                protected: protected_b64,
                recipients: jwe_recipients,
                tag: base64::engine::general_purpose::STANDARD.encode(tag),
                iv: base64::engine::general_purpose::STANDARD.encode(iv_bytes),
            };

            Ok(jwe)
        }
    }
}

#[async_trait]
impl DecryptionKey for LocalAgentKey {
    async fn decrypt(
        &self,
        ciphertext: &[u8],
        encrypted_key: &[u8],
        iv: &[u8],
        tag: &[u8],
        aad: Option<&[u8]>,
        _sender_key: Option<&dyn VerificationKey>,
    ) -> Result<Vec<u8>> {
        // The decrypt() trait method does not receive the ephemeral public key (EPK)
        // required for ECDH-ES+A256KW key agreement. Use unwrap_jwe() instead, which
        // parses the full JWE structure including the EPK from the protected header.
        let _ = (ciphertext, encrypted_key, iv, tag, aad);
        Err(Error::Cryptography(
            "decrypt() is not supported for ECDH-ES+A256KW keys; use unwrap_jwe() instead"
                .to_string(),
        ))
    }

    async fn unwrap_jwe(&self, jwe: &Jwe) -> Result<Vec<u8>> {
        let our_kid = crate::agent_key::AgentKey::key_id(self);

        // Find recipient matching our key ID or any X25519 key agreement key derived from our DID
        let our_did = our_kid.split('#').next().unwrap_or(our_kid);
        let recipient = jwe
            .recipients
            .iter()
            .find(|r| r.header.kid == our_kid || r.header.kid.starts_with(&format!("{}#", our_did)))
            .ok_or_else(|| {
                Error::Cryptography(format!(
                    "No matching recipient found for key ID: {}",
                    our_kid
                ))
            })?;

        // Decode and parse the protected header to get the EPK
        let protected_bytes =
            crate::message::base64_decode_flexible(&jwe.protected).map_err(|e| {
                Error::Cryptography(format!("Failed to decode protected header: {}", e))
            })?;

        let protected: JweProtected = serde_json::from_slice(&protected_bytes)
            .map_err(|e| Error::Cryptography(format!("Failed to parse protected header: {}", e)))?;

        // Decode the JWE elements (accept both base64 and base64url)
        let ciphertext = crate::message::base64_decode_flexible(&jwe.ciphertext)
            .map_err(|e| Error::Cryptography(format!("Failed to decode ciphertext: {}", e)))?;

        let wrapped_cek = crate::message::base64_decode_flexible(&recipient.encrypted_key)
            .map_err(|e| Error::Cryptography(format!("Failed to decode encrypted key: {}", e)))?;

        let iv = crate::message::base64_decode_flexible(&jwe.iv)
            .map_err(|e| Error::Cryptography(format!("Failed to decode IV: {}", e)))?;

        let tag = crate::message::base64_decode_flexible(&jwe.tag)
            .map_err(|e| Error::Cryptography(format!("Failed to decode tag: {}", e)))?;

        // Perform ECDH based on EPK type
        let shared_bytes: Vec<u8> = match &protected.epk {
            #[cfg(feature = "crypto-ed25519")]
            EphemeralPublicKey::Okp { crv, x } if crv == "X25519" => {
                // X25519 ECDH: convert our Ed25519 private key to X25519 and perform DH
                let epk_bytes = crate::message::base64_decode_flexible(x).map_err(|e| {
                    Error::Cryptography(format!("Failed to decode X25519 EPK: {}", e))
                })?;
                if epk_bytes.len() != 32 {
                    return Err(Error::Cryptography("Invalid X25519 EPK length".to_string()));
                }

                // Get our Ed25519 private key and convert to X25519
                let jwk = self.private_key_jwk()?;
                let d_b64 = jwk.get("d").and_then(|v| v.as_str()).ok_or_else(|| {
                    Error::Cryptography("Missing private key (d) in JWK".to_string())
                })?;
                let d_bytes = crate::message::base64_decode_flexible(d_b64).map_err(|e| {
                    Error::Cryptography(format!("Failed to decode private key: {}", e))
                })?;

                // Ed25519 seed → X25519 secret: SHA-512 hash of seed, first 32 bytes
                // x25519-dalek handles clamping internally
                use sha2::Digest;
                let hash = sha2::Sha512::digest(&d_bytes);
                let mut x25519_key_bytes = [0u8; 32];
                x25519_key_bytes.copy_from_slice(&hash[..32]);

                let secret = x25519_dalek::StaticSecret::from(x25519_key_bytes);
                let epk_array: [u8; 32] = epk_bytes[..32].try_into().unwrap();
                let public = x25519_dalek::PublicKey::from(epk_array);
                let shared = secret.diffie_hellman(&public);
                shared.as_bytes().to_vec()
            }
            #[cfg(feature = "crypto-p256")]
            EphemeralPublicKey::Ec { x, y, .. } => {
                // P-256 ECDH
                let epk_x = crate::message::base64_decode_flexible(x)
                    .map_err(|e| Error::Cryptography(format!("Failed to decode EPK x: {}", e)))?;
                let epk_y = crate::message::base64_decode_flexible(y)
                    .map_err(|e| Error::Cryptography(format!("Failed to decode EPK y: {}", e)))?;

                let mut epk_point_bytes = vec![0x04];
                epk_point_bytes.extend_from_slice(&epk_x);
                epk_point_bytes.extend_from_slice(&epk_y);

                let epk_encoded_point = P256EncodedPoint::from_bytes(&epk_point_bytes)
                    .map_err(|e| Error::Cryptography(format!("Invalid EPK point: {}", e)))?;

                let epk_public_key = P256PublicKey::from_encoded_point(&epk_encoded_point);
                if epk_public_key.is_none().into() {
                    return Err(Error::Cryptography("Invalid EPK public key".to_string()));
                }
                let epk_public_key = epk_public_key.unwrap();

                let jwk = self.private_key_jwk()?;
                let d_b64 = jwk.get("d").and_then(|v| v.as_str()).ok_or_else(|| {
                    Error::Cryptography("Missing private key (d) in JWK".to_string())
                })?;
                let d_bytes = base64::engine::general_purpose::STANDARD
                    .decode(d_b64)
                    .map_err(|e| {
                        Error::Cryptography(format!("Failed to decode private key: {}", e))
                    })?;

                let secret_key = p256::SecretKey::from_bytes((&d_bytes[..]).into())
                    .map_err(|e| Error::Cryptography(format!("Invalid private key: {}", e)))?;

                let shared_secret = p256::ecdh::diffie_hellman(
                    secret_key.to_nonzero_scalar(),
                    epk_public_key.as_affine(),
                );
                shared_secret.raw_secret_bytes().to_vec()
            }
            _ => {
                return Err(Error::Cryptography(
                    "Unsupported EPK type for JWE decryption".to_string(),
                ))
            }
        };

        // Derive KEK using Concat KDF
        // Per RFC 7518 Section 4.6.2, apu and apv are base64url-decoded before use
        let apu = if protected.apu.is_empty() {
            Vec::new()
        } else {
            crate::message::base64_decode_flexible(&protected.apu).unwrap_or_default()
        };
        let apv = if protected.apv.is_empty() {
            Vec::new()
        } else {
            crate::message::base64_decode_flexible(&protected.apv).unwrap_or_default()
        };

        let kek = crate::crypto::derive_key_ecdh_es(&shared_bytes, &apu, &apv, 256)?;

        // Unwrap CEK using AES-KW
        let mut kek_array = [0u8; 32];
        kek_array.copy_from_slice(&kek);
        let cek = crate::crypto::unwrap_key_aes_kw(&kek_array, &wrapped_cek)?;

        // Decrypt ciphertext with AES-GCM using the CEK
        let cipher = Aes256Gcm::new_from_slice(&cek)
            .map_err(|e| Error::Cryptography(format!("Failed to create AES-GCM cipher: {}", e)))?;

        let nonce = Nonce::from_slice(&iv);

        let mut padded_tag = [0u8; 16];
        let copy_len = std::cmp::min(tag.len(), 16);
        padded_tag[..copy_len].copy_from_slice(&tag[..copy_len]);
        let tag_array = aes_gcm::Tag::from_slice(&padded_tag);

        let mut buffer = ciphertext.to_vec();
        cipher
            .decrypt_in_place_detached(nonce, jwe.protected.as_bytes(), &mut buffer, tag_array)
            .or_else(|_| {
                // Retry with empty AAD for backwards compatibility
                buffer = ciphertext.to_vec();
                cipher.decrypt_in_place_detached(nonce, b"", &mut buffer, tag_array)
            })
            .map_err(|e| Error::Cryptography(format!("AES-GCM decryption failed: {:?}", e)))?;

        Ok(buffer)
    }
}

/// A standalone verification key that can be used to verify signatures
#[derive(Debug, Clone)]
pub struct PublicVerificationKey {
    /// The key's ID
    kid: String,
    /// The public key material as a JWK
    public_jwk: Value,
}

impl PublicVerificationKey {
    /// Verify a JWS
    pub async fn verify_jws(&self, jws: &crate::message::Jws) -> Result<Vec<u8>> {
        // Find the signature that matches our key ID
        let signature = jws
            .signatures
            .iter()
            .find(|s| s.get_kid().as_ref() == Some(&self.kid))
            .ok_or_else(|| {
                Error::Cryptography(format!("No signature found with kid: {}", self.kid))
            })?;

        // Get the protected header
        let protected = signature.get_protected_header().map_err(|e| {
            Error::Cryptography(format!("Failed to decode protected header: {}", e))
        })?;

        // Decode the signature (accept both base64 and base64url)
        let signature_bytes = crate::message::base64_decode_flexible(&signature.signature)
            .map_err(|e| Error::Cryptography(format!("Failed to decode signature: {}", e)))?;

        // Create the signing input (protected.payload)
        let signing_input = format!("{}.{}", signature.protected, jws.payload);

        // Verify the signature
        let verified = self
            .verify_signature(signing_input.as_bytes(), &signature_bytes, &protected)
            .await
            .map_err(|e| Error::Cryptography(e.to_string()))?;

        if !verified {
            return Err(Error::Cryptography(
                "Signature verification failed".to_string(),
            ));
        }

        // Decode the payload (accept both base64 and base64url)
        let payload_bytes = crate::message::base64_decode_flexible(&jws.payload)
            .map_err(|e| Error::Cryptography(format!("Failed to decode payload: {}", e)))?;

        Ok(payload_bytes)
    }

    /// Verify a signature against this key
    pub async fn verify(&self, payload: &[u8], signature: &[u8]) -> Result<()> {
        // Get the key type and curve
        let kty = self.public_jwk.get("kty").and_then(|v| v.as_str());
        let crv = self.public_jwk.get("crv").and_then(|v| v.as_str());

        // Create a protected header with the appropriate algorithm
        let alg = match (kty, crv) {
            (Some("OKP"), Some("Ed25519")) => "EdDSA",
            (Some("EC"), Some("P-256")) => "ES256",
            (Some("EC"), Some("secp256k1")) => "ES256K",
            _ => return Err(Error::Cryptography("Unsupported key type".to_string())),
        };

        let protected = JwsProtected {
            typ: "JWT".to_string(),
            alg: alg.to_string(),
            kid: self.kid.clone(),
        };

        // Verify the signature
        let result = self
            .verify_signature(payload, signature, &protected)
            .await?;
        if result {
            Ok(())
        } else {
            Err(Error::Cryptography(
                "Signature verification failed".to_string(),
            ))
        }
    }

    /// Create a new PublicVerificationKey from a JWK
    pub fn new(kid: String, public_jwk: Value) -> Self {
        Self { kid, public_jwk }
    }

    /// Create a PublicVerificationKey from a JWK
    pub fn from_jwk(jwk: &Value, kid: &str, _did: &str) -> Result<Self> {
        // Create a copy without the private key parts
        let mut public_jwk = serde_json::Map::new();

        if let Some(obj) = jwk.as_object() {
            // Copy all fields except 'd' (private key)
            for (key, value) in obj {
                if key != "d" {
                    public_jwk.insert(key.clone(), value.clone());
                }
            }
        } else {
            return Err(Error::Cryptography(
                "Invalid JWK format: not an object".to_string(),
            ));
        }

        Ok(Self {
            kid: kid.to_string(),
            public_jwk: Value::Object(public_jwk),
        })
    }

    /// Create a PublicVerificationKey from a VerificationMaterial
    pub fn from_verification_material(
        kid: String,
        material: &VerificationMaterial,
    ) -> Result<Self> {
        match material {
            VerificationMaterial::JWK { public_key_jwk } => {
                Ok(Self::new(kid, public_key_jwk.clone()))
            }
            VerificationMaterial::Base58 { public_key_base58 } => {
                // Convert Base58 to JWK
                let public_key_bytes = bs58::decode(public_key_base58).into_vec().map_err(|e| {
                    Error::Cryptography(format!("Failed to decode Base58 key: {}", e))
                })?;

                // Assume Ed25519 for Base58 keys
                Ok(Self::new(
                    kid,
                    serde_json::json!({
                        "kty": "OKP",
                        "crv": "Ed25519",
                        "x": base64::engine::general_purpose::STANDARD.encode(public_key_bytes),
                    }),
                ))
            }
            VerificationMaterial::Multibase {
                public_key_multibase,
            } => {
                // Convert Multibase to JWK
                let (_, bytes) = multibase::decode(public_key_multibase).map_err(|e| {
                    Error::Cryptography(format!("Failed to decode Multibase key: {}", e))
                })?;

                // Check if this is an Ed25519 key with multicodec prefix
                if bytes.len() >= 2 && bytes[0] == 0xed && bytes[1] == 0x01 {
                    // Strip multicodec prefix for Ed25519
                    let key_bytes = &bytes[2..];
                    Ok(Self::new(
                        kid,
                        serde_json::json!({
                            "kty": "OKP",
                            "crv": "Ed25519",
                            "x": base64::engine::general_purpose::STANDARD.encode(key_bytes),
                        }),
                    ))
                } else {
                    // Just use the bytes as is
                    Ok(Self::new(
                        kid,
                        serde_json::json!({
                            "kty": "OKP",
                            "crv": "Ed25519",
                            "x": base64::engine::general_purpose::STANDARD.encode(bytes),
                        }),
                    ))
                }
            }
        }
    }
}

#[async_trait]
impl VerificationKey for PublicVerificationKey {
    fn key_id(&self) -> &str {
        &self.kid
    }

    fn public_key_jwk(&self) -> Result<Value> {
        Ok(self.public_jwk.clone())
    }

    async fn verify_signature(
        &self,
        payload: &[u8],
        signature: &[u8],
        protected_header: &JwsProtected,
    ) -> Result<bool> {
        let kty = self.public_jwk.get("kty").and_then(|v| v.as_str());
        let crv = self.public_jwk.get("crv").and_then(|v| v.as_str());

        match (kty, crv, protected_header.alg.as_str()) {
            #[cfg(feature = "crypto-ed25519")]
            (Some("OKP"), Some("Ed25519"), "EdDSA") => {
                // Extract the public key
                let public_key_base64 = self
                    .public_jwk
                    .get("x")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| {
                        Error::Cryptography("Missing public key (x) in JWK".to_string())
                    })?;

                // Decode the public key from base64
                let public_key_bytes = base64::engine::general_purpose::STANDARD
                    .decode(public_key_base64)
                    .map_err(|e| {
                        Error::Cryptography(format!("Failed to decode public key: {}", e))
                    })?;

                // Ed25519 public keys must be exactly 32 bytes
                if public_key_bytes.len() != 32 {
                    return Err(Error::Cryptography(format!(
                        "Invalid Ed25519 public key length: {}, expected 32 bytes",
                        public_key_bytes.len()
                    )));
                }

                // Create an Ed25519 verifying key
                let verifying_key = match VerifyingKey::try_from(public_key_bytes.as_slice()) {
                    Ok(key) => key,
                    Err(e) => {
                        return Err(Error::Cryptography(format!(
                            "Failed to create Ed25519 verifying key: {:?}",
                            e
                        )))
                    }
                };

                // Verify the signature
                if signature.len() != 64 {
                    return Err(Error::Cryptography(format!(
                        "Invalid Ed25519 signature length: {}, expected 64 bytes",
                        signature.len()
                    )));
                }

                let mut sig_bytes = [0u8; 64];
                sig_bytes.copy_from_slice(signature);
                let ed_signature = ed25519_dalek::Signature::from_bytes(&sig_bytes);

                match verifying_key.verify(payload, &ed_signature) {
                    Ok(()) => Ok(true),
                    Err(_) => Ok(false),
                }
            }
            #[cfg(feature = "crypto-p256")]
            (Some("EC"), Some("P-256"), "ES256") => {
                // Extract the public key coordinates
                let x_b64 = self
                    .public_jwk
                    .get("x")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| {
                        Error::Cryptography("Missing x coordinate in JWK".to_string())
                    })?;
                let y_b64 = self
                    .public_jwk
                    .get("y")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| {
                        Error::Cryptography("Missing y coordinate in JWK".to_string())
                    })?;

                // Decode the coordinates
                let x_bytes = base64::engine::general_purpose::STANDARD
                    .decode(x_b64)
                    .map_err(|e| {
                        Error::Cryptography(format!("Failed to decode x coordinate: {}", e))
                    })?;
                let y_bytes = base64::engine::general_purpose::STANDARD
                    .decode(y_b64)
                    .map_err(|e| {
                        Error::Cryptography(format!("Failed to decode y coordinate: {}", e))
                    })?;

                // Create a P-256 encoded point from the coordinates
                let mut point_bytes = vec![0x04]; // Uncompressed point format
                point_bytes.extend_from_slice(&x_bytes);
                point_bytes.extend_from_slice(&y_bytes);

                let encoded_point = P256EncodedPoint::from_bytes(&point_bytes).map_err(|e| {
                    Error::Cryptography(format!("Failed to create P-256 encoded point: {}", e))
                })?;

                // This checks if the point is on the curve and returns the public key
                let public_key_opt = P256PublicKey::from_encoded_point(&encoded_point);
                if public_key_opt.is_none().into() {
                    return Err(Error::Cryptography("Invalid P-256 public key".to_string()));
                }
                let public_key = public_key_opt.unwrap();

                // Parse the signature from DER format
                let p256_signature = P256Signature::from_der(signature).map_err(|e| {
                    Error::Cryptography(format!("Failed to parse P-256 signature: {:?}", e))
                })?;

                // Verify the signature using P-256 ECDSA
                let verifier = p256::ecdsa::VerifyingKey::from(public_key);
                match verifier.verify(payload, &p256_signature) {
                    Ok(()) => Ok(true),
                    Err(_) => Ok(false),
                }
            }
            #[cfg(feature = "crypto-secp256k1")]
            (Some("EC"), Some("secp256k1"), "ES256K") => {
                // Extract the public key coordinates
                let x_b64 = self
                    .public_jwk
                    .get("x")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| {
                        Error::Cryptography("Missing x coordinate in JWK".to_string())
                    })?;
                let y_b64 = self
                    .public_jwk
                    .get("y")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| {
                        Error::Cryptography("Missing y coordinate in JWK".to_string())
                    })?;

                // Decode the coordinates
                let x_bytes = base64::engine::general_purpose::STANDARD
                    .decode(x_b64)
                    .map_err(|e| {
                        Error::Cryptography(format!("Failed to decode x coordinate: {}", e))
                    })?;
                let y_bytes = base64::engine::general_purpose::STANDARD
                    .decode(y_b64)
                    .map_err(|e| {
                        Error::Cryptography(format!("Failed to decode y coordinate: {}", e))
                    })?;

                // Create a secp256k1 public key from the coordinates
                let mut point_bytes = vec![0x04]; // Uncompressed point format
                point_bytes.extend_from_slice(&x_bytes);
                point_bytes.extend_from_slice(&y_bytes);

                // Parse the verifying key from the SEC1 encoded point
                let verifier =
                    k256::ecdsa::VerifyingKey::from_sec1_bytes(&point_bytes).map_err(|e| {
                        Error::Cryptography(format!(
                            "Failed to create secp256k1 verifying key: {:?}",
                            e
                        ))
                    })?;

                // Parse the signature from DER format
                let k256_signature = Secp256k1Signature::from_der(signature).map_err(|e| {
                    Error::Cryptography(format!("Failed to parse secp256k1 signature: {:?}", e))
                })?;

                // Verify the signature
                match verifier.verify(payload, &k256_signature) {
                    Ok(()) => Ok(true),
                    Err(_) => Ok(false),
                }
            }
            // Unsupported algorithm or key type combination
            _ => Err(Error::Cryptography(format!(
                "Unsupported key type/algorithm combination for verification: kty={:?}, crv={:?}, alg={}",
                kty, crv, protected_header.alg
            ))),
        }
    }
}