Esempio n. 1
0
 private static byte[] scanKeyFile(CryptobyConsole console)
 {
     scanner = new Scanner(java.lang.System.@in);
     byte[] tempKey = null;
     do
     {
         Console.Out.WriteLine("\nAllowed Key Sizes 128,192 and 256 Bit.");
         Console.Out.WriteLine("Enter Path to Key File (Type '" + quit + "' to Escape):"
                               );
         if (scanner.hasNext(quit))
         {
             aesCrypterFile(console);
         }
         keyPath = scanner.next();
         try
         {
             tempKey = CryptobyFileManager.getKeyFromFile(keyPath);
         }
         catch (System.IO.IOException)
         {
             CryptobyHelper.printIOExp();
             aesCrypterFile(console);
         }
         catch (FormatException)
         {
             Console.Out.WriteLine("Key File format is not correct!");
             aesCrypterFile(console);
         }
         keySize = tempKey.Length * 4;
     }while (keySize != 128 && keySize != 192 && keySize != 256);
     return(tempKey);
 }
Esempio n. 2
0
        public virtual void testRSACrypt1024false()
        {
            System.Console.Out.WriteLine("RSACrypt1024false");
            int            keySize   = 1024;
            CryptobyClient client    = new CryptobyClient();
            CryptobyCore   core      = new CryptobyCore(client);
            KeyGenRSA      generator = new KeyGenRSA(core);

            generator.initGenerator(keySize);
            byte[] plainInput = Encoding.UTF8.GetBytes("Text to Test for Testing from Tester by Testcase"
                                                       );
            string publicKeyString = generator.getPublicKey();

            byte[] publicKey = CryptobyHelper.hexStringToBytes(publicKeyString);
            generator.initGenerator(keySize);
            string privateKeyString = generator.getPrivateKey();

            byte[]   privateKey = CryptobyHelper.hexStringToBytes(privateKeyString);
            CryptRSA rsa        = new CryptRSA();

            byte[] expResult = plainInput;
            byte[] result    = rsa.encrypt(plainInput, publicKey);
            result = rsa.decrypt(result, privateKey);
            NUnit.Framework.Assert.IsFalse(Arrays.equals(expResult, result));
        }
Esempio n. 3
0
 private static void aesEncrypterText(CryptobyConsole console)
 {
     scanner = new Scanner(java.lang.System.@in);
     scanner.useDelimiter("\n");
     // Input your String Text to encrypt
     Console.Out.WriteLine("\nYour Text to encrypt (Type '" + quit + "' to Escape):"
                           );
     if (scanner.hasNext(quit))
     {
         aesCrypterText(console);
     }
     plainByte = Encoding.UTF8.GetBytes(scanner.next());
     // Input your Key for encryption
     key = scanKeyText(console);
     // Initial AES Crypt Object
     initAESKeyGen(console);
     // Encrypt the String Text with given Key
     Console.Out.WriteLine("\nEncrypting in progress...");
     cryptByte = console.getCore().getCryptSym().encrypt(plainByte, key);
     // Convert byte Array into a Hexcode String
     charTextHex = CryptobyHelper.bytesToHexStringUpper(cryptByte).ToCharArray();
     // Print encrypted Text in Hex Block form
     Console.Out.WriteLine("\nEncryption successfull...");
     Console.Out.WriteLine(CryptobyHelper.printHexBlock("AES", keySize, charTextHex
                                                        ));
     // Back to Text Crypter Menu
     Console.Out.WriteLine("\nGo back to AES Text Crypter Menu: Press Enter");
     CryptobyHelper.pressEnter();
     aesCrypterText(console);
 }
Esempio n. 4
0
 private void generateKeys(int keyBitSize)
 {
     keyByteSize = keyBitSize / 8;
     do
     {
         // Generate Primes for Q and P
         // Use Cores parallel, if there are more than 1
         if (cores > 1)
         {
             do
             {
                 BigInteger[] primes = getPrimesParallel(keyBitSize);
                 p = primes[0];
                 q = primes[1];
             }while (p.compareTo(q) == 0);
         }
         else
         {
             do
             {
                 p        = getPrimesParallel(keyBitSize)[0];
                 q        = getPrimesParallel(keyBitSize)[0];
                 log2ofPQ = java.lang.Math.abs(CryptobyHelper.logBigInteger(p) - CryptobyHelper.logBigInteger
                                                   (q));
             }while (log2ofPQ <= 0.1 || log2ofPQ >= 30);
         }
         // Calculate n Module
         calcN();
         // Calculate Phi Module
         calcPhi();
         // Calculate D Module
         calcD();
     }while (n.toByteArray().Length != (keyByteSize) || d.toByteArray().Length != (keyByteSize
                                                                                   ));
 }
Esempio n. 5
0
 /// <summary>Method convert public key String to block format and add a title.</summary>
 /// <remarks>Method convert public key String to block format and add a title.</remarks>
 /// <param name="publicKey">String converted to char array and than to block String</param>
 /// <returns>Return block String of publicKey</returns>
 public static string printPublicKeyBlock(string publicKey)
 {
     java.lang.StringBuilder sb = new java.lang.StringBuilder();
     sb.append("\nPublic Key:\n");
     sb.append(CryptobyHelper.charToBlockString(publicKey.ToCharArray()));
     sb.append(EOB);
     return(sb.ToString());
 }
        public virtual void testPrintPublicKeyBlock()
        {
            System.Console.Out.WriteLine("printPublicKeyBlock");
            string publicKey = "TestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTest";
            string result    = CryptobyHelper.printPublicKeyBlock(publicKey);

            System.Console.Out.WriteLine(result);
        }
