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 2.9KB

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