The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PGP.cs 3.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using Org.BouncyCastle.Bcpg.OpenPgp;
  2. using Org.BouncyCastle.Utilities.Encoders;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace Teknik.Utilities.Cryptography
  10. {
  11. public static class PGP
  12. {
  13. public static bool IsPublicKey(string key)
  14. {
  15. bool isValid = false;
  16. try
  17. {
  18. byte[] byteArray = Encoding.ASCII.GetBytes(key);
  19. using (MemoryStream stream = new MemoryStream(byteArray))
  20. {
  21. using (Stream decoderStream = PgpUtilities.GetDecoderStream(stream))
  22. {
  23. PgpPublicKeyRingBundle publicKeyBundle = new PgpPublicKeyRingBundle(decoderStream);
  24. PgpPublicKey foundKey = GetFirstPublicKey(publicKeyBundle);
  25. if (foundKey != null)
  26. {
  27. isValid = true;
  28. }
  29. }
  30. }
  31. }
  32. catch (Exception ex)
  33. {
  34. isValid = false;
  35. }
  36. return isValid;
  37. }
  38. public static string GetFingerprint(string key)
  39. {
  40. string hexString = string.Empty;
  41. byte[] byteArray = Encoding.ASCII.GetBytes(key);
  42. using (MemoryStream stream = new MemoryStream(byteArray))
  43. {
  44. using (Stream decoderStream = PgpUtilities.GetDecoderStream(stream))
  45. {
  46. PgpPublicKeyRingBundle publicKeyBundle = new PgpPublicKeyRingBundle(decoderStream);
  47. PgpPublicKey foundKey = GetFirstPublicKey(publicKeyBundle);
  48. if (foundKey != null)
  49. {
  50. byte[] fing = foundKey.GetFingerprint();
  51. hexString = Hex.ToHexString(fing);
  52. }
  53. }
  54. }
  55. return hexString;
  56. }
  57. public static string GetFingerprint64(string key)
  58. {
  59. string fingerprint = GetFingerprint(key);
  60. if (fingerprint.Length > 16)
  61. fingerprint = fingerprint.Substring(fingerprint.Length - 16);
  62. return fingerprint;
  63. }
  64. private static PgpPublicKey GetFirstPublicKey(PgpPublicKeyRingBundle publicKeyRingBundle)
  65. {
  66. foreach (PgpPublicKeyRing kRing in publicKeyRingBundle.GetKeyRings())
  67. {
  68. var keys = kRing.GetPublicKeys();
  69. foreach (var key in keys)
  70. {
  71. PgpPublicKey foundKey = (PgpPublicKey)key;
  72. //PgpPublicKey key = kRing.GetPublicKeys()
  73. //.Cast<PgpPublicKey>()
  74. // .Where(k => k.IsEncryptionKey)
  75. // .FirstOrDefault();
  76. if (foundKey != null && foundKey.IsEncryptionKey)
  77. return foundKey;
  78. }
  79. }
  80. return null;
  81. }
  82. }
  83. }