Esempio n. 7
0
        /// <summary>Generate a SHA3 Hash/Key depend on password input as String.</summary>
        /// <remarks>Generate a SHA3 Hash/Key depend on password input as String.</remarks>
        /// <param name="keySize">Size of hash. Allowed are 224, 256, 384 and 512.</param>
        /// <param name="password">String password which will be hashed</param>
        /// <returns>SHA3 hash as Hex String</returns>
        public virtual string generateKey(int keySize, string password)
        {
            byte[] bytePW = Encoding.UTF8.GetBytes(password);
            KeyGenSHA3.init(keySize);
            KeyGenSHA3.update(bytePW, bytePW.Length * 8);
            string output = CryptobyHelper.bytesToHexString(KeyGenSHA3.getHash());

            return(output);
        }
Esempio n. 8
0
        /// <summary>This method load a key file from disk to byte array.</summary>
        /// <remarks>
        /// This method load a key file from disk to byte array. They key in the file
        /// must be in Hex String Block format which will be merged and converted
        /// from hex String to byte array as output.
        /// </remarks>
        /// <param name="filePath">Path to key file which bytes will be loaded</param>
        /// <returns>Byte array of hex string in filePath</returns>
        /// <exception cref="System.IO.IOException">
        /// If file not found or other IO problems there will be
        /// throw an IOException
        /// </exception>
        public static byte[] getKeyFromFile(string filePath)
        {
            StreamReader streamReader = new StreamReader(filePath);
            string       sb           = streamReader.ReadToEnd();

            streamReader.Close();
            System.Console.WriteLine(CryptobyHelper.hexStringToBytes(sb));
            return(CryptobyHelper.hexStringToBytes(sb));
        }
Esempio n. 9
0
 private static void rsaDecrypterText(CryptobyConsole console)
 {
     scanner = new Scanner(java.lang.System.@in);
     // Input encrypted Hex String Text to decrypt
     Console.Out.WriteLine("\nYour Text to decrypt (Type '" + quit + "' to Escape):"
                           );
     // Convert crypted HexString Block to one String
     try
     {
         string cryptText = string.Empty;
         while (!scanner.hasNext(CryptobyHelper.getEOBString()))
         {
             if (scanner.hasNext(quit))
             {
                 rsaCrypterText(console);
             }
             cryptText = cryptText + scanner.next();
         }
         cryptByte = CryptobyHelper.hexStringToBytes(cryptText);
     }
     catch (FormatException)
     {
         // Catch false format of Input
         Console.Out.WriteLine("\nNot allowed Crypted Text! Must be a Upper Hex String!"
                               );
         cryptByte = BigInteger.ZERO.toByteArray();
     }
     // Input the Private Key
     privateKeyByte = scanPrivateKey(console);
     // Initial RSA Crypt Object
     initRSAKeyGen(console);
     // Decrypt the String Text with given Key
     Console.Out.WriteLine("\nDecryption in progress...");
     try
     {
         plainByte = console.getCore().getCryptAsym().decrypt(cryptByte, privateKeyByte);
     }
     catch (Exception)
     {
         Console.Out.WriteLine("\nUnable to decrypt this String!!");
         plainByte = null;
         // Press Return for Continues
         CryptobyHelper.pressEnter();
         rsaCrypterText(console);
     }
     Console.Out.WriteLine("\nDecryption finished...");
     // Print decrypted Text
     Console.Out.WriteLine("\nRSA-" + keySize + " decrypted Text:");
     Console.Out.WriteLine(Encoding.UTF8.GetString(plainByte));
     // Reset RSA Crypt Object to release Memory
     initRSAKeyGen(console);
     // Back to Menu rsaCrypter with Enter (Return) Key
     Console.Out.WriteLine("\nGo back to RSA Text Crypter Menu: Press Enter");
     CryptobyHelper.pressEnter();
     rsaCrypterText(console);
 }
Esempio n. 10
0
 /// <summary>
 /// Method merge inputs and add a title to return String which can print
 /// encrypted text and title in User Interfaces.
 /// </summary>
 /// <remarks>
 /// Method merge inputs and add a title to return String which can print
 /// encrypted text and title in User Interfaces.
 /// </remarks>
 /// <param name="cryptType">Type of cryptology implementation as String</param>
 /// <param name="inputKeySize">Size of used key as integer</param>
 /// <param name="inputCharTextHex">
 /// Char array of String which will be converted to
 /// block
 /// </param>
 /// <returns>Return String of merged input parameter and text</returns>
 public static string printHexBlock(string cryptType, int inputKeySize, char[] inputCharTextHex
                                    )
 {
     java.lang.StringBuilder sb = new java.lang.StringBuilder();
     sb.append("\n").append(cryptType).append("-").append(inputKeySize).append(" encrypted Text in Hex form (Copy with '"
                                                                               + EOB + "'):\n");
     sb.append(CryptobyHelper.charToBlockString(inputCharTextHex));
     sb.append(EOB);
     return(sb.ToString());
 }
Esempio n. 11
0
        public virtual void testCharToBlockString()
        {
            System.Console.Out.WriteLine("charToBlockString");
            byte[] cryptByte = Encoding.UTF8.GetBytes("TestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTest"
                                                      );
            char[] charTextHex = CryptobyHelper.bytesToHexStringUpper(cryptByte).ToCharArray(
                );
            string result = CryptobyHelper.charToBlockString(charTextHex);

            System.Console.Out.WriteLine(result);
        }
