예제 #1
0
        /// <summary>
        /// Private test method.
        /// </summary>
        private static void Encry_Decry_test()
        {
            // testing area for debug
            // string to BI
            string message = "Hello World";

            byte[]     message_byte = Encoding.ASCII.GetBytes(message);
            BigInteger M            = new BigInteger(message_byte);

            KeyGenerator keyGenerator = new KeyGenerator();

            keyGenerator.generateKeys();
            //Console.WriteLine("Keys: E: " + keyGenerator.E + " D: " + keyGenerator.D + " N: " + keyGenerator.N);

            Byte[] pub_key           = keyGenerator.getPublicKey();
            string pub_key_base64str = Convert.ToBase64String(pub_key);
            //Console.WriteLine("Public Key: " + pub_key_base64str + " ; Size: " + pub_key.Length);
            KeyParser pub_KP = new KeyParser(pub_key_base64str, true);

            pub_KP.parse();
            Console.WriteLine("Parsed pub key: " + " E: " + (pub_KP.E == keyGenerator.E) + "; N: " + (pub_KP.N == keyGenerator.N));

            BigInteger C = RSAEncryptor.RSA_Encrypt(M, pub_KP.E, pub_KP.N);

            Byte[] private_key           = keyGenerator.getPrivateKey();
            string private_key_base64str = Convert.ToBase64String(private_key);
            //Console.WriteLine("Private Key: " + private_key_base64str + " ; Size: " + private_key.Length);
            KeyParser priv_KP = new KeyParser(private_key_base64str, false);

            priv_KP.parse();
            Console.WriteLine("Parsed private key: " + " D: " + (priv_KP.D == keyGenerator.D) + "; N: " + (priv_KP.N == keyGenerator.N));


            BigInteger M_decrypted = RSAEncryptor.RSA_Decrypt(C, priv_KP.D, priv_KP.N);

            byte[] M_decrypted_byte  = M_decrypted.ToByteArray();
            string message_decrypted = Encoding.ASCII.GetString(M_decrypted_byte);

            Console.WriteLine("Decrypted: " + message_decrypted);

            // testing ends here
        }
