static void Main(string[] args) { string keyfile = "", inputFileName = "", outputFileName = "", keypassword = ""; ParamNameConstantsEnum encodingPreference = ParamNameConstantsEnum.Default; if (args == null || args.Length == 0) { Console.WriteLine("No Params provided"); Console.WriteLine("--help for Help"); return; } if (args[0].Trim() == "--help") { Console.WriteLine("[Operation] --i [InputFile] --o [OutputFile] --k [KeyFile]"); Console.WriteLine("[Operation]--d to Decrypt File --e to Encrypt File"); Console.WriteLine("Optional Parameters"); Console.WriteLine("Optional Paramter to be used to specify encryption file format --base64 if the application should output encrypted file in base64 format only"); Console.WriteLine("Optional parameter to be used with Decryption Operation for encrypted Private Key --privatekeypassword [Private Key Password]"); return; } foreach (string s in args) { Console.WriteLine(s); } ParamNameConstantsEnum optype = ParamNameConstants.GetParamType(args[0]); switch (optype) { case ParamNameConstantsEnum.Unknown: Console.WriteLine("Operation not specified as first parameter " + Environment.NewLine + " Operation switches --d for Decrypt " + Environment.NewLine + " --e for Encrypt " + Environment.NewLine); break; case ParamNameConstantsEnum n when(n == ParamNameConstantsEnum.Encrypt || n == ParamNameConstantsEnum.Decrypt): int argcounter = 1, argsreceived = 0; while (argsreceived < 3) { try { if (args[argcounter].Contains("--")) { ParamNameConstantsEnum argtype = ParamNameConstants.GetParamType(args[argcounter]); switch (argtype) { case ParamNameConstantsEnum.Unknown: Console.WriteLine("Unknown parameter"); argcounter++; break; case ParamNameConstantsEnum.InputFile: argcounter++; if (String.IsNullOrEmpty(args[argcounter])) { Console.WriteLine("Input file not specified"); throw new ArgumentNullException("Input file not specified"); } else { inputFileName = args[argcounter]; argsreceived++; } break; case ParamNameConstantsEnum.OutputFile: argcounter++; if (String.IsNullOrEmpty(args[argcounter])) { Console.WriteLine("Output file not specified"); throw new ArgumentNullException("Output file not specified"); } else { outputFileName = args[argcounter]; argsreceived++; } break; case ParamNameConstantsEnum.KeyFile: argcounter++; if (String.IsNullOrEmpty(args[argcounter])) { Console.WriteLine("Key file not specified"); throw new ArgumentNullException("Key file not specified"); } else { keyfile = args[argcounter]; argsreceived++; } break; case ParamNameConstantsEnum.PrivateKeyDecryptionPassword: argcounter++; if (String.IsNullOrEmpty(args[argcounter])) { Console.WriteLine("Private key password not specified"); throw new ArgumentNullException("Private key password not specified"); } else { keypassword = args[argcounter]; } break; case ParamNameConstantsEnum pref when(pref == ParamNameConstantsEnum.Binary || pref == ParamNameConstantsEnum.Base64): encodingPreference = pref; break; } } argcounter++; if (args.Length <= argcounter) { break; } } catch (ArgumentOutOfRangeException aorex) { Console.WriteLine("All required information was not provided " + aorex.ToString()); break; } catch (ArgumentNullException) { Console.WriteLine("All information required for operation was not specified correctly"); } } if (argsreceived == 3) { bool success = new FileEncryptor() { PrivateKeyEncryptionpassword = keypassword }.PerformOperation(keyfile, inputFileName, outputFileName, optype, encodingPreference); Console.WriteLine(" Operation was {0}", success? "Successful": "Unsuccessful"); } else { Console.WriteLine("Something went wrong, program will now exit..."); } break; default: Console.WriteLine("Something went wrong, program will now exit.."); break; } }
public bool DecryptFile(string privateKeyFile, string inputFileName, string outputFileName, ParamNameConstantsEnum encpreference) { FileStream fs; StringBuilder sb; RSACryptoServiceProvider rsa; string outputkeyfileName = inputFileName + ".info";; if (encpreference == ParamNameConstantsEnum.Base64) { outputkeyfileName = outputkeyfileName.Replace(".base64", ""); } try { using (fs = File.Open(privateKeyFile, FileMode.Open)) { StreamReader sr = new StreamReader(fs); sb = new StringBuilder(); sb.Append(sr.ReadToEnd()); sr.Close(); } string pemkey = sb.ToString(); int encryptedkeyindex = pemkey.IndexOf(KeyPhraseConstants.PrivateKeyEncryptionInfo, 0); //Console.WriteLine(" key encryption index : {0}",encryptedkeyindex); if (encryptedkeyindex >= 0) { using (MemoryStream memrd = new MemoryStream()) { StreamWriter wr = new StreamWriter(memrd); wr.Write(sb.ToString()); wr.Flush(); //wr.Close(); memrd.Position = 0; StreamReader rd = new StreamReader(memrd); if (string.IsNullOrEmpty(this.privateKeyEncryptionpassword.Trim())) { throw new PasswordNotSuppliedException("Private key is encrypted...Password for Decrypting private key not provided"); } PemReader pemreader = new PemReader(rd, new PemPasswordFinder(privateKeyEncryptionpassword)); AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemreader.ReadObject(); RsaPrivateCrtKeyParameters rsaparams = (RsaPrivateCrtKeyParameters)keyPair.Private; RSAParameters rsp = DotNetUtilities.ToRSAParameters(rsaparams); rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(rsp); rd.Close(); wr.Close(); memrd.Close(); } } else { int startkeyphraseindex = pemkey.IndexOf(KeyPhraseConstants.PrivateKeyStart, 0); int keystartindex = startkeyphraseindex + KeyPhraseConstants.PrivateKeyStart.Length; int endkeyphraseindex = pemkey.IndexOf(KeyPhraseConstants.PrivateKeyEnd, 0); string key = pemkey.Substring(keystartindex, pemkey.Length - (keystartindex + 1) - (pemkey.Length - endkeyphraseindex - 1)); sb = new StringBuilder(); sb.Append(key.Replace("\r", "")); sb.Replace("\n", ""); key = sb.ToString().Trim(); byte[] keydata = Convert.FromBase64String(key); rsa = new PemFileLoader().LoadPemPrivateKeyFile(keydata); } //Console.WriteLine(" File to decrypt " + inputFileName); //Console.WriteLine(" decrypted file" + outputFileName); if ((inputFileName != "") && (outputFileName != "")) { using (fs = File.Open(outputkeyfileName, FileMode.Open)) { byte[] decryptedbuffer; StreamReader reader = new StreamReader(fs); byte[] outbuffer = Convert.FromBase64String(reader.ReadToEnd()); reader.Close(); decryptedbuffer = rsa.Decrypt(outbuffer, RSAEncryptionPadding.Pkcs1); SymmetricFileEncryptor flencryptor = new SymmetricFileEncryptor(); switch (encpreference) { case ParamNameConstantsEnum.Base64: if (File.Exists(inputFileName)) { flencryptor.DecryptFromBase64EncodedFile(inputFileName, outputFileName, decryptedbuffer); } break; case ParamNameConstantsEnum.Binary: if (File.Exists(inputFileName)) { flencryptor.DecryptFile(inputFileName, outputFileName, decryptedbuffer); } break; default: if (File.Exists(inputFileName)) { flencryptor.DecryptFile(inputFileName, outputFileName, decryptedbuffer); } if (File.Exists(inputFileName + ".base64")) { flencryptor.DecryptFromBase64EncodedFile(inputFileName + ".base64", outputFileName + ".base64out", decryptedbuffer); } break; } } } return(true); } catch (FileNotFoundException fex) { Console.WriteLine("COuld not find key file " + fex.ToString()); } catch (PasswordNotSuppliedException pex) { Console.WriteLine("Could not decrypt private key to decrypt file : " + pex.ToString()); } catch (Exception ex) { Console.WriteLine("General exception " + ex.ToString()); } return(false); }
public bool PerformOperation(string keyfile, string inputFileName, string outputFileName, ParamNameConstantsEnum operation, ParamNameConstantsEnum encpreference) { switch (operation) { case ParamNameConstantsEnum.Decrypt: return(this.DecryptFile(keyfile, inputFileName, outputFileName, encpreference)); case ParamNameConstantsEnum.Encrypt: return(this.EncryptFile(keyfile, inputFileName, outputFileName, encpreference)); default: break; } return(false); }
public bool EncryptFile(string publicKeyFile, string inputFileName, string outputFileName, ParamNameConstantsEnum encpreference) { FileStream fs; StringBuilder sb; string outputkeyfileName = outputFileName + ".info"; try { using (fs = File.Open(publicKeyFile, FileMode.Open)) { StreamReader sr = new StreamReader(fs); sb = new StringBuilder(); sb.Append(sr.ReadToEnd()); sr.Close(); } string pemkey = sb.ToString(); int startkeyphraseindex = pemkey.IndexOf(KeyPhraseConstants.PublicKeyStart, 0); int keystartindex = startkeyphraseindex + KeyPhraseConstants.PublicKeyStart.Length; int endkeyphraseindex = pemkey.IndexOf(KeyPhraseConstants.PublicKeyEnd, 0); string key = pemkey.Substring(keystartindex, pemkey.Length - (keystartindex + 1) - (pemkey.Length - endkeyphraseindex - 1)); sb = new StringBuilder(); sb.Append(key.Replace("\r", "")); sb.Replace("\n", ""); key = sb.ToString().Trim(); byte[] keydata = Convert.FromBase64String(key); RSACryptoServiceProvider rsa = new PemFileLoader().LoadPemPublicKeyFile(keydata); Console.WriteLine(" File to encrypt " + inputFileName); Console.WriteLine(" Output File " + outputFileName); if ((inputFileName != "") && (outputFileName != "")) { SymmetricFileEncryptor flencryptor = new SymmetricFileEncryptor(); byte[] data = flencryptor.EncryptFile(inputFileName, outputFileName); byte[] plaintextbuffer; using (FileStream fsout = File.Open(outputkeyfileName, FileMode.Create)) { plaintextbuffer = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1); //fsout.Write(plaintextbuffer,0,plaintextbuffer.Length); StreamWriter writer = new StreamWriter(fsout); writer.Write(Convert.ToBase64String(plaintextbuffer)); writer.Flush(); writer.Close(); fsout.Close(); } } return(true); } catch (FileNotFoundException fex) { Console.WriteLine("COuld not find key file " + fex.ToString()); } catch (Exception ex) { Console.WriteLine("General exception " + ex.ToString()); } return(false); }