Esempio n. 12
0
 private static void aesDecrypterText(CryptobyConsole console)
 {
     scanner = new Scanner(java.lang.System.@in);
     // Input encrypted Hex String Text to decrypt
     Console.Out.WriteLine("\nYour Text to decrypt (Type '" + quit + "' to Escape):"
                           );
     // Convert crypted HexString Block to one String
     try
     {
         string cryptText = string.Empty;
         while (!scanner.hasNext(CryptobyHelper.getEOBString()))
         {
             if (scanner.hasNext(quit))
             {
                 aesCrypterText(console);
             }
             cryptText = cryptText + scanner.next();
         }
         cryptByte = CryptobyHelper.hexStringToBytes(cryptText);
     }
     catch (FormatException)
     {
         // Catch false format of Input
         Console.Out.WriteLine("\nNot allowed Crypted Text! Must be a Upper Hex String!"
                               );
         cryptByte = BigInteger.ZERO.toByteArray();
     }
     // Input your Key for encryption
     key = scanKeyText(console);
     // Initial AES Crypt Object
     initAESKeyGen(console);
     // Decrypt the String Text with given Key
     Console.Out.WriteLine("\nDecrypting in progress...");
     try
     {
         plainByte = console.getCore().getCryptSym().decrypt(cryptByte, key);
     }
     catch (Exception)
     {
         Console.Out.WriteLine("\nUnable to decrypt this String!!");
         // Enter for Continues
         CryptobyHelper.pressEnter();
         aesCrypterText(console);
     }
     // Print decrypted Text
     Console.Out.WriteLine("\nDecryption finished...");
     Console.Out.WriteLine("\nAES-" + keySize + " decrypted Text:");
     Console.Out.WriteLine(Encoding.UTF8.GetString(plainByte));
     // Back to Text Crypter Menu
     Console.Out.WriteLine("\nGo back to AES Text Crypter Menu: Press Enter");
     CryptobyHelper.pressEnter();
     aesCrypterText(console);
 }
Esempio n. 13
0
        /// <summary>Generate a random SHA3 Hash/Key as String.</summary>
        /// <remarks>Generate a random SHA3 Hash/Key as String.</remarks>
        /// <param name="keySize">Size of hash. Allowed are 224, 256, 384 and 512.</param>
        /// <returns>SHA3 hash as Hex String</returns>
        public virtual string generateKey(int keySize)
        {
            SecureRandom scRandom = new SecureRandom();

            byte[] randomPW = new byte[40];
            scRandom.nextBytes(randomPW);
            KeyGenSHA3.init(keySize);
            KeyGenSHA3.update(randomPW, randomPW.Length * 8);
            string output = CryptobyHelper.bytesToHexString(KeyGenSHA3.getHash());

            return(output);
        }
Esempio n. 14
0
        /// <param name="console"></param>
        public static void testMillerRabin(CryptobyConsole console)
        {
            Scanner scanner = new Scanner(java.lang.System.@in);
            // Initial Variables
            int        rounds;
            string     percent;
            BigInteger number;

            do
            {
                // Input Number for Primenumber Testing
                System.Console.Out.WriteLine("Set Primenumber to Test.");
                System.Console.Out.Write("Please enter a positive number: ");
                while (!scanner.hasNextBigInteger())
                {
                    System.Console.Out.Write("That's not a number! Enter a positive number: ");
                    scanner.next();
                }
                number = scanner.nextBigInteger();
            }while (number.compareTo(BigInteger.ONE) < 0);
            do
            {
                // Set the rounds of the Miller Rabin Test
                System.Console.Out.WriteLine("Set rounds parameter between 1 and 15.");
                System.Console.Out.Write("Please enter the number of rounds: ");
                while (!scanner.hasNextInt())
                {
                    System.Console.Out.Write("That's not a number! Enter a valid number: ");
                    scanner.next();
                }
                rounds = scanner.nextInt();
            }while (rounds < 1 || rounds > 15);
            // Initial Miller Rabin Object
            console.getCore().getClient().setPrimTestArt("MillerRabin");
            console.getCore().getClient().setPrimetestrounds(rounds);
            console.getCore().initPrimeTest();
            // Get Result of Test
            if (console.getCore().getPrimetest().isPrime(number))
            {
                percent = console.getCore().getPrimetest().getProbability().ToString();
                System.Console.Out.WriteLine("\nResult: Number is probably a Primenumber, probability: "
                                             + percent + "%");
            }
            else
            {
                System.Console.Out.WriteLine("\nResult: Number is NOT a Primenumber");
            }
            // Back to Menu Choose PrimeTest
            System.Console.Out.WriteLine("\nGo back to Primetest Menu: Press Enter");
            CryptobyHelper.pressEnter();
            console.menuPrimeTest();
        }
Esempio n. 15
0
        public virtual void testPrintHexBlock()
        {
            System.Console.Out.WriteLine("printHexBlock");
            byte[] cryptByte = Encoding.UTF8.GetBytes("TestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTest"
                                                      );
            char[] inputCharTextHex = CryptobyHelper.bytesToHexStringUpper(cryptByte).ToCharArray
                                          ();
            string cryptType    = "RSA";
            int    inputKeySize = 1024;
            string result       = CryptobyHelper.printHexBlock(cryptType, inputKeySize, inputCharTextHex
                                                               );

            System.Console.Out.WriteLine(result);
        }
Esempio n. 16
0
        public virtual void testEncryptDecrypt256()
        {
            System.Console.Out.WriteLine("encrypt and decrypt testphrase");
            byte[] plainInput = Encoding.UTF8.GetBytes("Text to Test for Testing from Tester by Testcase"
                                                       );
            KeyGenSHA3 keyGen = new KeyGenSHA3();
            string     hexKey = keyGen.generateKey(256, "password");

            byte[]   bKey     = CryptobyHelper.hexStringToBytes(hexKey);
            CryptAES instance = new CryptAES();

            byte[] expResult = plainInput;
            byte[] result    = instance.encrypt(plainInput, bKey);
            result = instance.decrypt(result, bKey);
            Assert.AreEqual(expResult, result);
        }