예제 #2
0
        /// <summary>
        /// The main program that executes based on command line arguments
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        static async Task Main(string[] args)
        {
            // test
            // Encry_Decry_test();

            KeySystem    keySystem = new KeySystem();
            KeyGenerator KG        = new KeyGenerator();
            HttpClient   client    = new HttpClient();

            string server_address = "http://kayrun.cs.rit.edu:5000";

            if (args.Length != 0)
            {
                // Handle Argument Input
                if (args[0] == "keyGen")
                {
                    if (args.Length == 2)
                    {
                        int  keySize;
                        bool result = int.TryParse(args[1], out keySize);
                        if (result == false || ((keySize % 8) != 0))
                        {
                            Console.WriteLine("Please Enter a valid keySize");
                        }
                        else
                        {
                            KG.generateKeys(keySize);
                            byte[] privateKey_bytes  = KG.getPrivateKey();
                            string privateKey_base64 = Convert.ToBase64String(privateKey_bytes);
                            keySystem.privateKey.key = privateKey_base64;


                            byte[] publicKey_bytes  = KG.getPublicKey();
                            string publicKey_base64 = Convert.ToBase64String(publicKey_bytes);
                            keySystem.publicKey.key = publicKey_base64;

                            keySystem.privateKey.emails.Clear();
                            keySystem.publicKey.email = null;

                            keySystem.writeFiles();
                        }
                    }
                    else
                    {
                        Console.WriteLine("Please enter keyGen <bitsize>");
                    }
                }
                else if (args[0] == "sendKey")
                {
                    string email;
                    if (args.Length == 2)
                    {
                        try
                        {
                            email = args[1];
                            string uri = server_address + "/Key/" + email;

                            Dictionary <string, string> packageJson = new Dictionary <string, string>();
                            packageJson.Add("email", email);
                            packageJson.Add("key", keySystem.publicKey.key);
                            string body = JsonSerializer.Serialize(packageJson);

                            string response_Json = await PutMessage(client, uri, body);

                            //Write files
                            keySystem.publicKey.email = email;
                            if (keySystem.privateKey.emails.Contains(email) == false)
                            {
                                keySystem.privateKey.emails.Add(email);
                            }
                            keySystem.writeFiles();

                            Console.WriteLine("Key saved");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("SendKey Error: {0}", e.Message);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Please enter sendKey <email>");
                    }
                }
                else if (args[0] == "getKey")
                {
                    string email;
                    if (args.Length == 2)
                    {
                        try
                        {
                            email = args[1];
                            string uri           = server_address + "/Key/" + email;
                            string response_Json = await GetMessage(client, uri);

                            Dictionary <string, string> other_key = JsonSerializer.Deserialize <Dictionary <string, string> >(response_Json);
                            // Write File
                            string    keyFileName = email + ".key";
                            PublicKey pubKey      = new PublicKey();
                            pubKey.email = other_key["email"];
                            pubKey.key   = other_key["key"];

                            string otherKeyFileJson = JsonSerializer.Serialize(pubKey);
                            File.WriteAllText(keyFileName, otherKeyFileJson);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("GetKey Exception: {0}", e.Message);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Please enter an email");
                    }
                }
                else if (args[0] == "sendMsg")
                {
                    string email;
                    string message;
                    if (args.Length == 3)
                    {
                        try
                        {
                            email   = args[1];
                            message = args[2];

                            // Check email public key
                            string email_keyFile = email + ".key";
                            if (File.Exists(email_keyFile))
                            {
                                // Get key
                                string keyFile_Json = File.ReadAllText(email_keyFile);
                                Dictionary <string, string> key_dict = JsonSerializer.Deserialize <Dictionary <string, string> >(keyFile_Json);
                                string    pubkey = key_dict["key"];
                                KeyParser kp     = new KeyParser(pubkey, true);
                                kp.parse();

                                // Encryption
                                byte[]     msg_byte = Encoding.ASCII.GetBytes(message);
                                BigInteger M        = new BigInteger(msg_byte);
                                BigInteger C        = RSAEncryptor.RSA_Encrypt(M, kp.E, kp.N);

                                // Encode
                                byte[] C_bytes  = C.ToByteArray();
                                string C_base64 = Convert.ToBase64String(C_bytes);

                                // Load message object
                                Dictionary <string, string> msg_dict = new Dictionary <string, string>();
                                msg_dict.Add("email", email);
                                msg_dict.Add("content", C_base64);
                                string body = JsonSerializer.Serialize(msg_dict);

                                // Send message object
                                string uri           = server_address + "/Message/" + email;
                                string response_Json = await PutMessage(client, uri, body);

                                Console.WriteLine("Message Written");
                            }
                            else
                            {
                                Console.WriteLine("Cannot find the needed public key, please download it first before messaging");
                                Environment.Exit(0);
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("sendMsg Exception: {0}", e.Message);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Please enter: sendMsg <email> <message>");
                    }
                }
                else if (args[0] == "getMsg")
                {
                    string email;
                    if (args.Length == 2)
                    {
                        try
                        {
                            email = args[1];
                            // Validate email
                            if (keySystem.privateKey.emails.Contains(email))
                            {
                                // get json from server
                                string uri           = server_address + "/Message/" + email;
                                string response_Json = await GetMessage(client, uri);

                                Dictionary <string, string> msg_dict = JsonSerializer.Deserialize <Dictionary <string, string> >(response_Json);
                                string msg_raw; // the base64 encrypted msg
                                msg_raw = msg_dict["content"];

                                // Decode raw message
                                byte[]     msg_bytes = Convert.FromBase64String(msg_raw);
                                BigInteger C         = new BigInteger(msg_bytes);

                                // Decryption
                                KeyParser kp = new KeyParser(keySystem.privateKey.key, false);
                                kp.parse();
                                BigInteger M       = RSAEncryptor.RSA_Decrypt(C, kp.D, kp.N);
                                byte[]     M_bytes = M.ToByteArray();
                                string     message = Encoding.ASCII.GetString(M_bytes);

                                Console.WriteLine(message);
                            }
                            else
                            {
                                Console.WriteLine("Cannot find the needed private key.");
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("getMsg Exception: {0}", e.Message);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Please enter: getMsg <email>");
                    }
                }
            }


            //Console.WriteLine("Keysystem.public: " + keySystem.publicKey.key);
            //Console.WriteLine("Keysystem.private: " + keySystem.privateKey.key);
        }