public bool DecryptData(string signed, string msg = "") { if (Init()) { if (_type == 1) { //SHA256 sha256Hash = SHA256.Create(); //byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(msg)); byte[] bsigned = StringToByteArray(signed); byte[] bytes = Encoding.UTF8.GetBytes(msg); var rsa = RSA.Create(); rsa.KeySize = _keySize; rsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(_publicKey), out int byteReads); var result = rsa.VerifyData(bytes, bsigned, HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1); return(result); } else { PGPLib pgp = new PGPLib(); byte[] bytes = Encoding.UTF8.GetBytes(_publicKey); var stream = new MemoryStream(bytes); SignatureCheckResult signatureCheck = pgp.VerifyString(signed, stream, out string plainText); var result = signatureCheck == SignatureCheckResult.SignatureVerified; return(result); } } else { return(false); } }
public string EncryptData(string msg) { if (Init()) { if (_type == 1) { SHA256 sha256Hash = SHA256.Create(); byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(msg)); var rsa = RSA.Create(); rsa.KeySize = 1024; rsa.ImportRSAPrivateKey(Convert.FromBase64String(_privateKey), out int byteReads); var signed = rsa.SignData(bytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); string result = Convert.ToBase64String(signed); return(result); } else { PGPLib pgp = new PGPLib(); var signed = pgp.SignString(msg, new FileInfo(_privateKey), _pgpKeyPassword); return(signed); } } else { return(null); } }
public String encrypet(string InputText, string path, int ID) { String plainString = InputText; // create an instance of the library PGPLib pgp = new PGPLib(); Studnets loginStudent = new Studnets(); DataRow loginS = loginStudent.drSearchStudentEmail(ID); string password = null; if (loginS != null) { password = loginS["Password"].ToString(); } String signedString = ""; try { signedString = pgp.SignString(plainString, new FileInfo(path), password); } catch { return("false"); } return(signedString); }
private void EncryptMessageButton_Click(object sender, RoutedEventArgs e) { string publickey = new TextRange(PublicKeyBox.Document.ContentStart, PublicKeyBox.Document.ContentEnd).Text; string message = new TextRange(MessageToBeEncryptedBox.Document.ContentStart, MessageToBeEncryptedBox.Document.ContentEnd).Text; PGPLib pgp = new PGPLib(); MemoryStream encryptedmessage = new MemoryStream(); using (MemoryStream messagestream = new MemoryStream(Encoding.UTF8.GetBytes(message))) { using (MemoryStream publickeystream = new MemoryStream(Encoding.UTF8.GetBytes(publickey))) { bool ascii = true; pgp.EncryptStream(messagestream, publickeystream, encryptedmessage, ascii); encryptedmessage = new MemoryStream(encryptedmessage.ToArray()); StreamReader streamReader = new StreamReader(encryptedmessage); string encryptedtext = streamReader.ReadToEnd(); EncryptedMessageBox.Text = ""; EncryptedMessageBox.Text = encryptedtext; } } }
private void DecryptButton_Click(object sender, RoutedEventArgs e) { string encryptedmessage = new TextRange(EncryptedMessageTextbox.Document.ContentStart, EncryptedMessageTextbox.Document.ContentEnd).Text; string password = PasswordBox.Text; string privatekey = new TextRange(PrivateKeyTextbox.Document.ContentStart, PrivateKeyTextbox.Document.ContentEnd).Text; if (encryptedmessage == String.Empty) { MessageBox.Show("Keine Nachricht eingegeben"); } if (privatekey == String.Empty) { MessageBox.Show("Keinen Private Key eingegeben"); } PGPLib pGPLib = new PGPLib(); MemoryStream decrypted = new MemoryStream(); using (MemoryStream encryptedmessagestream = new MemoryStream(Encoding.UTF8.GetBytes(encryptedmessage))) { using (MemoryStream privatekeystream = new MemoryStream(Encoding.UTF8.GetBytes(privatekey))) { string test = pGPLib.DecryptStream(encryptedmessagestream, privatekeystream, password, decrypted); decrypted = new MemoryStream(decrypted.ToArray()); StreamReader streamReader = new StreamReader(decrypted); string decryptedtext = streamReader.ReadToEnd(); DecryptedMessageBox.Text = ""; DecryptedMessageBox.Text = decryptedtext; } } }
public string DecryptFiles(string EncryptedFilePath, string KeyInboundPath, string KeyInboundPassword, string OutputFolder) { string result = null; // initialize the library PGPLib pgp = new PGPLib(); pgp.Cypher = CypherAlgorithm.TRIPLE_DES; // decrypts the content of the PGP archive // and returns array with full file paths of the // exytracted file(s) string[] decryptedFileNames = { }; try { decryptedFileNames = pgp.DecryptTo(EncryptedFilePath, KeyInboundPath, KeyInboundPassword, OutputFolder); } catch (IOException ex) { throw ex; } catch (PGPException ex) { if (ex is NonPGPDataException) { throw new Exception("the passed encrypted input is not a valid OpenPGP archive"); } else if (ex is IntegrityCheckException) { throw new Exception("the passed encrypted input is corrupted"); } else if (ex is FileIsPBEEncryptedException) { throw new Exception("the passed encrypted input is encrypted with a password, but an attempted was made to decrypt it with a private key"); } else if (ex is WrongPrivateKeyException) { throw new Exception("the encrypted input was encrypted with a different private key than the provided one"); } else if (ex is WrongPasswordException) { throw new Exception("the password for the provided private key is wrong"); } else { throw new Exception("general decryption error"); } } return(result); }
public string DecryptFile(string EncryptedFilePath, string KeyInboundPath, string KeyInboundPassword, string SenderKeyPath, string OutputFilePath) { string result = null; // initialize the library PGPLib pgp = new PGPLib(); pgp.Cypher = CypherAlgorithm.TRIPLE_DES; try { bool verified = pgp.DecryptAndVerifyFile(EncryptedFilePath, KeyInboundPath, KeyInboundPassword, SenderKeyPath, OutputFilePath); if (!verified) { throw new Exception("Signature is invalid!"); } } catch (IOException ex) { throw ex; } catch (PGPException ex) { if (ex is NonPGPDataException) { throw new Exception("the passed encrypted input is not a valid OpenPGP archive"); } else if (ex is IntegrityCheckException) { throw new Exception("the passed encrypted input is corrupted"); } else if (ex is FileIsPBEEncryptedException) { throw new Exception("the passed encrypted input is encrypted with a password, but an attempted was made to decrypt it with a private key"); } else if (ex is WrongPrivateKeyException) { throw new Exception("the encrypted input was encrypted with a different private key than the provided one"); } else if (ex is WrongPasswordException) { throw new Exception("the password for the provided private key is wrong"); } else { throw new Exception("general decryption error"); } } return(result); }
static void DownloadandDecrypt() { PGPLib pgp = new PGPLib(); bool asciiArmor = false; bool withIntegrityCheck = false; string downloadedblobpath = @"C:\DATA FILES\Downloaded Files\"; string decryptedblobpath = @"C:\DATA FILES\Decrypted Files\"; string fileName = ""; string privatekeypassword = "******"; string downloadedfile = System.IO.Path.Combine(downloadedblobpath, fileName); string decryptedfile = System.IO.Path.Combine(decryptedblobpath, fileName); CloudStorageAccount storageAccount = CloudStorageAccount.Parse( CloudConfigurationManager.GetSetting("StorageConnectionString")); // Create the blob client. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve reference to a previously created container. CloudBlobContainer container = blobClient.GetContainerReference("encryptedtgblfiles"); foreach (IListBlobItem item in container.ListBlobs(null, false)) { if (item.GetType() == typeof(CloudBlockBlob)) { CloudBlockBlob blob = (CloudBlockBlob)item; // Retrieve reference to a blob named "photo1.jpg". CloudBlockBlob blockBlob = container.GetBlockBlobReference(blob.Name); // Save blob contents to a file. using (var fileStream = System.IO.File.OpenWrite(downloadedblobpath + blob.Name)) { blockBlob.DownloadToStream(fileStream); } } } if (System.IO.Directory.Exists(downloadedblobpath)) { string[] files = System.IO.Directory.GetFiles(downloadedblobpath); // Copy the files and overwrite destination files if they already exist. foreach (string s in files) { // Use static Path methods to extract only the file name from the path. fileName = System.IO.Path.GetFileName(s); pgp.DecryptFile(downloadedblobpath + fileName, @"C:\DATA FILES\privatekey.asc", privatekeypassword, decryptedblobpath + fileName); // destFile = System.IO.Path.Combine(targetPath, fileName); // System.IO.File.Copy(s, destFile, true); } } }
public Boolean Decreypt(string encrypt, int ID) { //Get Public File GetKey objKey = new GetKey(); DataRow drKey = objKey.drSearchStudentKey(ID); string PublicKey1 = drKey[0].ToString(); // obtain an OpenPGP signed message String signedString = encrypt; // Extract the message and check the validity of the signature String plainText; // create an instance of the library PGPLib pgp = new PGPLib(); SignatureCheckResult signatureCheck; try { signatureCheck = pgp.VerifyString(signedString, new FileInfo(PublicKey1), out plainText); } catch { return(false); } string strData1 = plainText; // Print the results Console.WriteLine("Extracted plain text message is " + plainText); if (signatureCheck == SignatureCheckResult.SignatureVerified) { // Console.WriteLine("Signature OK"); return(true); } else if (signatureCheck == SignatureCheckResult.SignatureBroken) { //Console.WriteLine("Signature of the message is either broken or forged"); return(false); } else if (signatureCheck == SignatureCheckResult.PublicKeyNotMatching) { // Console.WriteLine("The provided public key doesn't match the signature"); return(false); } else if (signatureCheck == SignatureCheckResult.NoSignatureFound) { // Console.WriteLine("This message is not digitally signed"); return(false); } return(false); }
public string EncryptFile(string keyPath, string ediToEnc) { try { PGPLib pgp = new PGPLib(); return(pgp.EncryptString(ediToEnc, keyPath)); } catch (Exception ex) { Console.WriteLine(ex.Message); return(string.Empty); } }
public void Decreypt(string encrypt) { //Get Public File GetKey objKey = new GetKey(); int ID = Convert.ToInt32(Session["ID"].ToString()); DataRow drKey = objKey.drSearchStudentKey(ID); string PublicKey1 = drKey[0].ToString(); // obtain an OpenPGP signed message String signedString = encrypt; // Extract the message and check the validity of the signature String plainText; // create an instance of the library PGPLib pgp = new PGPLib(); //SignatureCheckResult signatureCheck = pgp.VerifyString(signedString, // new FileInfo(@"C:\Users\Dua'a-Orcas\Desktop\finalProject\WebApplication1 - Copy (2)\WebApplication1\Sig\public_key_exported.asc"), // out plainText); SignatureCheckResult signatureCheck = pgp.VerifyString(signedString, new FileInfo(PublicKey1), out plainText); string strData1 = plainText; // Print the results Console.WriteLine("Extracted plain text message is " + plainText); if (signatureCheck == SignatureCheckResult.SignatureVerified) { Console.WriteLine("Signature OK"); Result = true; } else if (signatureCheck == SignatureCheckResult.SignatureBroken) { Console.WriteLine("Signature of the message is either broken or forged"); } else if (signatureCheck == SignatureCheckResult.PublicKeyNotMatching) { Console.WriteLine("The provided public key doesn't match the signature"); } else if (signatureCheck == SignatureCheckResult.NoSignatureFound) { Console.WriteLine("This message is not digitally signed"); } }
public string EncryptData(string msg, string code = "") { if (Init()) { if (_type == 1) { //SHA256 sha256Hash = SHA256.Create(); // byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(msg)); //var key = Encoding.UTF8.GetBytes(code); //HMACMD5 hmac = new HMACMD5(key); // Convert the input string to a byte array and compute the hash. //byte[] bytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(msg)); var rsa = RSA.Create(); rsa.KeySize = _keySize; rsa.ImportRSAPrivateKey(Convert.FromBase64String(_privateKey), out int byteReads); var r = rsa.SignData(Encoding.UTF8.GetBytes(msg), HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1); //string result = Convert.ToBase64String(r); StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < r.Length; i++) { sBuilder.Append(r[i].ToString("x2")); } return(sBuilder.ToString()); } else { PGPLib pgp = new PGPLib(); byte[] bytes = Encoding.UTF8.GetBytes(_privateKey); var stream = new MemoryStream(bytes); var signed = pgp.SignString(msg, stream, _pgpKeyPassword); // Xử lý chuỗi lấy ra base64 string var split = signed.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); string result = string.Join("", split.Skip(2).Take(split.Length - 3)); // return(result); } } else { return(null); } }
private string signDataPgp() { PGPLib pgp = new PGPLib(); try { string privateKeyPem = Directory.GetCurrentDirectory().ToString() + @"\Services\fileKey\privateKeyPGP.asc"; string secretKeyFile = Directory.GetCurrentDirectory().ToString() + @"\Services\fileKey\secretKeyFile.txt"; string signPGPFile = Directory.GetCurrentDirectory().ToString() + @"\Services\fileKey\signPGP.pgp"; pgp.SignFile(secretKeyFile, privateKeyPem, "nhom9", signPGPFile, true); //var signText = pgp.SignString("nhom9", privateKeyPem, "nhom9"); string signText = System.IO.File.ReadAllText(Directory.GetCurrentDirectory().ToString() + @"\Services\fileKey\signPGP.pgp"); return(signText); } catch (Exception e) { return(""); } }
public static String MultiRecipientStringEncrypter(string toBeEncryptedData, string secretKeyPath, string[] recipientPublicKeyPaths, bool gui = false, string privatePassWord = "") { FileInfo secKeyPathInfo = new FileInfo(secretKeyPath); FileStream secKeyStream = secKeyPathInfo.OpenRead(); PGPLib pgp = new PGPLib(); MemoryStream streamString = new MemoryStream(Encoding.UTF8.GetBytes(toBeEncryptedData)); FileStream[] recipientPublicKeyPathsStream = new FileStream[recipientPublicKeyPaths.Length]; for (int i = 0; i < recipientPublicKeyPaths.Length; i++) { FileInfo publicKeyInfo = new FileInfo(recipientPublicKeyPaths[i]); recipientPublicKeyPathsStream[i] = publicKeyInfo.OpenRead(); } if (privatePassWord == "") { if (!gui) { Console.Write("Please enter the passphrase of the chosen private key: "); privatePassWord = Console.ReadLine(); } else { privatePassWord = Prompt.ShowDialog("Enter the password of the chosen secret key", "Password entry", false, false, false); } } MemoryStream encryptedOutputStream = new MemoryStream(); Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; string filler = unixTimestamp.ToString(); //needed for the encryption, decided that it may as well have a semi-useful value pgp.SignAndEncryptStream(streamString, filler, secKeyStream, privatePassWord, recipientPublicKeyPathsStream, encryptedOutputStream, true, true); string encryptedMultiRecipientString = Encoding.ASCII.GetString(encryptedOutputStream.ToArray()); return(encryptedMultiRecipientString); }
public String encrypet(string InputText, string path) { int ID = Convert.ToInt32(Session["ID"].ToString()); String plainString = InputText; // create an instance of the library PGPLib pgp = new PGPLib(); Studnets loginStudent = new Studnets(); DataRow loginS = loginStudent.drSearchStudentEmail(ID); string password = null; if (loginS != null) { password = loginS["Password"].ToString(); } String signedString = pgp.SignString(plainString, new FileInfo(path), password); return(signedString); }
public String encrypet(string InputText, string path, string password) { String plainString = InputText; // create an instance of the library PGPLib pgp = new PGPLib(); String signedString = ""; try { signedString = pgp.SignString(plainString, new FileInfo(path), password); } catch { return("false"); } return(signedString); }
static void RawFileMovetoEncrypt() { PGPLib pgp = new PGPLib(); bool asciiArmor = false; bool withIntegrityCheck = false; string sourcePath = @"C:\DATA FILES\Raw Data Files\"; string targetPath = @"C:\DATA FILES\Encrypted Data Files\"; string fileName = ""; int fileSize; string sourceFile = System.IO.Path.Combine(sourcePath, fileName); string destFile = System.IO.Path.Combine(targetPath, fileName); if (System.IO.Directory.Exists(sourcePath)) { string[] files = System.IO.Directory.GetFiles(sourcePath); // Copy the files and overwrite destination files if they already exist. foreach (string s in files) { // Use static Path methods to extract only the file name from the path. fileName = System.IO.Path.GetFileName(s); pgp.EncryptFile(sourcePath + fileName, @"C:\DATA FILES\publickey.asc", targetPath + fileName, asciiArmor, withIntegrityCheck); // destFile = System.IO.Path.Combine(targetPath, fileName); // System.IO.File.Copy(s, destFile, true); } } CloudStorageAccount storageAccount = CloudStorageAccount.Parse( CloudConfigurationManager.GetSetting("StorageConnectionString")); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); //encryptedtgblfiles CloudBlobContainer container = blobClient.GetContainerReference("encryptedtgblfiles"); if (System.IO.Directory.Exists(sourcePath)) { string[] files = System.IO.Directory.GetFiles(sourcePath); // Copy the files and overwrite destination files if they already exist. foreach (string s in files) { fileName = System.IO.Path.GetFileName(s); CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName); fileSize = fileName.Length; // Create or overwrite the "myblob" blob with contents from a local file. using (var fileStream = System.IO.File.OpenRead(targetPath + fileName)) { blockBlob.UploadFromStream(fileStream); } // To move a file or folder to a new location: // logger(fileName, "Uploaded",fileSize); // To move an entire directory. To programmatically modify or combine // path strings, use the System.IO.Path class. //System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private"); } } }
public static void Decrypt(string encryptedMessage, string secretKeyPath, string publicKeyPath, bool gui = false, string privatePassWord = "") { string plainTextExtracted; if (privatePassWord == "") { if (!gui) { Console.Write("Please enter the passphrase of the chosen private key: "); privatePassWord = Console.ReadLine(); } else { privatePassWord = Prompt.ShowDialog("Enter the password of the chosen secret key", "Password entry", false, false, false); } } // create an instance of the library PGPLib pgp = new PGPLib(); // decrypt and verify try { SignatureCheckResult signatureCheck = pgp.DecryptAndVerifyString(encryptedMessage, new FileInfo(secretKeyPath), //secret key path privatePassWord, //this is the password of the secret key new FileInfo(publicKeyPath), out string plainTextExtract); plainTextExtracted = plainTextExtract; // print the results if (signatureCheck == SignatureCheckResult.SignatureVerified) { Console.WriteLine("Signature OK"); if (gui) { MessageBox.Show("Signature OK"); } } else if (signatureCheck == SignatureCheckResult.SignatureBroken) { Console.WriteLine("Signature of the message is either broken or forged"); if (gui) { MessageBox.Show("Signature of the message is either broken or forged"); } } else if (signatureCheck == SignatureCheckResult.PublicKeyNotMatching) { Console.WriteLine("The provided public key doesn't match the signature"); if (gui) { MessageBox.Show("The provided public key doesn't match the signature"); } } else if (signatureCheck == SignatureCheckResult.NoSignatureFound) { Console.WriteLine("This message is not digitally signed"); if (gui) { MessageBox.Show("This message is not digitally signed"); } } if (!gui) { Console.WriteLine("Extracted message: \n" + plainTextExtracted); } else { SimpleReportViewer.ShowDialog(plainTextExtracted, "Decrypted data", Program.genericGUIForm); } } catch (Exception e) { if (e is DidiSoft.Pgp.Exceptions.WrongPrivateKeyException) { Console.WriteLine("The chosen private key is either not a private key or not suited to decrypt this message."); if (gui) { MessageBox.Show("The chosen private key is either not a private key or not suited to decrypt this message."); } //The supplied private key source is not a private key at all } else if (e is DidiSoft.Pgp.Exceptions.WrongPasswordException) { Console.WriteLine("The entered passphrase is incorrect, please try again."); if (!gui) { Decrypt(encryptedMessage, secretKeyPath, publicKeyPath); } else { MessageBox.Show("The entered passphrase is incorrect, please try again."); } } else if (e is DidiSoft.Pgp.Exceptions.WrongPublicKeyException) { if (!gui) { Console.WriteLine("The chosen public key is either not a public key or not suited to verify this message."); } else { MessageBox.Show("The chosen public key is either not a public key or not suited to verify this message."); } } else if (e is DidiSoft.Pgp.Exceptions.KeyIsExpiredException) { Console.WriteLine("The public key you want to encrypt for is expired and cannot be used."); if (gui) { MessageBox.Show("The public key you want to encrypt for is expired and cannot be used."); } //Can be worked around by setting UseExpiredKeys to true } else if (e is DidiSoft.Pgp.Exceptions.KeyIsRevokedException) { Console.WriteLine("The public key you want to encrypt for appears to be revoked and cannot be used."); if (gui) { MessageBox.Show("The public key you want to encrypt for appears to be revoked and cannot be used."); } //Can be worked around by setting UseRevokedKeys to true } else if (e is DidiSoft.Pgp.Exceptions.NonPGPDataException) { Console.WriteLine("The data you want to decrypt is not encrypted with PGP."); if (gui) { MessageBox.Show("The data you want to decrypt is not encrypted with PGP."); } //Can be worked around by setting UseRevokedKeys to true } else if (e is IOException) { Console.WriteLine("IO Exception has occured, decrypting of unencrypted data is not possible."); if (gui) { MessageBox.Show("IO Exception has occured, decrypting of unencrypted data is not possible."); } //Can be worked around by setting UseRevokedKeys to true } else { throw new ApplicationException("Something unexpected went wrong, contact support and explain your actions in detail and chronological order."); } } }