Esempio n. 17
0
        public virtual void testEncryptDecrypt256_false()
        {
            System.Console.Out.WriteLine("crypt almost false key");
            byte[] plainInput = Encoding.UTF8.GetBytes("Text to Test for Testing from Tester by Testcase"
                                                       );
            string hexKey = "13A9489AF957FF7B5E8E712737D0B4A0C92AE8EBAE9DD11E9C11B8CB79707017";

            byte[]   bKey     = CryptobyHelper.hexStringToBytes(hexKey);
            CryptAES instance = new CryptAES();

            byte[] expResult = plainInput;
            byte[] result    = instance.encrypt(plainInput, bKey);
            hexKey = "13A9489AF957FF7B5E8E712737D0B4A0C92AE8EBAE9DD11E9C11B8CB79707011";
            bKey   = CryptobyHelper.hexStringToBytes(hexKey);
            result = instance.decrypt(result, bKey);
            Assert.IsFalse(Encoding.UTF8.GetString(expResult).Equals
                               (Encoding.UTF8.GetString(result)));
        }
Esempio n. 18
0
 /// <summary>Generate RSA Private and Public Key with Size of keyBitSize.</summary>
 /// <remarks>Generate RSA Private and Public Key with Size of keyBitSize.</remarks>
 /// <param name="keyBitSize">
 /// Size of RSA key which will be generated. Allowed are
 /// 1024, 2048 and 4096
 /// </param>
 public virtual void initGenerator(int keyBitSize)
 {
     if (keyBitSize != 1024 && keyBitSize != 2048 && keyBitSize != 4096)
     {
         throw new ArgumentException("Just Keys with Size of 1024,2048 or 4096 are allowed!"
                                     );
     }
     generateKeys(keyBitSize);
     // Generate Public Key to Hex String
     pubKeyByte = n.toByteArray();
     pubKey     = CryptobyHelper.bytesToHexString(pubKeyByte);
     byte[] dByte = d.toByteArray();
     privKeyByte = new byte[dByte.Length + pubKeyByte.Length];
     // Copy D ByteArray into first Part and N ByteArray into second Part
     Array.Copy(dByte, 0, privKeyByte, 0, dByte.Length);
     Array.Copy(pubKeyByte, 0, privKeyByte, dByte.Length, pubKeyByte.Length);
     // Generate Private Key to Hex String
     privKey = CryptobyHelper.bytesToHexString(privKeyByte);
 }
Esempio n. 19
0
 private BigInteger[] getPrimesParallel(int keyBitSize)
 {
     System.Threading.Thread[] startThreads = new System.Threading.Thread[cores];
     GenPrimeThread[]          primeThreads = new GenPrimeThread[cores];
     BigInteger[] primes   = new BigInteger[cores];
     BigInteger[] retPrime = new BigInteger[2];
     for (int i = 0; i < cores; i++)
     {
         primeThreads[i] = new GenPrimeThread(core, keyBitSize);
         startThreads[i] = new System.Threading.Thread(new System.Threading.ThreadStart(primeThreads[i].run));
     }
     // Start Threads
     for (int i_1 = 0; i_1 < cores; i_1++)
     {
         startThreads[i_1].Start();
     }
     for (int i_2 = 0; i_2 < cores; i_2++)
     {
         startThreads[i_2].Join();
     }
     for (int i_3 = 0; i_3 < cores; i_3++)
     {
         primes[i_3] = primeThreads[i_3].getPrime();
     }
     for (int i_4 = 0; i_4 < cores; i_4++)
     {
         for (int j = cores - 1; j >= 0; j--)
         {
             log2ofPQ = java.lang.Math.abs(CryptobyHelper.logBigInteger(primes[i_4]) - CryptobyHelper
                                           .logBigInteger(primes[j]));
             if (log2ofPQ >= 0.1 || log2ofPQ <= 30)
             {
                 retPrime[0] = primes[i_4];
                 retPrime[1] = primes[j];
                 return(retPrime);
             }
         }
     }
     retPrime[0] = BigInteger.ZERO;
     retPrime[1] = BigInteger.ZERO;
     return(retPrime);
 }
Esempio n. 20
0
        public virtual void testEncryptDecrypt256_HugeData()
        {
            System.Console.Out.WriteLine("encrypt and decrypt huge Data");
            byte[]     plainInput = new byte[1000000];
            KeyGenSHA3 keyGen     = new KeyGenSHA3();
            string     hexKey     = keyGen.generateKey(256, "password");

            byte[]   bKey     = CryptobyHelper.hexStringToBytes(hexKey);
            CryptAES instance = new CryptAES();

            byte[] expResult = plainInput;
            byte[] result    = instance.encrypt(plainInput, bKey);
            result = instance.decrypt(result, bKey);
            for (int i = 0; i < 10; i++)
            {
                result = instance.encrypt(plainInput, bKey);
                result = instance.decrypt(result, bKey);
            }
            Assert.AreEqual(expResult, result);
        }
Esempio n. 21
0
 // Help Functions
 private static byte[] scanPrivateKey(CryptobyConsole console)
 {
     byte[] retKey = null;
     do
     {
         scanner = new Scanner(java.lang.System.@in);
         string keyText = string.Empty;
         // Input Private Key for decryption
         Console.Out.WriteLine("\nEnter the private Key (Type '" + quit + "' to Escape):"
                               );
         try
         {
             while (!scanner.hasNext(CryptobyHelper.getEOBString()))
             {
                 if (scanner.hasNext(quit))
                 {
                     rsaCrypterText(console);
                 }
                 keyText = keyText + scanner.next();
             }
             retKey  = CryptobyHelper.hexStringToBytes(keyText);
             keySize = retKey.Length * 4;
         }
         catch (FormatException)
         {
             // Catch false format of Input
             Console.Out.WriteLine("Not allowed Characters in Private Key! Just lower alphanumeric Characters!"
                                   );
             retKey  = BigInteger.ZERO.toByteArray();
             keySize = 0;
         }
         catch (ArgumentNullException)
         {
             Console.Out.WriteLine("NullPointerException catched! Try again!");
             retKey  = BigInteger.ZERO.toByteArray();
             keySize = 0;
         }
     }while (keySize != 1024 && keySize != 2048 && keySize != 4096);
     return(retKey);
 }
