//private void GetDigitsAndBitsWithTimeOut(out int digits, out int bits) //{ // int[] result = null; // var tokenSource = new CancellationTokenSource(); // CancellationToken token = tokenSource.Token; // int timeOut = 500; // milliseconds // bool success; // var task = Task.Factory.StartNew(() => result = GetDigitsAndBits(), token); // success = task.Wait(timeOut, token); // if (!success) // throw new OverflowException(); // digits = result[0]; // bits = result[1]; //} private BigInteger GetNumber() { //The input from the taskpane is converted to a BigNumber and is sent to the output. if (settings.Number == null || settings.Number.Equals("")) { return(BigInteger.Zero); } return(BigIntegerHelper.ParseExpression(settings.Number)); }
public void Execute() { BigInteger m, k; ProgressChanged(0, 1); if (x == null || Messages == null) { GuiLogMessage("Illegal array 'x' or 'messages'.", NotificationLevel.Error); return; } if (x.Length != Messages.Length) { GuiLogMessage("Arrays 'x' and 'messages' must have the same number of entries.", NotificationLevel.Error); return; } EncryptedMessages = new BigInteger[x.Length]; for (int i = 0; i < Messages.Length; i++) { try // can be read as parseable expression? { m = BigIntegerHelper.ParseExpression(Messages[i]); } catch (Exception ex) { GuiLogMessage("Error while converting '" + Messages[i] + "' to a number.", NotificationLevel.Error); return; } k = BigInteger.ModPow(((v - x[i]) % N + N) % N, d, N); EncryptedMessages[i] = (m + k) % N; ProgressChanged(i + 1, Messages.Length); } OnPropertyChanged("EncryptedMessages"); }
/// <summary> /// Called by the environment to start generating of public/private keys /// </summary> public void Execute() { BigInteger p; BigInteger q; BigInteger n; BigInteger e; BigInteger d; ProgressChanged(0.0, 1.0); switch (settings.Source) { // manual case 0: try { p = BigIntegerHelper.ParseExpression(settings.P); q = BigIntegerHelper.ParseExpression(settings.Q); e = BigIntegerHelper.ParseExpression(settings.E); if (!BigIntegerHelper.IsProbablePrime(p)) { GuiLogMessage(p.ToString() + " is not prime!", NotificationLevel.Error); return; } if (!BigIntegerHelper.IsProbablePrime(q)) { GuiLogMessage(q.ToString() + " is not prime!", NotificationLevel.Error); return; } if (p == q) { GuiLogMessage("The primes P and Q can not be equal!", NotificationLevel.Error); return; } } catch (Exception ex) { GuiLogMessage("Invalid Big Number input: " + ex.Message, NotificationLevel.Error); return; } try { D = BigIntegerHelper.ModInverse(e, (p - 1) * (q - 1)); } catch (Exception) { GuiLogMessage("RSAKeyGenerator Error: E (" + e + ") can not be inverted.", NotificationLevel.Error); return; } try { N = p * q; E = e; } catch (Exception ex) { GuiLogMessage("Big Number fail: " + ex.Message, NotificationLevel.Error); return; } break; case 1: try { n = BigIntegerHelper.ParseExpression(settings.N); d = BigIntegerHelper.ParseExpression(settings.D); e = BigIntegerHelper.ParseExpression(settings.E); } catch (Exception ex) { GuiLogMessage("Invalid Big Number input: " + ex.Message, NotificationLevel.Error); return; } try { N = n; E = e; D = d; } catch (Exception ex) { GuiLogMessage("Big Number fail: " + ex.Message, NotificationLevel.Error); return; } break; //randomly generated case 2: try { n = BigInteger.Parse(this.settings.Range); switch (this.settings.RangeType) { case 0: // n = number of bits for primes if ((int)n <= 2) { GuiLogMessage("Value for n has to be greater than 2.", NotificationLevel.Error); return; } if (n >= 1024) { GuiLogMessage("Please note that the generation of prime numbers with " + n + " bits may take some time...", NotificationLevel.Warning); } // calculate the number of expected tries for the indeterministic prime number generation using the density of primes in the given region BigInteger limit = ((BigInteger)1) << (int)n; limittries = (int)(BigInteger.Log(limit) / 6); expectedtries = 2 * limittries; tries = 0; p = this.RandomPrimeBits((int)n); tries = limittries; limittries = expectedtries; do { q = this.RandomPrimeBits((int)n); } while (p == q); break; case 1: // n = upper limit for primes default: if (n <= 4) { GuiLogMessage("Value for n has to be greater than 4", NotificationLevel.Error); return; } p = BigIntegerHelper.RandomPrimeLimit(n + 1); ProgressChanged(0.5, 1.0); do { q = BigIntegerHelper.RandomPrimeLimit(n + 1); } while (p == q); break; } } catch { GuiLogMessage("Please enter an integer value for n.", NotificationLevel.Error); return; } BigInteger phi = (p - 1) * (q - 1); // generate E for the given values of p and q bool found = false; foreach (var ee in new BigInteger[] { 3, 5, 7, 11, 17, 65537 }) { if (ee < phi && ee.GCD(phi) == 1) { E = ee; found = true; break; } } if (!found) { for (int i = 0; i < 1000; i++) { e = BigIntegerHelper.RandomIntLimit(phi); if (e >= 2 && e.GCD(phi) == 1) { E = e; found = true; break; } } } if (!found) { GuiLogMessage("Could not generate a valid E for p=" + p + " and q=" + q + ".", NotificationLevel.Error); return; } N = p * q; D = BigIntegerHelper.ModInverse(E, phi); break; //using x509 certificate case 3: try { X509Certificate2 cert; RSAParameters par; if (this.settings.Password != "") { GuiLogMessage("Password entered. Try getting public and private key", NotificationLevel.Info); cert = new X509Certificate2(settings.CertificateFile, settings.Password, X509KeyStorageFlags.Exportable); if (cert == null || cert.PrivateKey == null) { throw new Exception("Private Key of X509Certificate could not be fetched"); } RSACryptoServiceProvider provider = (RSACryptoServiceProvider)cert.PrivateKey; par = provider.ExportParameters(true); } else { GuiLogMessage("No Password entered. Try loading public key only", NotificationLevel.Info); cert = new X509Certificate2(settings.CertificateFile); if (cert == null || cert.PublicKey == null || cert.PublicKey.Key == null) { throw new Exception("Private Key of X509Certificate could not be fetched"); } RSACryptoServiceProvider provider = (RSACryptoServiceProvider)cert.PublicKey.Key; par = provider.ExportParameters(false); } try { N = new BigInteger(par.Modulus); } catch (Exception ex) { GuiLogMessage("Could not get N from certificate: " + ex.Message, NotificationLevel.Warning); } try { E = new BigInteger(par.Exponent); } catch (Exception ex) { GuiLogMessage("Could not get E from certificate: " + ex.Message, NotificationLevel.Warning); } try { if (this.settings.Password != "") { D = new BigInteger(par.D); } else { D = 0; } } catch (Exception ex) { GuiLogMessage("Could not get D from certificate: " + ex.Message, NotificationLevel.Warning); } } catch (Exception ex) { GuiLogMessage("Could not load the selected certificate: " + ex.Message, NotificationLevel.Error); } break; } ProgressChanged(1.0, 1.0); }
public bool ConvertToOutput(object input) { if (input == null) { return(false); } #region ConvertFromTypes #region ConvertFromICryptoolStream if (input is ICryptoolStream) { switch (this.settings.Converter) { case OutputTypes.CryptoolStreamType: { Output = (ICryptoolStream)input; break; } case OutputTypes.StringType: { byte[] buffer = ICryptoolStreamToByteArray((ICryptoolStream)input); Output = GetStringForEncoding(buffer, settings.InputEncoding); break; } case OutputTypes.ByteArrayType: { Output = ICryptoolStreamToByteArray((ICryptoolStream)input); break; } case OutputTypes.BigIntegerType: { byte[] buffer = ICryptoolStreamToByteArray((ICryptoolStream)input); Output = ByteArrayToBigInteger(buffer, settings.Endianness); break; } default: GuiLogMessage("Conversion from " + input.GetType() + " to " + GetType(settings.Converter) + " is not implemented", NotificationLevel.Error); return(false); } return(true); } #endregion #region ConvertFromIntArray else if (input is int[]) { GuiLogMessage("Conversion from int[] to the chosen type is not implemented", NotificationLevel.Error); return(false); } #endregion #region ConvertFromByteArray else if (input is byte[]) { switch (this.settings.Converter) { case OutputTypes.BigIntegerType: // byte[] to BigInteger { byte[] temp = (byte[])input; Output = ByteArrayToBigInteger(temp, settings.Endianness); return(true); } case OutputTypes.IntType: // byte[] to int { try { byte[] temp = new byte[4]; Array.Copy((byte[])input, temp, 4); if (settings.Endianness) { Array.Reverse(temp); } Output = BitConverter.ToInt32(temp, 0); return(true); } catch (Exception e) { GuiLogMessage("Could not convert byte[] to integer: " + e.Message, NotificationLevel.Error); return(false); } } case OutputTypes.ShortType: // byte[] to short { try { byte[] temp = new byte[2]; Array.Copy((byte[])input, temp, 2); if (settings.Endianness) { Array.Reverse(temp); } Output = BitConverter.ToInt16(temp, 0); return(true); } catch (Exception e) { GuiLogMessage("Could not convert byte[] to short: " + e.Message, NotificationLevel.Error); return(false); } } case OutputTypes.ByteType: // byte[] to byte { try { Output = ((byte[])input)[0]; return(true); } catch (Exception e) { GuiLogMessage("Could not convert byte[] to byte: " + e.Message, NotificationLevel.Error); return(false); } } case OutputTypes.StringType: // byte[] to String { Output = GetStringForEncoding((byte[])input, settings.InputEncoding); return(true); } case OutputTypes.ByteArrayType: // byte[] to byte[] { Output = (byte[])input; return(true); } } } #endregion #region ConvertFromBigInteger else if (input is BigInteger) { if (this.settings.Converter == OutputTypes.ByteArrayType) { Output = ((BigInteger)input).ToByteArray(); return(true); } try { Output = ((BigInteger)input).ToString(this.settings.Format); return(true); } catch (FormatException ex) { ShowFormatErrorMessage(ex); } } #endregion #region ConvertFromInt else if (input is int) { if (this.settings.Converter == OutputTypes.ByteArrayType) { Output = BitConverter.GetBytes((int)input); return(true); } try { Output = ((int)input).ToString(this.settings.Format); return(true); } catch (FormatException ex) { ShowFormatErrorMessage(ex); } } #endregion #region ConvertFromShort else if (input is short) { if (this.settings.Converter == OutputTypes.ByteArrayType) { Output = BitConverter.GetBytes((short)input); return(true); } if (this.settings.Converter == OutputTypes.StringType && !string.IsNullOrEmpty(this.settings.Format)) { try { Output = ((short)input).ToString(this.settings.Format); return(true); } catch (FormatException ex) { ShowFormatErrorMessage(ex); } } } #endregion #region ConvertFromByte else if (input is byte) { if (this.settings.Converter == OutputTypes.ByteArrayType) { Output = new byte[] { (byte)input }; return(true); } if (this.settings.Converter == OutputTypes.StringType && !string.IsNullOrEmpty(this.settings.Format)) { try { Output = ((byte)input).ToString(this.settings.Format); return(true); } catch (FormatException ex) { ShowFormatErrorMessage(ex); } } } #endregion #region ConvertFromDouble else if (input is Double) { if (this.settings.Converter == OutputTypes.ByteArrayType) { Output = BitConverter.GetBytes((Double)input); return(true); } if (this.settings.Converter == OutputTypes.StringType && !string.IsNullOrEmpty(this.settings.Format)) { try { Output = ((double)input).ToString(this.settings.Format); return(true); } catch (FormatException ex) { ShowFormatErrorMessage(ex); } } } #endregion #region ConvertFromBool else if (input is bool) { switch (this.settings.Converter) { case OutputTypes.BooleanType: Output = input; return(true); case OutputTypes.StringType: Output = input.ToString(); return(true); case OutputTypes.IntType: Output = (int)((bool)input ? 1 : 0); return(true); case OutputTypes.ShortType: Output = (short)((bool)input ? 1 : 0); return(true); case OutputTypes.ByteType: Output = (byte)((bool)input ? 1 : 0); return(true); case OutputTypes.ByteArrayType: Output = new byte[] { (byte)(((bool)input) ? 1 : 0) }; return(true); case OutputTypes.BigIntegerType: Output = (BigInteger)((bool)input ? 1 : 0); return(true); case OutputTypes.DoubleType: Output = (Double)((bool)input ? 1 : 0); return(true); case OutputTypes.CryptoolStreamType: Output = new byte[] { (byte)(((bool)input) ? 1 : 0) }; return(true); default: GuiLogMessage("Could not convert from bool to chosen type: ", NotificationLevel.Error); return(false); } } #endregion #endregion if (input is string[]) { string[] inputarray = (string[])input; if (this.settings.Converter == OutputTypes.BooleanType) { bool[] result = new bool[inputarray.Length]; for (int i = 0; i < inputarray.Length; i++) { result[i] = inputarray[i] == "1"; } Output = result; return(true); } if (this.settings.Converter == OutputTypes.BigIntegerType) { BigInteger[] result = new BigInteger[inputarray.Length]; try // can be read as parseable expression? { for (int i = 0; i < inputarray.Length; i++) { result[i] = BigIntegerHelper.ParseExpression(inputarray[i]); } } catch (Exception) { GuiLogMessage("Could not convert input to BigInteger", NotificationLevel.Error); return(false); } Output = result; return(true); } } // the string representation is used for all upcoming operations string inpString = Convert.ToString(input); #region ConvertFromString switch (this.settings.Converter) // convert to what? { #region ConvertToString case OutputTypes.StringType: { if (settings.Numeric) { try // can be read as parseable expression? { Output = BigIntegerHelper.ParseExpression(inpString).ToString(); return(true); } catch (Exception) { } } Output = inpString; return(true); } #endregion #region ConvertToInt case OutputTypes.IntType: { try // can be read as int from decimal string? { Output = Convert.ToInt32(inpString); return(true); } catch (Exception e) { } try // can be read as int from hexadecimal string? { Output = Convert.ToInt32(inpString, 16); return(true); } catch (Exception e) { GuiLogMessage("Could not convert input to integer: " + e.Message, NotificationLevel.Error); return(false); } } #endregion #region ConvertToShort case OutputTypes.ShortType: { try // can be read as short from decimal string? { Output = Convert.ToInt16(inpString); return(true); } catch (Exception e) { } try // can be read as short from hexadecimal string? { Output = Convert.ToInt16(inpString, 16); return(true); } catch (Exception e) { GuiLogMessage("Could not convert input to short: " + e.Message, NotificationLevel.Error); return(false); } } #endregion #region ConvertToByte case OutputTypes.ByteType: { try // can be read as byte from decimal string? { Output = Convert.ToByte(inpString); return(true); } catch (Exception e) { } try // can be read as byte hexadecimal string? { Output = Convert.ToByte(inpString, 16); return(true); } catch (Exception e) { GuiLogMessage("Could not convert input to byte: " + e.Message, NotificationLevel.Error); return(false); } } #endregion #region ConvertToDouble case OutputTypes.DoubleType: { try // can be read as double? { Output = StringToDouble(inpString, this.settings.FormatAmer ? "en" : "de"); GuiLogMessage("Converting String to double is not safe. Digits may have been cut off.", NotificationLevel.Warning); return(true); } catch (Exception e) { GuiLogMessage("Could not convert input to double: " + e.Message, NotificationLevel.Error); return(false); } } #endregion #region ConvertToBigInteger case OutputTypes.BigIntegerType: { try // can be read as parseable expression? { Output = BigIntegerHelper.ParseExpression(inpString); return(true); } catch (Exception) { } // remove all non-hex characters and parse as hexstring byte[] result = TryMatchHex(inpString); if (result != null) { Output = ByteArrayToBigInteger(result, settings.Endianness); return(true); } GuiLogMessage("Could not convert input to BigInteger", NotificationLevel.Error); return(false); } #endregion #region ConvertToIntArray #endregion #region ConvertToByteArray case OutputTypes.ByteArrayType: { if (settings.Numeric) // apply user setting concerning numeric interpretation of input (else input is read as string) { try // can be read as parseable expression? { Output = BigIntegerHelper.ParseExpression(inpString).ToByteArray(); return(true); } catch (Exception) { } try // can be read as Hexstring? { byte[] result = TryMatchHex(inpString); if (result != null) { Output = result; return(true); } } catch (Exception) { } try // can be read as double { double tempDouble = StringToDouble(inpString, this.settings.FormatAmer ? "en" : "de"); byte[] temp = BitConverter.GetBytes(tempDouble); Output = temp; double test = BitConverter.ToDouble(temp, 0); GuiLogMessage("Converting String to double is not safe. Digits may have been cut off: " + test.ToString(), NotificationLevel.Warning); return(true); } catch (Exception) { } } // numeric interpretation NOT selected: Output = GetBytesForEncoding(inpString, settings.OutputEncoding); return(true); } #endregion #region ConvertToCryptoolStream case OutputTypes.CryptoolStreamType: { if (input is byte[] || input is byte || input is BigInteger || input is String) { OnPropertyChanged("Output"); return(true); } else { GuiLogMessage("Conversion from " + input.GetType().Name + " to CryptoolStream is not yet implemented", NotificationLevel.Error); return(false); } } #endregion #region ConvertToAnythingLeft default: return(false); #endregion } #endregion }
/// <summary> /// Called by the environment to start generating of public/private keys /// </summary> public void Execute() { BigInteger p = 1, q = 1; ProgressChanged(0, 1); switch (settings.Source) { // manually enter primes case 0: try { p = BigIntegerHelper.ParseExpression(settings.P); q = BigIntegerHelper.ParseExpression(settings.Q); if (!BigIntegerHelper.IsProbablePrime(p)) { GuiLogMessage(p.ToString() + " is not prime!", NotificationLevel.Error); return; } if (!BigIntegerHelper.IsProbablePrime(q)) { GuiLogMessage(q.ToString() + " is not prime!", NotificationLevel.Error); return; } if (p == q) { GuiLogMessage("The primes P and Q can not be equal!", NotificationLevel.Error); return; } } catch (Exception ex) { GuiLogMessage("Invalid Big Number input: " + ex.Message, NotificationLevel.Error); return; } break; //randomly generated primes case 1: try { int keyBitLength = Convert.ToInt32(settings.KeyBitLength); if (keyBitLength < 4) { GuiLogMessage("The keylength must be greater than 3.", NotificationLevel.Error); return; } int i, maxtries = 10; for (i = 0; i < maxtries; i++) { p = BigIntegerHelper.RandomPrimeMSBSet(keyBitLength - (keyBitLength / 2)); q = BigIntegerHelper.RandomPrimeMSBSet(keyBitLength / 2); //GuiLogMessage("p = " + p.ToString(), NotificationLevel.Info); //GuiLogMessage("q = " + q.ToString(), NotificationLevel.Info); if (p != q) { break; } } if (i == maxtries) { throw new Exception("Could not create two differing primes"); } } catch (Exception ex) { GuiLogMessage(ex.Message, NotificationLevel.Error); return; } break; default: throw new Exception("Illegal Key Generation Mode"); } N = p * q; G = N + 1; Lambda = (p - 1) * (q - 1); ProgressChanged(1, 1); }