1
0

wolfCrypt-Test.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. /* wolfCrypt-Test.cs
  2. *
  3. * Copyright (C) 2006-2024 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. /* Tests for the wolfCrypt C# wrapper */
  22. using System;
  23. using System.Linq;
  24. using System.Text;
  25. using System.Security.Cryptography;
  26. using wolfSSL.CSharp;
  27. using System.Runtime.InteropServices;
  28. using static wolfSSL.CSharp.wolfcrypt;
  29. public class wolfCrypt_Test_CSharp
  30. {
  31. private static void random_test()
  32. {
  33. int ret, i, zeroCount = 0;
  34. Byte[] data = new Byte[128];
  35. Console.WriteLine("Starting RNG test");
  36. /* Random Test */
  37. ret = wolfcrypt.Random(data, data.Length);
  38. if (ret == 0)
  39. {
  40. /* Check for 0's */
  41. for (i = 0; i < (int)data.Length; i++)
  42. {
  43. if (data[i] == 0)
  44. {
  45. zeroCount++;
  46. }
  47. }
  48. if (zeroCount == data.Length)
  49. {
  50. Console.WriteLine("RNG zero check error");
  51. }
  52. else
  53. {
  54. Console.WriteLine("RNG Test Passed");
  55. }
  56. }
  57. else
  58. {
  59. Console.WriteLine("RNG Error" + wolfcrypt.GetError(ret));
  60. }
  61. } /* END random_test */
  62. private static void ecc_test(string hashAlgorithm, int keySize)
  63. {
  64. int ret;
  65. IntPtr rng = IntPtr.Zero;
  66. IntPtr PrivKey = IntPtr.Zero;
  67. IntPtr PubKey = IntPtr.Zero;
  68. IntPtr key = IntPtr.Zero;
  69. Console.WriteLine("\nStarting ECC" + (keySize*8) + " test for " + hashAlgorithm + "...");
  70. /* Create a new RNG context */
  71. rng = wolfcrypt.RandomNew();
  72. if (rng == IntPtr.Zero)
  73. {
  74. throw new Exception("RNG initialization failed.");
  75. }
  76. /* Generate ECC Key Pair */
  77. Console.WriteLine("Testing ECC Key Generation...");
  78. key = wolfcrypt.EccMakeKey(keySize, rng);
  79. if (key == IntPtr.Zero)
  80. {
  81. throw new Exception("EccMakeKey failed");
  82. }
  83. Console.WriteLine("ECC Key Generation test passed.");
  84. /* Export and Import Key */
  85. Console.WriteLine("Testing ECC Key Export and Import...");
  86. byte[] privateKeyDer;
  87. ret = wolfcrypt.EccExportPrivateKeyToDer(key, out privateKeyDer);
  88. if (ret < 0) {
  89. throw new Exception("ExportPrivateKeyToDer failed");
  90. }
  91. byte[] publicKeyDer;
  92. ret = wolfcrypt.EccExportPublicKeyToDer(key, out publicKeyDer, true);
  93. if (ret < 0) {
  94. throw new Exception("ExportPublicKeyToDer failed");
  95. }
  96. PrivKey = wolfcrypt.EccImportKey(privateKeyDer);
  97. if (PrivKey == IntPtr.Zero)
  98. {
  99. throw new Exception("EccImportKey Private failed");
  100. }
  101. PubKey = wolfcrypt.EccImportPublicKeyFromDer(publicKeyDer);
  102. if (PubKey == IntPtr.Zero)
  103. {
  104. throw new Exception("ImportPublicKeyFromDer Public failed");
  105. }
  106. Console.WriteLine("ECC Key Export and Import test passed.");
  107. /* Generate hash based on selected algorithm */
  108. byte[] dataToHash = System.Text.Encoding.UTF8.GetBytes("This is some data to hash");
  109. byte[] hash;
  110. switch (hashAlgorithm.ToUpper())
  111. {
  112. case "SHA256":
  113. using (SHA256 sha256 = SHA256.Create())
  114. {
  115. hash = sha256.ComputeHash(dataToHash);
  116. }
  117. break;
  118. case "SHA384":
  119. using (SHA384 sha384 = SHA384.Create())
  120. {
  121. hash = sha384.ComputeHash(dataToHash);
  122. }
  123. break;
  124. case "SHA512":
  125. using (SHA512 sha512 = SHA512.Create())
  126. {
  127. hash = sha512.ComputeHash(dataToHash);
  128. }
  129. break;
  130. default:
  131. throw new Exception("Unsupported hash algorithm");
  132. }
  133. Console.WriteLine($"{hashAlgorithm} hash generated.");
  134. /* Sign Data */
  135. Console.WriteLine("Testing ECC Signature Creation...");
  136. byte[] signature = new byte[wolfcrypt.ECC_MAX_SIG_SIZE];
  137. int signLength = wolfcrypt.EccSign(PrivKey, hash, signature);
  138. if (signLength <= 0)
  139. {
  140. throw new Exception("EccSign failed");
  141. }
  142. byte[] actualSignature = new byte[signLength];
  143. Array.Copy(signature, 0, actualSignature, 0, signLength);
  144. Console.WriteLine($"ECC Signature Creation test passed. Signature Length: {signLength}");
  145. /* Verify Signature */
  146. Console.WriteLine("Testing ECC Signature Verification...");
  147. int verifyResult = wolfcrypt.EccVerify(PubKey, actualSignature, hash);
  148. if (verifyResult != 0)
  149. {
  150. throw new Exception("EccVerify failed");
  151. }
  152. Console.WriteLine("ECC Signature Verification test passed.");
  153. /* Cleanup */
  154. if (key != IntPtr.Zero) wolfcrypt.EccFreeKey(key);
  155. if (PubKey != IntPtr.Zero) wolfcrypt.EccFreeKey(PubKey);
  156. if (PrivKey != IntPtr.Zero) wolfcrypt.EccFreeKey(PrivKey);
  157. if (rng != IntPtr.Zero) wolfcrypt.RandomFree(rng);
  158. } /* END ecc_test */
  159. private static void ecies_test(int keySize)
  160. {
  161. /* maximum encrypted message:
  162. * msgSz (14) + pad (2) + pubKeySz(1+66*2) + ivSz(16) + digestSz(32) = 197 */
  163. int bufferSize = wolfcrypt.MAX_ECIES_TEST_SZ;
  164. const string message = "Hello wolfSSL!";
  165. byte[] salt = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
  166. IntPtr a = IntPtr.Zero;
  167. IntPtr b = IntPtr.Zero;
  168. IntPtr aCtx = IntPtr.Zero;
  169. IntPtr bCtx = IntPtr.Zero;
  170. IntPtr rng = IntPtr.Zero;
  171. IntPtr heap = IntPtr.Zero;
  172. byte[] plaintext = new byte[bufferSize];
  173. byte[] encrypted = new byte[bufferSize];
  174. byte[] decrypted = new byte[bufferSize];
  175. try
  176. {
  177. Console.WriteLine($"\nStarting ECIES test for {keySize} byte key size...");
  178. /* Create a new RNG context */
  179. rng = wolfcrypt.RandomNew();
  180. if (rng == IntPtr.Zero)
  181. {
  182. throw new Exception("RNG initialization failed.");
  183. }
  184. /* Initialize keys */
  185. a = wolfcrypt.EccMakeKey(keySize, rng);
  186. b = wolfcrypt.EccMakeKey(keySize, rng);
  187. if (a == IntPtr.Zero || b == IntPtr.Zero)
  188. {
  189. throw new Exception("Key generation failed.");
  190. }
  191. Console.WriteLine("ECC key generation passed.");
  192. /* Create ECIES contexts for encryption and decryption */
  193. aCtx = wolfcrypt.EciesNewCtx((int)wolfcrypt.ecFlags.REQ_RESP_CLIENT, rng, heap);
  194. bCtx = wolfcrypt.EciesNewCtx((int)wolfcrypt.ecFlags.REQ_RESP_SERVER, rng, heap);
  195. if (aCtx == IntPtr.Zero || bCtx == IntPtr.Zero)
  196. {
  197. throw new Exception("Context creation failed.");
  198. }
  199. Console.WriteLine("ECC context creation passed.");
  200. /* Set KDF salt */
  201. if (wolfcrypt.EciesSetKdfSalt(aCtx, salt) != 0 ||
  202. wolfcrypt.EciesSetKdfSalt(bCtx, salt) != 0)
  203. {
  204. throw new Exception("Failed to set KDF salt.");
  205. }
  206. Console.WriteLine("KDF salt setup passed.");
  207. /* Prepare plaintext */
  208. Array.Clear(plaintext, 0, plaintext.Length);
  209. Array.Copy(Encoding.ASCII.GetBytes(message), plaintext, message.Length);
  210. /* Pad to block size */
  211. int plaintextLen = ((message.Length + (wolfcrypt.AES_BLOCK_SIZE - 1)) /
  212. wolfcrypt.AES_BLOCK_SIZE) * wolfcrypt.AES_BLOCK_SIZE;
  213. /* Encrypt message */
  214. int ret = wolfcrypt.EciesEncrypt(a, b, plaintext, (uint)plaintextLen, encrypted, aCtx);
  215. if (ret < 0)
  216. {
  217. throw new Exception("Encryption failed.");
  218. }
  219. int encryptedLen = ret;
  220. Console.WriteLine("ECC encryption passed.");
  221. /* Decrypt message */
  222. ret = wolfcrypt.EciesDecrypt(b, a, encrypted, (uint)encryptedLen, decrypted, bCtx);
  223. if (ret < 0)
  224. {
  225. throw new Exception("Decryption failed.");
  226. }
  227. int decryptedLen = ret;
  228. Console.WriteLine("ECC decryption passed.");
  229. /* Compare decrypted text to original plaintext */
  230. if (decryptedLen != plaintextLen || !wolfcrypt.ByteArrayVerify(plaintext, decrypted))
  231. {
  232. throw new Exception("Decrypted text does not match original plaintext.");
  233. }
  234. Console.WriteLine("Decrypted text matches original plaintext.");
  235. }
  236. finally
  237. {
  238. /* Cleanup key and context */
  239. if (a != IntPtr.Zero) wolfcrypt.EccFreeKey(a);
  240. if (b != IntPtr.Zero) wolfcrypt.EccFreeKey(b);
  241. if (aCtx != IntPtr.Zero) wolfcrypt.EciesFreeCtx(aCtx);
  242. if (bCtx != IntPtr.Zero) wolfcrypt.EciesFreeCtx(bCtx);
  243. if (rng != IntPtr.Zero) wolfcrypt.RandomFree(rng);
  244. }
  245. } /* END ecies_test */
  246. private static void ecdhe_test(int keySize)
  247. {
  248. int ret;
  249. IntPtr rng = IntPtr.Zero;
  250. IntPtr keyA = IntPtr.Zero;
  251. IntPtr keyB = IntPtr.Zero;
  252. IntPtr publicKeyA = IntPtr.Zero;
  253. IntPtr publicKeyB = IntPtr.Zero;
  254. byte[] derKey;
  255. Console.WriteLine("\nStarting ECDHE shared secret test for " + keySize + " key size...");
  256. /* Create RNG */
  257. Console.WriteLine("Generating RNG...");
  258. rng = RandomNew();
  259. if (rng == IntPtr.Zero)
  260. {
  261. throw new Exception("Failed to generate RNG.");
  262. }
  263. Console.WriteLine("RNG generation test passed.");
  264. /* Generate Key Pair A */
  265. Console.WriteLine("Generating Key Pair A...");
  266. keyA = wolfcrypt.EccMakeKey(keySize, rng);
  267. if (keyA == IntPtr.Zero)
  268. {
  269. throw new Exception("Failed to generate key pair A.");
  270. }
  271. /* Generate Key Pair B */
  272. Console.WriteLine("Generating Key Pair B...");
  273. keyB = wolfcrypt.EccMakeKey(keySize, rng);
  274. if (keyB == IntPtr.Zero)
  275. {
  276. throw new Exception("Failed to generate key pair B.");
  277. }
  278. Console.WriteLine("ECC Key generation test passed.");
  279. /* Export Public Key B to DER format */
  280. Console.WriteLine("Exporting Public Key B to DER format...");
  281. ret = wolfcrypt.EccExportPublicKeyToDer(keyB, out derKey, true);
  282. if (ret < 0 || derKey == null)
  283. {
  284. throw new Exception("EccExportPublicKeyToDer failed");
  285. }
  286. /* Decode Public Key B from DER format */
  287. Console.WriteLine("Decoding Public Key B from DER format...");
  288. publicKeyB = wolfcrypt.EccImportPublicKeyFromDer(derKey);
  289. if (publicKeyB == IntPtr.Zero)
  290. {
  291. throw new Exception("Failed to decode public key B from DER format.");
  292. }
  293. Console.WriteLine("ECC Export and Import test passed.");
  294. /* Compute Shared Secret using Private Key A and Public Key B */
  295. Console.WriteLine("Computing Shared Secret using Private Key A and Public Key B...");
  296. byte[] sharedSecretA = new byte[keySize];
  297. int retA = wolfcrypt.EcdheSharedSecret(keyA, publicKeyB, sharedSecretA, rng);
  298. if (retA != 0)
  299. {
  300. throw new Exception("Failed to compute shared secret A. Error code: " + retA);
  301. }
  302. Console.WriteLine("ECC shared secret created using private Key A.");
  303. /* Export Public Key A to DER format */
  304. Console.WriteLine("Exporting Public Key A to DER format...");
  305. ret = wolfcrypt.EccExportPublicKeyToDer(keyA, out derKey, true);
  306. if (ret < 0 || derKey == null)
  307. {
  308. throw new Exception("EccExportPublicKeyToDer failed");
  309. }
  310. /* Decode Public Key A from DER format */
  311. Console.WriteLine("Decoding Public Key A from DER format...");
  312. publicKeyA = wolfcrypt.EccImportPublicKeyFromDer(derKey);
  313. if (publicKeyA == IntPtr.Zero)
  314. {
  315. throw new Exception("Failed to decode public key A from DER format.");
  316. }
  317. /* Compute Shared Secret using Private Key B and Public Key A */
  318. Console.WriteLine("Computing Shared Secret using Private Key B and Public Key A...");
  319. byte[] sharedSecretB = new byte[keySize];
  320. int retB = wolfcrypt.EcdheSharedSecret(keyB, publicKeyA, sharedSecretB, rng);
  321. if (retB != 0)
  322. {
  323. throw new Exception("Failed to compute shared secret B. Error code: " + retB);
  324. }
  325. Console.WriteLine("ECC shared secret created using private Key B.");
  326. /* Compare Shared Secrets */
  327. Console.WriteLine("Comparing Shared Secrets...");
  328. if (!wolfcrypt.ByteArrayVerify(sharedSecretA, sharedSecretB))
  329. {
  330. throw new Exception("Shared secrets do not match.");
  331. }
  332. else
  333. {
  334. Console.WriteLine("ECC shared secret match.");
  335. }
  336. /* Cleanup */
  337. if (keyA != IntPtr.Zero) wolfcrypt.EccFreeKey(keyA);
  338. if (keyB != IntPtr.Zero) wolfcrypt.EccFreeKey(keyB);
  339. if (publicKeyA != IntPtr.Zero) wolfcrypt.EccFreeKey(publicKeyA);
  340. if (publicKeyB != IntPtr.Zero) wolfcrypt.EccFreeKey(publicKeyB);
  341. if (rng != IntPtr.Zero) wolfcrypt.RandomFree(rng);
  342. } /* END ecdhe_test */
  343. private static void rsa_test(string hashAlgorithm, int keySize)
  344. {
  345. IntPtr key = IntPtr.Zero;
  346. IntPtr heap = IntPtr.Zero;
  347. int devId = wolfcrypt.INVALID_DEVID;
  348. Console.WriteLine("\nStarting RSA" + keySize + " test for " + hashAlgorithm + "...");
  349. /* Generate RSA Key Pair */
  350. Console.WriteLine("Testing RSA Key Generation...");
  351. key = wolfcrypt.RsaMakeKey(heap, devId, keySize);
  352. if (key == IntPtr.Zero)
  353. {
  354. throw new Exception("RsaMakeKey failed");
  355. }
  356. Console.WriteLine("RSA Key Generation test passed.");
  357. /* Generate hash based on selected algorithm */
  358. byte[] dataToHash = System.Text.Encoding.UTF8.GetBytes("This is some data to hash");
  359. byte[] hash;
  360. switch (hashAlgorithm.ToUpper())
  361. {
  362. case "SHA256":
  363. using (SHA256 sha256 = SHA256.Create())
  364. {
  365. hash = sha256.ComputeHash(dataToHash);
  366. }
  367. break;
  368. case "SHA384":
  369. using (SHA384 sha384 = SHA384.Create())
  370. {
  371. hash = sha384.ComputeHash(dataToHash);
  372. }
  373. break;
  374. case "SHA512":
  375. using (SHA512 sha512 = SHA512.Create())
  376. {
  377. hash = sha512.ComputeHash(dataToHash);
  378. }
  379. break;
  380. default:
  381. throw new Exception("Unsupported hash algorithm");
  382. }
  383. Console.WriteLine($"{hashAlgorithm} hash generated.");
  384. /* Sign Data */
  385. Console.WriteLine("Testing RSA Signature Creation...");
  386. byte[] signature = new byte[keySize / 8];
  387. int signLength = wolfcrypt.RsaSignSSL(key, hash, signature);
  388. if (signLength <= 0)
  389. {
  390. throw new Exception("RsaSignSSL failed");
  391. }
  392. byte[] actualSignature = new byte[signLength];
  393. Array.Copy(signature, 0, actualSignature, 0, signLength);
  394. Console.WriteLine($"RSA Signature Creation test passed. Signature Length: {signLength}");
  395. /* Verify Signature */
  396. Console.WriteLine("Testing RSA Signature Verification...");
  397. int verifyResult = wolfcrypt.RsaVerifySSL(key, actualSignature, hash);
  398. if (verifyResult != 0)
  399. {
  400. throw new Exception("RsaVerifySSL failed");
  401. }
  402. Console.WriteLine("RSA Signature Verification test passed.");
  403. /* Cleanup */
  404. if (key != IntPtr.Zero) wolfcrypt.RsaFreeKey(key);
  405. } /* END rsa_test */
  406. private static void ed25519_test()
  407. {
  408. int ret;
  409. IntPtr key = IntPtr.Zero;
  410. byte[] privKey;
  411. byte[] pubKey;
  412. Console.WriteLine("\nStarting ED25519 tests...");
  413. IntPtr heap = IntPtr.Zero;
  414. int devId = wolfcrypt.INVALID_DEVID;
  415. /* Generate ED25519 Key Pair */
  416. Console.WriteLine("Testing ED25519 Key Generation...");
  417. key = wolfcrypt.Ed25519MakeKey(heap, devId);
  418. if (key == IntPtr.Zero)
  419. {
  420. throw new Exception("Ed25519MakeKey failed");
  421. }
  422. Console.WriteLine("ED25519 Key Generation test passed.");
  423. /* Export and Import Key */
  424. Console.WriteLine("Testing ED25519 Key Export and Import...");
  425. /* Export Private */
  426. ret = wolfcrypt.Ed25519ExportKeyToDer(key, out privKey);
  427. if (ret < 0 || privKey == null)
  428. {
  429. throw new Exception("Ed25519ExportKeyToDer failed");
  430. }
  431. /* Export Public */
  432. ret = wolfcrypt.Ed25519ExportPublicKeyToDer(key, out pubKey, true);
  433. if (ret < 0 || pubKey == null)
  434. {
  435. throw new Exception("Ed25519ExportKeyToDer failed");
  436. }
  437. /* Import Private */
  438. IntPtr importedPrivKey = wolfcrypt.Ed25519PrivateKeyDecode(privKey);
  439. if (importedPrivKey == IntPtr.Zero)
  440. {
  441. throw new Exception("Ed25519PrivateKeyDecode failed");
  442. }
  443. /* Import Public */
  444. IntPtr importedPubKey = wolfcrypt.Ed25519PublicKeyDecode(pubKey);
  445. if (importedPubKey == IntPtr.Zero)
  446. {
  447. throw new Exception("Ed25519PublicKeyDecode failed");
  448. }
  449. Console.WriteLine("ED25519 Key Export and Import test passed.");
  450. /* Generate a hash */
  451. byte[] dataToHash = System.Text.Encoding.UTF8.GetBytes("This is some data to hash");
  452. /* Sign Data */
  453. Console.WriteLine("Testing ED25519 Signature Creation...");
  454. byte[] signature;
  455. ret = wolfcrypt.Ed25519SignMsg(dataToHash, out signature, key);
  456. if (ret != 0)
  457. {
  458. throw new Exception("Ed25519SignMsg failed");
  459. }
  460. Console.WriteLine($"ED25519 Signature Creation test passed. Signature Length: {signature.Length}");
  461. /* Verify Signature */
  462. Console.WriteLine("Testing ED25519 Signature Verification...");
  463. ret = wolfcrypt.Ed25519VerifyMsg(signature, dataToHash, key);
  464. if (ret != 0)
  465. {
  466. throw new Exception("Ed25519VerifyMsg failed");
  467. }
  468. Console.WriteLine("ED25519 Signature Verification test passed.");
  469. /* Cleanup */
  470. if (key != IntPtr.Zero) wolfcrypt.Ed25519FreeKey(key);
  471. } /* END ed25519_test */
  472. private static void curve25519_test()
  473. {
  474. int ret;
  475. IntPtr keyA = IntPtr.Zero;
  476. IntPtr keyB = IntPtr.Zero;
  477. IntPtr publicKeyA = IntPtr.Zero;
  478. IntPtr publicKeyB = IntPtr.Zero;
  479. byte[] derKey;
  480. Console.WriteLine("\nStarting Curve25519 shared secret test...");
  481. /* Generate Key Pair A */
  482. Console.WriteLine("Generating Key Pair A...");
  483. keyA = wolfcrypt.Curve25519MakeKey(IntPtr.Zero, 0);
  484. if (keyA == IntPtr.Zero)
  485. {
  486. throw new Exception("Failed to generate key pair A.");
  487. }
  488. /* Generate Key Pair B */
  489. Console.WriteLine("Generating Key Pair B...");
  490. keyB = wolfcrypt.Curve25519MakeKey(IntPtr.Zero, 0);
  491. if (keyB == IntPtr.Zero)
  492. {
  493. throw new Exception("Failed to generate key pair B.");
  494. }
  495. Console.WriteLine("Curve25519 Key generation test passed.");
  496. /* Export Public Key B to DER format */
  497. Console.WriteLine("Exporting Public Key B to DER format...");
  498. ret = wolfcrypt.Curve25519ExportPublicKeyToDer(keyB, out derKey, true);
  499. if (ret < 0 || derKey == null)
  500. {
  501. throw new Exception("Curve25519ExportPublicKeyToDer failed");
  502. }
  503. /* Decode Public Key B from DER format */
  504. Console.WriteLine("Decoding Public Key B from DER format...");
  505. publicKeyB = wolfcrypt.Curve25519PublicKeyDecode(derKey);
  506. if (publicKeyB == IntPtr.Zero)
  507. {
  508. throw new Exception("Failed to decode public key B from DER format.");
  509. }
  510. Console.WriteLine("Curve25519 Export and Import test passed.");
  511. /* Compute Shared Secret using Private Key A and Public Key B */
  512. Console.WriteLine("Computing Shared Secret using Private Key A and Public Key B...");
  513. byte[] sharedSecretA = new byte[wolfcrypt.ED25519_KEY_SIZE];
  514. int retA = wolfcrypt.Curve25519SharedSecret(keyA, publicKeyB, sharedSecretA);
  515. if (retA != 0)
  516. {
  517. throw new Exception("Failed to compute shared secret A. Error code: " + retA);
  518. }
  519. Console.WriteLine("Curve25519 shared secret created using private Key A.");
  520. /* Export Public Key A to DER format */
  521. Console.WriteLine("Exporting Public Key A to DER format...");
  522. ret = wolfcrypt.Curve25519ExportPublicKeyToDer(keyA, out derKey, true);
  523. if (ret < 0 || derKey == null)
  524. {
  525. throw new Exception("Curve25519ExportPublicKeyToDer failed");
  526. }
  527. /* Decode Public Key A from DER format */
  528. Console.WriteLine("Decoding Public Key A from DER format...");
  529. publicKeyA = wolfcrypt.Curve25519PublicKeyDecode(derKey);
  530. if (publicKeyA == IntPtr.Zero)
  531. {
  532. throw new Exception("Failed to decode public key A from DER format.");
  533. }
  534. /* Compute Shared Secret using Private Key B and Public Key A */
  535. Console.WriteLine("Computing Shared Secret using Private Key B and Public Key A...");
  536. byte[] sharedSecretB = new byte[wolfcrypt.ED25519_KEY_SIZE];
  537. int retB = wolfcrypt.Curve25519SharedSecret(keyB, publicKeyA, sharedSecretB);
  538. if (retB != 0)
  539. {
  540. throw new Exception("Failed to compute shared secret B. Error code: " + retB);
  541. }
  542. Console.WriteLine("Curve25519 shared secret created using private Key B.");
  543. /* Compare Shared Secrets */
  544. Console.WriteLine("Comparing Shared Secrets...");
  545. if (!wolfcrypt.ByteArrayVerify(sharedSecretA, sharedSecretB))
  546. {
  547. throw new Exception("Shared secrets do not match.");
  548. }
  549. else
  550. {
  551. Console.WriteLine("Curve25519 shared secret match.");
  552. }
  553. /* Cleanup */
  554. if (keyA != IntPtr.Zero) wolfcrypt.Curve25519FreeKey(keyA);
  555. if (keyB != IntPtr.Zero) wolfcrypt.Curve25519FreeKey(keyB);
  556. if (publicKeyA != IntPtr.Zero) wolfcrypt.Curve25519FreeKey(publicKeyA);
  557. if (publicKeyB != IntPtr.Zero) wolfcrypt.Curve25519FreeKey(publicKeyB);
  558. } /* END curve25519_test */
  559. private static void aes_gcm_test()
  560. {
  561. IntPtr aes = IntPtr.Zero;
  562. byte[] key;
  563. byte[] iv;
  564. byte[] plaintext;
  565. byte[] ciphertext;
  566. byte[] addAuth;
  567. byte[] authTag;
  568. byte[] decrypted;
  569. int ret;
  570. try
  571. {
  572. Console.WriteLine("\nStarting AES-GCM tests...");
  573. IntPtr heap = IntPtr.Zero;
  574. int devId = wolfcrypt.INVALID_DEVID;
  575. /* Initialize AES-GCM Context */
  576. Console.WriteLine("Testing AES-GCM Initialization...");
  577. /*
  578. * This is from the Test Case 16 from the document Galois/
  579. * Counter Mode of Operation (GCM) by McGrew and
  580. * Viega.
  581. */
  582. key = new byte[32]
  583. {
  584. 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,
  585. 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08,
  586. 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,
  587. 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08
  588. };
  589. iv = new byte[12]
  590. {
  591. 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad,
  592. 0xde, 0xca, 0xf8, 0x88
  593. };
  594. plaintext = new byte[]
  595. {
  596. 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5,
  597. 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a,
  598. 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda,
  599. 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72,
  600. 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53,
  601. 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25,
  602. 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57,
  603. 0xba, 0x63, 0x7b, 0x39
  604. };
  605. ciphertext = new byte[]
  606. {
  607. 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07,
  608. 0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d,
  609. 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9,
  610. 0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa,
  611. 0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d,
  612. 0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38,
  613. 0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a,
  614. 0xbc, 0xc9, 0xf6, 0x62
  615. };
  616. addAuth = new byte[]
  617. {
  618. 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef,
  619. 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef,
  620. 0xab, 0xad, 0xda, 0xd2
  621. };
  622. authTag = new byte[16];
  623. aes = wolfcrypt.AesNew(heap, devId);
  624. if (aes == IntPtr.Zero)
  625. {
  626. throw new Exception($"AesNew failed with error code {aes}");
  627. }
  628. Console.WriteLine("AesNew test passed.");
  629. /* Set AES-GCM Key */
  630. Console.WriteLine("Testing AES-GCM Key Setting...");
  631. uint len = (uint)key.Length;
  632. ret = wolfcrypt.AesGcmSetKey(aes, key);
  633. if (ret != 0)
  634. {
  635. throw new Exception($"AesGcmSetKey failed with error code {ret}");
  636. }
  637. Console.WriteLine("AES-GCM Key Setting test passed.");
  638. /* Encryption */
  639. Console.WriteLine("Testing AES-GCM Encryption...");
  640. ret = wolfcrypt.AesGcmEncrypt(aes, iv, plaintext, ciphertext, authTag, addAuth);
  641. if (ret != 0)
  642. {
  643. throw new Exception($"AesGcmEncrypt failed with error code {ret}");
  644. }
  645. Console.WriteLine($"AES-GCM Encryption test passed. Ciphertext Length: {ciphertext.Length}");
  646. /* Decryption */
  647. Console.WriteLine("Testing AES-GCM Decryption...");
  648. decrypted = new byte[plaintext.Length];
  649. ret = wolfcrypt.AesGcmDecrypt(aes, iv, ciphertext, decrypted, authTag, addAuth);
  650. if (ret != 0)
  651. {
  652. throw new Exception($"AesGcmDecrypt failed with error code {ret}");
  653. }
  654. /* Verify Decryption */
  655. if (!plaintext.SequenceEqual(decrypted))
  656. {
  657. throw new Exception("Decryption failed: decrypted data does not match original plaintext.");
  658. }
  659. Console.WriteLine("AES-GCM Decryption test passed.");
  660. }
  661. catch (Exception ex)
  662. {
  663. Console.WriteLine($"AES-GCM test failed: {ex.Message}");
  664. }
  665. finally
  666. {
  667. /* Cleanup */
  668. if (aes != IntPtr.Zero)
  669. {
  670. wolfcrypt.AesGcmFree(aes);
  671. }
  672. }
  673. } /* END aes_gcm_test */
  674. private static void hash_test(uint hashType)
  675. {
  676. IntPtr hash = IntPtr.Zero;
  677. IntPtr heap = IntPtr.Zero;
  678. int devId = wolfcrypt.INVALID_DEVID;
  679. /* Get the enum name */
  680. string hashTypeName = Enum.GetName(typeof(wolfcrypt.hashType), hashType);
  681. Console.WriteLine($"\nStarting hash test for {hashTypeName}...");
  682. /* Allocate new hash context */
  683. Console.WriteLine("Testing hash context allocation...");
  684. hash = wolfcrypt.HashNew(hashType, heap, devId);
  685. if (hash == IntPtr.Zero)
  686. {
  687. Console.WriteLine($"HashNew failed for {hashTypeName}");
  688. return;
  689. }
  690. Console.WriteLine("Hash context allocation test passed.");
  691. /* Initialize the hash context with the specified hash type */
  692. Console.WriteLine("Testing hash initialization...");
  693. int initResult = wolfcrypt.InitHash(hash, hashType);
  694. if (initResult != 0)
  695. {
  696. Console.WriteLine($"InitHash failed for {hashTypeName}");
  697. wolfcrypt.HashFree(hash, hashType);
  698. return;
  699. }
  700. Console.WriteLine("Hash initialization test passed.");
  701. /* Update the hash with data */
  702. byte[] dataToHash = Encoding.UTF8.GetBytes("This is some data to hash");
  703. Console.WriteLine("Testing hash update...");
  704. int updateResult = wolfcrypt.HashUpdate(hash, hashType, dataToHash);
  705. if (updateResult != 0)
  706. {
  707. Console.WriteLine($"HashUpdate failed for {hashTypeName}");
  708. wolfcrypt.HashFree(hash, hashType);
  709. return;
  710. }
  711. Console.WriteLine("Hash update test passed.");
  712. /* Finalize the hash and get the result */
  713. Console.WriteLine("Testing hash finalization...");
  714. byte[] hashOutput;
  715. int finalResult = wolfcrypt.HashFinal(hash, hashType, out hashOutput);
  716. if (finalResult != 0)
  717. {
  718. Console.WriteLine($"HashFinal failed for {hashType}");
  719. wolfcrypt.HashFree(hash, hashType);
  720. return;
  721. }
  722. Console.WriteLine($"Hash finalization test passed for {hashTypeName}. Hash Length: {hashOutput.Length}");
  723. /* Output the hash result */
  724. Console.WriteLine($"Hash Output ({hashTypeName}): {BitConverter.ToString(hashOutput).Replace("-", "")}");
  725. /* Cleanup */
  726. Console.WriteLine("Testing hash cleanup...");
  727. int freeResult = wolfcrypt.HashFree(hash, hashType);
  728. if (freeResult != 0)
  729. {
  730. Console.WriteLine($"HashFree failed for {hashTypeName}");
  731. }
  732. else
  733. {
  734. Console.WriteLine("Hash cleanup test passed.");
  735. }
  736. } /* END hash_test */
  737. public static void standard_log(int lvl, StringBuilder msg)
  738. {
  739. Console.WriteLine(msg);
  740. }
  741. public static void Main(string[] args)
  742. {
  743. try
  744. {
  745. Console.WriteLine("Starting Cryptographic Tests...\n");
  746. wolfcrypt.Init();
  747. /* setup logging to stdout */
  748. wolfcrypt.SetLogging(standard_log);
  749. random_test();
  750. Console.WriteLine("\nStarting ECC tests");
  751. ecc_test("SHA256", 32); /* Uses SHA-256 (32 byte hash) */
  752. ecc_test("SHA384", 32); /* Uses SHA-384 (32 byte hash) */
  753. ecc_test("SHA512", 32); /* Uses SHA-512 (32 byte hash) */
  754. Console.WriteLine("\nStarting ECIES tests");
  755. ecies_test(32); /* ECIES test (32 byte key size) */
  756. ecies_test(48); /* ECIES test (48 byte key size) */
  757. ecies_test(66); /* ECIES test (66 byte key size) */
  758. Console.WriteLine("\nStarting ECDHE tests");
  759. ecdhe_test(32); /* ECDHE shared secret test (32 byte key size) */
  760. ecdhe_test(48); /* ECDHE shared secret test (48 byte key size) */
  761. ecdhe_test(66); /* ECDHE shared secret test (66 byte key size) */
  762. Console.WriteLine("\nStarting RSA tests");
  763. rsa_test("SHA256", 2048); /* Uses SHA-256 (2048 bit hash) */
  764. rsa_test("SHA384", 2048); /* Uses SHA-384 (2048 bit hash) */
  765. rsa_test("SHA512", 2048); /* Uses SHA-512 (2048 bit hash) */
  766. Console.WriteLine("\nStarting ED25519 test");
  767. ed25519_test(); /* ED25519 test */
  768. Console.WriteLine("\nStarting curve25519 test");
  769. curve25519_test(); /* curve25519 shared secret test */
  770. Console.WriteLine("\nStarting AES-GCM test");
  771. aes_gcm_test(); /* AES_GCM test */
  772. Console.WriteLine("\nStarting HASH tests");
  773. hash_test((uint)wolfcrypt.hashType.WC_HASH_TYPE_SHA256); /* SHA-256 HASH test */
  774. hash_test((uint)wolfcrypt.hashType.WC_HASH_TYPE_SHA384); /* SHA-384 HASH test */
  775. hash_test((uint)wolfcrypt.hashType.WC_HASH_TYPE_SHA512); /* SHA-512 HASH test */
  776. hash_test((uint)wolfcrypt.hashType.WC_HASH_TYPE_SHA3_256); /* SHA3_256 HASH test */
  777. wolfcrypt.Cleanup();
  778. Console.WriteLine("\nAll tests completed successfully");
  779. }
  780. catch (Exception ex)
  781. {
  782. Console.WriteLine($"An error occurred: {ex.Message}");
  783. Environment.Exit(-1);
  784. }
  785. }
  786. }