Esempio n. 22
0
 private static void rsaEncrypterText(CryptobyConsole console)
 {
     // Input your String Text to encrypt
     plainByte = scanPlainText(console);
     // Input the Public Key to encrypt
     publicKeyByte = scanPublicKey(console);
     // Initial RSA Crypt Object
     initRSAKeyGen(console);
     // Encrypt the String Text with given Key
     Console.Out.WriteLine("\nEncryption in progress...");
     cryptByte = console.getCore().getCryptAsym().encrypt(plainByte, publicKeyByte);
     Console.Out.WriteLine("\nEncryption successfull...");
     // Convert byte Array into a Hexcode String
     charTextHex = CryptobyHelper.bytesToHexStringUpper(cryptByte).ToCharArray();
     // Print encrypted Text in Hex Block form
     Console.Out.WriteLine(CryptobyHelper.printHexBlock("RSA", keySize, charTextHex
                                                        ));
     // Back to Menu rsaCrypter with Enter (Return) Key
     Console.Out.WriteLine("\nGo back to RSA Text Crypter Menu: Press Enter");
     CryptobyHelper.pressEnter();
     rsaCrypterText(console);
 }
Esempio n. 23
0
        public virtual void testEncryptDecrypt256_CBC()
        {
            System.Console.Out.WriteLine("encrypt and decrypt recurring words");
            byte[] plainInput = Encoding.UTF8.GetBytes("TestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTest"
                                                       );
            KeyGenSHA3 keyGen = new KeyGenSHA3();
            string     hexKey = keyGen.generateKey(256, "password");

            byte[]   bKey     = CryptobyHelper.hexStringToBytes(hexKey);
            CryptAES instance = new CryptAES();

            byte[] expResult = plainInput;
            byte[] result    = instance.encrypt(plainInput, bKey);
            string resString = CryptobyHelper.bytesToHexStringUpper(result);

            for (int i = 0; i < resString.Length - 32; i += 32)
            {
                Assert.IsFalse(resString.Substring(i, 32).Equals
                                   (resString.Substring(i + 32, 32)));
            }
            result = instance.decrypt(result, bKey);
            Assert.AreEqual(expResult, result);
        }
Esempio n. 24
0
 private static void aesEncrypterFile(CryptobyConsole console)
 {
     // Input Path to File for encryption
     scanner = new Scanner(java.lang.System.@in);
     Console.Out.WriteLine("Enter Path to File for encryption (Type '" + quit +
                           "' to Escape):");
     scanner.useDelimiter("\n");
     if (scanner.hasNext(quit))
     {
         aesCrypterFile(console);
     }
     plainFilePath = scanner.next();
     // Get Bytes from PlainFile
     try
     {
         plainByte = CryptobyFileManager.getBytesFromFile(plainFilePath);
     }
     catch (System.IO.IOException)
     {
         CryptobyHelper.printIOExp();
         aesCrypterFile(console);
     }
     // Input Path saving Path
     scanner = new Scanner(java.lang.System.@in);
     Console.Out.WriteLine("Enter Path to save encrypted File (Type '" + quit +
                           "' to Escape):");
     scanner.useDelimiter("\n");
     if (scanner.hasNext(quit))
     {
         aesCrypterFile(console);
     }
     cryptFilePath = scanner.next();
     // Input Key File for encryption
     key = scanKeyFile(console);
     // Initial AES Crypt Object
     initAESKeyGen(console);
     // Encrypt the String Text with given Key
     Console.Out.WriteLine("\nEncrypting in progress...");
     cryptByte = console.getCore().getCryptSym().encrypt(plainByte, key);
     Console.Out.WriteLine("\nEncryption successfull. Saving File now...");
     //Put encrypted Bytes to File
     try
     {
         CryptobyFileManager.putBytesToFile(cryptFilePath, cryptByte);
     }
     catch (System.IO.IOException ex)
     {
         Logger.getLogger(typeof(RsaUI).FullName).log(Level.SEVERE, null, ex);
     }
     Console.Out.WriteLine("\nEncrypted File saved to this Path:");
     Console.Out.WriteLine(cryptFilePath);
     // Reset Variables
     initAESKeyGen(console);
     cryptByte = null;
     plainByte = null;
     key       = null;
     // Back to File Crypter Menu
     Console.Out.WriteLine("\nGo back to AES File Crypter Menu: Press Enter");
     CryptobyHelper.pressEnter();
     aesCrypterFile(console);
 }
