public RetrievePgpKeys(string privateKeyEmail, bool toEncrypt, KeyStoreDB keyStoreDb) { if (string.IsNullOrEmpty(privateKeyEmail)) { throw new ArgumentNullException("privateKeyName"); } KeyUsers keySecUser = keyStoreDb.KeyUsers.Where(u => u.Email == privateKeyEmail).FirstOrDefault(); SecretKey = ReadSecretKey(keySecUser.KeyStoreID, keyStoreDb, toEncrypt); }
public async Task ImportKey(string keyId, KeyStoreDB keyStoreDb) { ImportKey impKey = new ImportKey(); string resp = await client.GetStringAsync(string.Format(srchString, keyId)); if (!string.IsNullOrEmpty(resp)) { string tmpFileName = Guid.NewGuid().ToString() + ".tmp"; string tmpPath = Path.GetTempPath().ToString(); File.WriteAllText(Path.Combine(tmpPath, tmpFileName), resp); int cnt = impKey.ImportPublicKey(tmpFileName, tmpPath, keyStoreDb); File.Delete(Path.Combine(tmpPath, tmpFileName)); } }
public static bool Update(KeyStoreDB keyStoreDb, long keyId, string trust) { if (keyStoreDb == null) { throw new ArgumentNullException("keyStoreDb"); } if (keyId == 0) { throw new ArgumentOutOfRangeException("keyId"); } if (string.IsNullOrEmpty(trust)) { throw new ArgumentNullException("trust"); } KeyStores updRow = keyStoreDb.KeyStores.Find(keyId); switch (updRow.KeyType) { case "Public": if (pubKeyLevels.Contains(trust.ToLower())) { updRow.OwnerTrust = trust; } else { updRow.OwnerTrust = string.Empty; } break; case "Secret": if (secKeyLevel.Equals(trust.ToLower())) { updRow.OwnerTrust = trust; } else { updRow.OwnerTrust = trust; } break; default: break; } keyStoreDb.SaveChanges(); return(true); }
private PgpPublicKey ReadPublicKey(long keyId, KeyStoreDB keyStoreDb) { string armouredKeyFile = keyStoreDb.KeyStores.Find(keyId).ArmouredKeyFile; using (Stream keyIn = new MemoryStream(Encoding.UTF8.GetBytes(armouredKeyFile))){ using (Stream inputStream = PgpUtilities.GetDecoderStream(keyIn)) { PgpPublicKeyRingBundle publicKeyRingBundle = new PgpPublicKeyRingBundle(inputStream); PgpPublicKey foundKey = GetFirstPublicKey(publicKeyRingBundle); if (foundKey != null) { return(foundKey); } } } throw new Exception("Unable to find encryption key in public key ring."); }
private PgpSecretKey ReadSecretKey(long keyId, KeyStoreDB keyStoreDb, bool toEncrypt) { string armouredKeyFile = keyStoreDb.KeyStores.Find(keyId).ArmouredKeyFile; using (Stream keyIn = new MemoryStream(Encoding.UTF8.GetBytes(armouredKeyFile))){ using (Stream inputStream = PgpUtilities.GetDecoderStream(keyIn)) { PgpSecretKeyRingBundle secretKeyRingBundle = new PgpSecretKeyRingBundle(inputStream); PgpSecretKey foundKey = toEncrypt ? GetFirstSecretKey(secretKeyRingBundle) : GetLastSecretKey(secretKeyRingBundle); if (foundKey != null) { return(foundKey); } } } throw new Exception("Unable to find signing key in key ring."); }
private bool RemovePublicKeyForSecretKey(long keyId, KeyStoreDB keyStoreDB) { KeyStores pubKeyDelete = keyStoreDB.KeyStores.Find(keyId); if (pubKeyDelete != null) { KeyUsers pubUserDelete = keyStoreDB.KeyUsers.Find(keyId); if (pubUserDelete != null) { keyStoreDB.KeyUsers.Remove(pubUserDelete); } keyStoreDB.KeyStores.Remove(pubKeyDelete); keyStoreDB.SaveChanges(); } return(true); }
// Gets the data from the database public RetrievePgpKeys(List <string> publicKeyEmails, string privateKeyEmail, char[] passPhrase, bool toEncrypt, KeyStoreDB keyStoreDb) { if (publicKeyEmails == null || publicKeyEmails.Count <= 0) { throw new ArgumentNullException("publicKeyName"); } if (string.IsNullOrEmpty(privateKeyEmail)) { throw new ArgumentNullException("privateKeyName"); } if (passPhrase == null || passPhrase.Count() <= 0) { throw new ArgumentNullException("passPhrase"); } PublicKeys = new List <PgpPublicKey>(); foreach (string publicKeyEmail in publicKeyEmails) { KeyUsers keyUser = keyStoreDb.KeyUsers.Where(u => u.Email == publicKeyEmail).FirstOrDefault(); if (keyUser != null) { PublicKeys.Add(ReadPublicKey(keyUser.KeyStoreID, keyStoreDb)); } } KeyUsers keySecUser = keyStoreDb.KeyUsers.Where(u => u.Email == privateKeyEmail).FirstOrDefault(); SecretKey = ReadSecretKey(keySecUser.KeyStoreID, keyStoreDb, toEncrypt); PrivateKey = ReadPrivateKey(passPhrase); }
public static void AddSignature(PgpPublicKey key, KeyStoreDB keyDb, string keyExportName, PgpSecretKey secKey, char[] passPhrase, SignatureOperation op, DateTime expiryDate, PgpSignature certLevel = null, string userId = "") { string fileData = string.Empty; bool useTemp = true; if (key == null) { throw new ArgumentNullException("key"); } if (keyDb == null) { throw new ArgumentNullException("keyDb"); } if (!Enum.IsDefined(typeof(SignatureOperation), op)) { throw new ArgumentOutOfRangeException(string.Format("op: {0}", op)); } AlgorithmAgreement algorithms = new AlgorithmAgreement(new List <PgpPublicKey>() { key }); PgpPrivateKey privateKey = secKey.ExtractPrivateKey(passPhrase); PgpSignatureGenerator sigGen = new PgpSignatureGenerator(key.Algorithm, algorithms.AgreedHashAlgorithm); switch (op) { case SignatureOperation.AddUserId: break; case SignatureOperation.RevokeKey: MemoryStream mStream = new MemoryStream(); using (ArmoredOutputStream outArmour = new ArmoredOutputStream(mStream)) { outArmour.SetHeader("Version", "Lynx Privacy"); sigGen.InitSign(PgpSignature.KeyRevocation, privateKey); PgpSignature sig = sigGen.GenerateCertification(secKey.PublicKey); PgpPublicKey.AddCertification(secKey.PublicKey, sig); sig.InitVerify(secKey.PublicKey); if (!sig.VerifyCertification(secKey.PublicKey)) { throw new PgpException("revocation verification failed."); } sig.Encode(outArmour); outArmour.Close(); } mStream.Position = 0; StreamReader srdr = new StreamReader(mStream); string armour = srdr.ReadToEnd(); string outstr = armour.Replace("BEGIN PGP SIGNATURE", "BEGIN PGP PUBLIC KEY BLOCK") .Replace("END PGP SIGNATURE", "END PGP PUBLIC KEY BLOCK"); mStream.Close(); if (string.IsNullOrEmpty(keyExportName)) { useTemp = true; string tempPath = Path.GetTempPath(); keyExportName = Path.Combine(tempPath, Guid.NewGuid().ToString() + ".tmppgp"); } File.WriteAllText(keyExportName, outstr); keyExportName = ""; //Debug.Assert(secKey.PublicKey.IsRevoked() == true); break; case SignatureOperation.SetKeyExpiry: break; case SignatureOperation.CertifyKey: break; default: break; } if (secKey.PublicKey != null) { if (string.IsNullOrEmpty(keyExportName)) { useTemp = true; string tempPath = Path.GetTempPath(); keyExportName = Path.Combine(tempPath, Guid.NewGuid().ToString() + ".tmppgp"); } ExportKey expKey = new ExportKey(keyDb); expKey.UpdateDbSecretKey(secKey, keyExportName); if (useTemp) { //File.Delete(keyExportName); } } }
public static void AddCertification(PgpPublicKey key, KeyStoreDB keyDb, PgpSecretKey secKey, char[] passPhrase) { }
public int ImportSecretKey(string fileName, string filePath, KeyStoreDB keyStoreDB) { int cntImport = 0; string keyPath = Path.Combine(filePath, fileName); string stringFileContent = File.ReadAllText(keyPath); PgpSecretKey secKey = ReadSecretKey(keyPath, true); //bool removed = RemovePublicKeyForSecretKey(secKey.KeyId, keyStoreDB); try { keyStoreDB.KeyStores.Add(new KeyStores() { KeyStoreID = secKey.KeyId, ArmouredKeyFile = stringFileContent, Fingerprint = secKey.PublicKey.GetFingerprint(), CreationTime = secKey.PublicKey.CreationTime, ValidDays = secKey.PublicKey.ValidDays, IsEncryptionKey = false, IsMasterKey = secKey.IsMasterKey, IsSigningKey = secKey.IsSigningKey, IsRevoked = secKey.PublicKey.IsRevoked(), KeyType = "Secret" }); IEnumerable userIDs = secKey.UserIds; foreach (string userId in userIDs) { Match match = Regex.Match(userId, strRegex, RegexOptions.Compiled); if (match != null) { string comment1 = match.Groups["comment1"] != null ? match.Groups["comment1"].Value : string.Empty; string comment2 = match.Groups["comment2"] != null ? match.Groups["comment2"].Value : string.Empty; if (!string.IsNullOrEmpty(comment2)) { comment1 += " " + comment2; } KeyUsers userExists = keyStoreDB.KeyUsers.Find(secKey.KeyId); if (userExists != null) { keyStoreDB.KeyUsers.Remove(userExists); keyStoreDB.SaveChanges(); } keyStoreDB.KeyUsers.Add(new KeyUsers() { KeyStoreID = secKey.KeyId, UserName = match.Groups["user"] != null ? match.Groups["user"].Value : string.Empty, Email = match.Groups["email"] != null ? match.Groups["email"].Value : string.Empty, Comment = comment1, EncryptionType = ((PublicKeyAlgorithmTag)secKey.PublicKey.Algorithm).ToString(), KeySize = secKey.PublicKey.BitStrength }); } } keyStoreDB.SaveChanges(); } catch (DbUpdateConcurrencyException dbConEx) { throw new DbUpdateConcurrencyException(dbConEx.Message); } catch (DbUpdateException dbEx) { throw new DbUpdateException(dbEx.Message); } catch (Exception ex) { throw new Exception(ex.Message); } return(++cntImport); }
public static void KeyChangePassphrase(PgpSecretKey key, char[] originalPhrase, char[] newPhrase, KeyStoreDB keyDb, string keyExportName) { string fileData = string.Empty; bool useTemp = false; if (key == null) { throw new ArgumentNullException("key"); } if (keyDb == null) { throw new ArgumentNullException("keyDb"); } if (originalPhrase == null || originalPhrase.Count() <= 0) { throw new ArgumentNullException("originalPhrase"); } if (newPhrase == null || newPhrase.Count() <= 0) { throw new ArgumentNullException("newPhrase"); } PgpSecretKey newKey = ChangePassprase(key, originalPhrase, newPhrase); Debug.Assert(key.GetHashCode() != newKey.GetHashCode()); if (newKey != null) { if (string.IsNullOrEmpty(keyExportName)) { useTemp = true; string tempPath = Path.GetTempPath(); keyExportName = Path.Combine(tempPath, Guid.NewGuid().ToString() + ".tmppgp"); } ExportKey expKey = new ExportKey(keyDb); expKey.UpdateDbSecretKey(newKey, keyExportName); if (useTemp) { //File.Delete(keyExportName); } } }
public ExportKey(KeyStoreDB keyStoreDb) { m_keyStoreDb = keyStoreDb; }