Esempio n. 25
0
 private static void aesDecrypterFile(CryptobyConsole console)
 {
     // Input Path to File for decryption
     scanner = new Scanner(java.lang.System.@in);
     Console.Out.WriteLine("Enter Path to decrypt a File (Type '" + quit + "' to Escape):"
                           );
     scanner.useDelimiter("\n");
     if (scanner.hasNext(quit))
     {
         aesCrypterFile(console);
     }
     cryptFilePath = scanner.next();
     try
     {
         // Get Bytes from PlainFile
         cryptByte = CryptobyFileManager.getBytesFromFile(cryptFilePath);
     }
     catch (System.IO.IOException)
     {
         CryptobyHelper.printIOExp();
         aesCrypterFile(console);
     }
     // Input Path saving Path
     scanner = new Scanner(java.lang.System.@in);
     Console.Out.WriteLine("Enter Path to save decrypted File (Type '" + quit +
                           "' to Escape):");
     scanner.useDelimiter("\n");
     if (scanner.hasNext(quit))
     {
         aesCrypterFile(console);
     }
     plainFilePath = scanner.next();
     // Input your Key for encryption
     key = scanKeyFile(console);
     // Initial AES Crypt Object
     initAESKeyGen(console);
     // Decrypt the String Text with given Key
     Console.Out.WriteLine("\nDecrypting in progress...");
     try
     {
         plainByte = console.getCore().getCryptSym().decrypt(cryptByte, key);
     }
     catch (Exception)
     {
         Console.Out.WriteLine("\nUnable to decrypt this String!!");
         // Enter for Continues
         CryptobyHelper.pressEnter();
         aesCrypterFile(console);
     }
     Console.Out.WriteLine("\nDecryption finished. Saving File now...");
     try
     {
         //Put encrypted Bytes to File
         CryptobyFileManager.putBytesToFile(plainFilePath, plainByte);
     }
     catch (System.IO.IOException)
     {
         CryptobyHelper.printIOExp();
         aesCrypterFile(console);
     }
     Console.Out.WriteLine("\nDecrypted File saved to this Path:");
     Console.Out.WriteLine(plainFilePath);
     // Reset Variables
     initAESKeyGen(console);
     cryptByte = null;
     plainByte = null;
     key       = null;
     // Back to File Crypter Menu
     Console.Out.WriteLine("\nGo back to AES File Crypter Menu: Press Enter");
     CryptobyHelper.pressEnter();
     aesCrypterFile(console);
 }
Esempio n. 26
0
        /// <param name="console"></param>
        public static void genSHA3KeyText(CryptobyConsole console)
        {
            Scanner scanner = new Scanner(java.lang.System.@in);
            // Initial Variables
            int    keySize;
            int    choice;
            string pwAns;
            string key;
            string password;

            // Set Default Key Size
            keySize = 256;
            do
            {
                Console.Out.WriteLine("\n");
                Console.Out.WriteLine("Select Key Size in Bit");
                Console.Out.WriteLine("----------------------\n");
                Console.Out.WriteLine("1 - 224");
                Console.Out.WriteLine("2 - 256");
                Console.Out.WriteLine("3 - 384");
                Console.Out.WriteLine("4 - 512");
                Console.Out.WriteLine("5 - Back");
                Console.Out.Write("Enter Number: ");
                while (!scanner.hasNextInt())
                {
                    Console.Out.WriteLine("That's not a number! Enter 1,2,3,4 or 5:");
                    scanner.next();
                }
                choice = scanner.nextInt();
            }while (choice < 1 || choice > 5);
            switch (choice)
            {
            case 1:
            {
                keySize = 224;
                break;
            }

            case 2:
            {
                keySize = 256;
                break;
            }

            case 3:
            {
                keySize = 384;
                break;
            }

            case 4:
            {
                keySize = 512;
                break;
            }

            case 5:
            {
                console.menuGenKey();
                break;
            }

            default:
            {
                console.menuGenKey();
                break;
            }
            }
            do
            {
                // Input a Password or nothing, in the case it will be used a Secure Random number
                Console.Out.WriteLine("Do you want to use a password. If not, it will be used a SecureRandom password."
                                      );
                Console.Out.Write("Enter y or n: ");
                pwAns = scanner.next();
            }while (!pwAns.Equals("y") && !pwAns.Equals("n"));
            if (pwAns.Equals("y"))
            {
                Console.Out.Write("Enter Password for the Key: ");
                password = scanner.next();
            }
            else
            {
                password = string.Empty;
            }
            // Initial Key Generator
            console.getCore().getClient().setKeySymArt("SHA3");
            console.getCore().initSymKey();
            // Get Result of Test
            if (password.Equals(string.Empty))
            {
                key = console.getCore().getKeyGenSym().generateKey(keySize);
            }
            else
            {
                key = console.getCore().getKeyGenSym().generateKey(keySize, password);
            }
            // Print Key
            Console.Out.WriteLine("SHA3-" + keySize + ": " + key);
            // Enter for Continues
            CryptobyHelper.pressEnter();

            // Back to Menu Choose PrimeTest
            console.menuGenKey();
        }
Esempio n. 27
0
        /// <summary>Encrypt a byte array in blocks with AES algorithm in CBC mode.</summary>
        /// <remarks>Encrypt a byte array in blocks with AES algorithm in CBC mode.</remarks>
        /// <param name="plainInput">Plain byte array to encrypt</param>
        /// <param name="key">256 Bit key to encrypt plainInput</param>
        /// <returns>Return encrypted byte array</returns>
        public virtual byte[] encrypt(byte[] plainInput, byte[] key)
        {
            int inputLength = plainInput.Length;
            int percentProgress;
            int prevPercent = -1;

            byte[] inputLengthByte = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(inputLength).array();
            int    restInput       = plainInput.Length % nBytes;

            byte[] exKey        = initKeyExpand(key);
            byte[] cipher       = new byte[nBytes];
            byte[] cryptOutput  = new byte[(inputLength - restInput) + nBytes * 2];
            int    outputLength = cryptOutput.Length;

            byte[]       initVector = new byte[nBytes];
            byte[]       nextBlock  = new byte[nBytes];
            SecureRandom scRandom   = new SecureRandom();

            // Copy plaintext Array into crypt Array
            System.Array.Copy(plainInput, 0, cryptOutput, 0, inputLength);
            // Fill Initialization Vector with Random Bytes
            scRandom.nextBytes(initVector);
            // Copy first Input Block to nextBlock
            System.Array.Copy(cryptOutput, 0, nextBlock, 0, nBytes);
            // XOR Random initVektor with first Input Block
            nextBlock = CryptobyHelper.xorByteArrays(nextBlock, initVector);
            // Copy xored prevBlock into first Input Block
            System.Array.Copy(nextBlock, 0, cryptOutput, 0, nBytes);
            // Encrypt last BlockArray
            initVector = encryptCipher(initVector, exKey);
            // Add the initVector Array in to last BlockArray and encrypt it
            System.Array.Copy(initVector, 0, cryptOutput, outputLength - nBytes, nBytes);
            // Add in the first Byte after CryptText the origin length of plaintext Array
            System.Array.Copy(inputLengthByte, 0, cryptOutput, outputLength - nBytes * 2, 4);
            // Encrypt every Block in CBC Mode
            for (int i = 0; i < outputLength - nBytes; i += nBytes)
            {
                // Convert i to percent for ProgressBar
//				percentProgress = (int)(((float)i / (float)(outputLength - nBytes)) * 100);
//				// Print ProgressBar
//				if (percentProgress > prevPercent)
//				{
//					CryptobyHelper.printProgressBar(percentProgress);
//				}
//				prevPercent = percentProgress;
                // Copy current block in to Cipher Array
                System.Array.Copy(nextBlock, 0, cipher, 0, nBytes);
                // Encrypt Cipher
                cipher = this.encryptCipher(cipher, exKey);
                // CBC Mode: XOR next PlainBlock with encrypted Cipher
                if (i + nBytes < outputLength)
                {
                    System.Array.Copy(cryptOutput, i + nBytes, nextBlock, 0, nBytes);
                    nextBlock = CryptobyHelper.xorByteArrays(nextBlock, cipher);
                }
                // Copy Cipher back in decryptOutput Array
                System.Array.Copy(cipher, 0, cryptOutput, i, nBytes);
            }
//			CryptobyHelper.printProgressBar(100);
            return(cryptOutput);
        }
Esempio n. 28
0
        /// <summary>Decrypt a byte array in blocks with AES algorithm in CBC mode.</summary>
        /// <remarks>Decrypt a byte array in blocks with AES algorithm in CBC mode.</remarks>
        /// <param name="cryptInput">Encrypted byte array to decrypt</param>
        /// <param name="key">256 Bit key to decrypt cryptInput</param>
        /// <returns>Return decrypted byte array</returns>
        public virtual byte[] decrypt(byte[] cryptInput, byte[] key)
        {
            int percentProgress;
            int prevPercent = -1;

            byte[] exKey        = initKeyExpand(key);
            int    outputLength = cryptInput.Length;

            byte[] decryptOutput = new byte[outputLength];
            System.Array.Copy(cryptInput, 0, decryptOutput, 0, outputLength);
            byte[] cipher          = new byte[nBytes];
            byte[] inputLengthByte = new byte[nBytes];
            byte[] plainOutput;
            byte[] initVector = new byte[nBytes];
            byte[] prevBlock  = new byte[nBytes];
            // Add the initVector Array in to last BlockArray and encrypt it
            System.Array.Copy(decryptOutput, outputLength - nBytes, initVector, 0, nBytes);
            // Decrypt last BlockArray
            initVector = this.decryptCipher(initVector, exKey);
            // Copy initVector to prevBlock Array
            System.Array.Copy(initVector, 0, prevBlock, 0, nBytes);
            for (int i = 0; i < outputLength - nBytes; i += nBytes)
            {
//				// Convert i to percent for ProgressBar
//				percentProgress = (int)(((float)i / (float)(outputLength - nBytes)) * 100);
//				// Print ProgressBar
//				if (percentProgress > prevPercent)
//				{
//					CryptobyHelper.printProgressBar(percentProgress);
//				}
//				prevPercent = percentProgress;
                // Copy current block in to Cipher Array
                System.Array.Copy(decryptOutput, i, cipher, 0, nBytes);
                // Decrypt Cipher
                cipher = this.decryptCipher(cipher, exKey);
                // CBC Mode: XOR next PlainBlock with encrypted Cipher
                if (i + nBytes < outputLength)
                {
                    cipher = CryptobyHelper.xorByteArrays(prevBlock, cipher);
                    System.Array.Copy(decryptOutput, i, prevBlock, 0, nBytes);
                }
                // Copy Cipher back in current decryptOutput Array
                System.Array.Copy(cipher, 0, decryptOutput, i, nBytes);
            }
            // Read last Index of encryptet Output
            // and use the Integer Content for lenght of plainOutput
            System.Array.Copy(decryptOutput, outputLength - nBytes * 2, inputLengthByte, 0, 4);
            int lengthOriginArray = ByteBuffer.wrap(inputLengthByte).order(ByteOrder.BIG_ENDIAN
                                                                           ).getInt();

            try
            {
                plainOutput = new byte[lengthOriginArray];
                System.Array.Copy(decryptOutput, 0, plainOutput, 0, lengthOriginArray);
            }
            catch (Exception)
            {
                plainOutput = cryptInput;
            }
//			CryptobyHelper.printProgressBar(100);
            return(plainOutput);
        }
Esempio n. 29
0
 private static void rsaDecrypterFile(CryptobyConsole console)
 {
     // Input Path to File for decryption
     scanner = new Scanner(java.lang.System.@in);
     Console.Out.WriteLine("Enter Path to File for Decryption (Type '" + quit +
                           "' to Escape):");
     scanner.useDelimiter("\n");
     if (scanner.hasNext(quit))
     {
         rsaCrypterFile(console);
     }
     cryptFilePath = scanner.next();
     // Get Bytes from PlainFile
     try
     {
         cryptByte = CryptobyFileManager.getBytesFromFile(cryptFilePath);
     }
     catch (System.IO.IOException)
     {
         CryptobyHelper.printIOExp();
         rsaCrypterFile(console);
     }
     // Input Path saving Path
     scanner = new Scanner(java.lang.System.@in);
     Console.Out.WriteLine("Enter saving Path for decrypted File (Type '" + quit
                           + "' to Escape):");
     scanner.useDelimiter("\n");
     if (scanner.hasNext(quit))
     {
         rsaCrypterFile(console);
     }
     plainFilePath = scanner.next();
     // Input Path to Key File for decryption
     scanner = new Scanner(java.lang.System.@in);
     Console.Out.WriteLine("Enter Path to Private Key File (Type '" + quit + "' to Escape):"
                           );
     scanner.useDelimiter("\n");
     if (scanner.hasNext(quit))
     {
         rsaCrypterFile(console);
     }
     privateKeyPath = scanner.next();
     // Get Bytes from Private Key File
     try
     {
         privateKeyByte = CryptobyFileManager.getKeyFromFile(privateKeyPath);
     }
     catch (System.IO.IOException)
     {
         CryptobyHelper.printIOExp();
         rsaCrypterFile(console);
     }
     catch (FormatException)
     {
         Console.Out.WriteLine("Key File format is not correct!");
         rsaCrypterFile(console);
     }
     // Initial RSA Crypt Object
     initRSAKeyGen(console);
     // Encrypt the File with given Key
     Console.Out.WriteLine("\nDecryption in progress...");
     try
     {
         plainByte = console.getCore().getCryptAsym().decrypt(cryptByte, privateKeyByte);
     }
     catch (Exception)
     {
         Console.Out.WriteLine("\nUnable to decrypt this File!!");
         plainByte = null;
         // Press Return for Continues
         CryptobyHelper.pressEnter();
         rsaCrypterFile(console);
     }
     Console.Out.WriteLine("\nDecryption finished. Saving File now...");
     try
     {
         //Put encrypted Bytes to File
         CryptobyFileManager.putBytesToFile(plainFilePath, plainByte);
     }
     catch (System.IO.IOException)
     {
         CryptobyHelper.printIOExp();
         rsaCrypterFile(console);
     }
     Console.Out.WriteLine("\nDecrypted File saved to this Path:");
     Console.Out.WriteLine(plainFilePath);
     // Reset Variables
     initRSAKeyGen(console);
     cryptByte     = null;
     plainByte     = null;
     publicKeyByte = null;
     // Back to Menu rsaCrypter with Enter (Return) Key
     Console.Out.WriteLine("\nGo back to RSA File Crypter Menu: Press Enter");
     CryptobyHelper.pressEnter();
     rsaCrypterFile(console);
 }
Esempio n. 30
0
        private static void rsaEncGenKeysText(CryptobyConsole console)
        {
            scanner = new Scanner(java.lang.System.@in);
            string privateKey;
            string publicKey;

            // Set Default Key Size
            keySize = 1024;
            do
            {
                Console.Out.WriteLine("\n");
                Console.Out.WriteLine("Choose Key Size in Bit");
                Console.Out.WriteLine("----------------------\n");
                Console.Out.WriteLine("1 - 1024");
                Console.Out.WriteLine("2 - 2048");
                Console.Out.WriteLine("3 - 4096");
                Console.Out.WriteLine("4 - Back");
                Console.Out.Write("Enter Number: ");
                while (!scanner.hasNextInt())
                {
                    Console.Out.Write("That's not a number! Enter 1,2,3 or 4: ");
                    scanner.next();
                }
                choice = scanner.nextInt();
            }while (choice < 1 || choice > 4);
            switch (choice)
            {
            case 1:
            {
                keySize = 1024;
                break;
            }

            case 2:
            {
                keySize = 2048;
                break;
            }

            case 3:
            {
                keySize = 4096;
                break;
            }

            case 4:
            {
                rsaCrypterText(console);
                break;
            }

            default:
            {
                rsaEncGenKeysText(console);
                break;
            }
            }
            // Input your String Text to encrypt
            plainByte = scanPlainText(console);
            // Initial RSA Crypt Object
            initRSAKeyGen(console);
            // Get Public Key in Bytecode
            Console.Out.WriteLine("\nGenerate Private and Public RSA Keys...");
            console.getCore().getKeyGenAsym().initGenerator(keySize);
            publicKeyByte = console.getCore().getKeyGenAsym().getPublicKeyByte();
            // Get Public and Private Key as String
            publicKey  = console.getCore().getKeyGenAsym().getPublicKey();
            privateKey = console.getCore().getKeyGenAsym().getPrivateKey();
            // Encrypt the String Text with given Key
            Console.Out.WriteLine("\nEncryption in progress...");
            cryptByte = console.getCore().getCryptAsym().encrypt(plainByte, publicKeyByte);
            Console.Out.WriteLine("\nEncryption successfull...");
            // Convert crypted byte Array into a Hexcode String
            charTextHex = CryptobyHelper.bytesToHexStringUpper(cryptByte).ToCharArray();
            // Print encrypted Text in Hex Block form
            Console.Out.WriteLine(CryptobyHelper.printHexBlock("RSA", keySize, charTextHex
                                                               ));
            // Print Private Keys
            Console.Out.WriteLine(CryptobyHelper.printPrivateKeyBlock(privateKey));
            // Print Public Keys
            Console.Out.WriteLine(CryptobyHelper.printPublicKeyBlock(publicKey));
            // Back to Menu rsaCrypter with Enter (Return) Key
            Console.Out.WriteLine("\nGo back to RSA Text Crypter Menu: Press Enter");
            CryptobyHelper.pressEnter();
            rsaCrypterText(console);
        }