Convert pythonecode into c# - c#

I have to integrate to some device that needs to generate some id
this device has no SDK or API but, I have found some project in python that works fine.
for now, iv tested the option to run the python script as a process
but it's not good option.
Code :
TRANSID_PREFIX = 'web'
def genTransId(self, trans_type=TRANSID_PREFIX):
def float2hex(f):
MAXHEXADECIMALS = 15
w = f // 1
d = f % 1
# Do the whole:
if w == 0: result = '0'
else: result = ''
while w:
w, r = divmod(w, 16)
r = int(r)
if r > 9: r = chr(r+55)
else: r = str(r)
result = r + result
# And now the part:
if d == 0: return result
result += '.'
count = 0
while d:
d = d * 16
w, d = divmod(d, 1)
w = int(w)
if w > 9: w = chr(w+55)
else: w = str(w)
result += w
count += 1
if count > MAXHEXADECIMALS: break
return result
now = datetime.today()
return trans_type+"!" + float2hex(random.random() * math.pow(2, 32)).lower() + "!" + str(int((time.mktime(now.timetuple())*1e3 + now.microsecond/1e3)))

Tool to convert python to c#
and
https://github.com/uxmal/pytocs
But, can you give some more info on your statement:
"iv tested the option to run the python script as a process but it's not good option" ?

Related

What takes too long on this code?

Trying to solve another SO question, I came up with the following algorithm which I thought is quite optmized. However while running DotNetBenchmark on all solutions, I was very surprised that my code was running on a whopping average of 387 ms compared to the ~ 20-30 ms some of the other answers acheived.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
int CalcMe(string input) // I used Marc Gravel's input generation method
{
var operands = input.Split(' ');
var j = 1; // operators index
var result = int.Parse(operands[0]); // output
// i = numbers index
for (int i = 2; i < operands.Length; i += 2)
{
switch (operands[j])
{
case "+":
result += int.Parse(operands[i]);
break;
case "-":
result -= int.Parse(operands[i]);
break;
case "*":
result *= int.Parse(operands[i]);
break;
case "/":
try
{
result /= int.Parse(operands[i]);
break;
}
catch
{
break; // division by 0.
}
default:
throw new Exception("Unknown Operator");
}
j += 2; // next operator
}
return result;
}
Just by extracting the String.Split() to the caller Main() method, I lowered the execution to 110 ms, but that still does not solve the mystery since all other answers handle the input directly.
I am just trying to understand to perhaps change my way of thinking toward optimizations. I couldn't see any keywords that I only use. switch, for and int.Parse() are pretty much on every other solution.
EDIT 1: Test input generation
The input generation is copied form Marc answer on the original quetsion as below:
static string GenerateInput()
{
Random rand = new Random(12345);
StringBuilder input = new StringBuilder();
string operators = "+-*/";
var lastOperator = '+';
for (int i = 0; i < 1000000; i++)
{
var #operator = operators[rand.Next(0, 4)];
input.Append(rand.Next(lastOperator == '/' ? 1 : 0, 100) + " " + #operator + " ");
lastOperator = #operator;
}
input.Append(rand.Next(0, 100));
return input.ToString();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
Won't achieve almost anything here. Inlining is used when you want to tell to compiler to just copy and paste your code on multiple places to avoid unnecessary method invocations. And it's pretty damn smart to know when to do it on it's own in most of occasions.
var operands = input.Split(' ');
Causes the JIT to go through the whole string, do a search, split a string and fill the array, which can take a long time.
switch (operands[j])
Switching on strings can also have an impact since it has to call equals on cases. You'd want to use simple types in switch if you're looking at performance(char for example).
int.Parse
This actually does a bunch of allocations and even deals with unsafe code. You can see the code for parsing here:
https://referencesource.microsoft.com/#mscorlib/system/number.cs,698
Or if the link goes down:
[System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Int32 ParseInt32(String s, NumberStyles style, NumberFormatInfo info) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
Int32 i = 0;
StringToNumber(s, style, ref number, info, false);
if ((style & NumberStyles.AllowHexSpecifier) != 0) {
if (!HexNumberToInt32(ref number, ref i)) {
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
}
else {
if (!NumberToInt32(ref number, ref i)) {
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
}
return i;
}
[System.Security.SecuritySafeCritical] // auto-generated
private unsafe static void StringToNumber(String str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo info, Boolean parseDecimal) {
if (str == null) {
throw new ArgumentNullException("String");
}
Contract.EndContractBlock();
Contract.Assert(info != null, "");
fixed (char* stringPointer = str) {
char * p = stringPointer;
if (!ParseNumber(ref p, options, ref number, null, info , parseDecimal)
|| (p - stringPointer < str.Length && !TrailingZeros(str, (int)(p - stringPointer)))) {
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
}
}
I think comparing of strings much more complicated than comparing of chars
Below the key difference
switch (operands[j])
{
case "+":
...
switch (cOperator)
{
case '+':
...
Interesting problem! I was interested in implementing this for myself, and checking what I can come up with, as well as how it compares to other implementations. I did it in F# but since both F# and C# are strongly-typed CLR languages, and the insights gained below are (arguably) independent of C#, I hope you'll agree that the following is not quite off-topic.
First I needed a few functions for creating a suitable expression string (adapted from your posting), measuring time, and running a bunch of functions with the generated string:
module Testbed =
let private mkTestCase (n : int) =
let next (r : System.Random) i = r.Next (0, i)
let r = System.Random ()
let s = System.Text.StringBuilder n
let ops = "+-*/"
(s.Append (next r 100), {1 .. n})
||> Seq.fold (fun s _ ->
let nx = next r 100
let op = ops.[next r (if nx = 0 then 3 else 4)]
s.Append (" " + string op + " " + string nx))
|> string
let private stopwatch n f =
let mutable r = Unchecked.defaultof<_>
let sw = System.Diagnostics.Stopwatch ()
sw.Start ()
for i = 1 to n do r <- f ()
sw.Stop ()
(r, sw.ElapsedMilliseconds / int64 n)
let runtests tests =
let s, t = stopwatch 100 (fun () -> mkTestCase 1000000)
stdout.Write ("MKTESTCASE\nTime: {0}ms\n", t)
tests |> List.iter (fun (name : string, f) ->
let r, t = stopwatch 100 (fun () -> f s)
let w = "{0} ({1} chars)\nResult: {2}\nTime: {3}ms\n"
stdout.Write (w, name, s.Length, r, t))
For a string of 1 million operations (around 4.9 million chars), the mkTestCase function ran in 317ms on my laptop.
Next I translated your function to F#:
module MethodsToTest =
let calc_MBD1 (s : string) =
let inline runop f a b =
match f with
| "+" -> a + b
| "-" -> a - b
| "*" -> a * b
| "/" -> a / b
| _ -> failwith "illegal op"
let rec loop (ops : string []) r i j =
if i >= ops.Length then r else
let n = int ops.[i]
loop ops (runop ops.[j] r n) (i + 2) (j + 2)
let ops = s.Split ' '
loop ops (int ops.[0]) 2 1
This ran in 488ms on my laptop.
Next I wanted to check if string matching is really that much slower than character matching:
let calc_MBD2 (s : string) =
let inline runop f a b =
match f with
| '+' -> a + b
| '-' -> a - b
| '*' -> a * b
| '/' -> a / b
| _ -> failwith "illegal op"
let rec loop (ops : string []) r i j =
if i >= ops.Length then r else
let n = int ops.[i]
loop ops (runop ops.[j].[0] r n) (i + 2) (j + 2)
let ops = s.Split ' '
loop ops (int ops.[0]) 2 1
Common wisdom would say that character matching should be significantly faster, given that it involves only a primitive comparison instead of calculating a hash, but the above ran in 482ms on my laptop, so the difference between primitive character comparison, and comparing hashes of strings of length 1 is almost negligible.
Lastly I checked whether hand-rolling the number parsing would provide a significant saving:
let calc_MBD3 (s : string) =
let inline getnum (c : char) = int c - 48
let parse (s : string) =
let rec ploop r i =
if i >= s.Length then r else
let c = s.[i]
let n = if c >= '0' && c <= '9'
then 10 * r + getnum c else r
ploop n (i + 1)
ploop 0 0
let inline runop f a b =
match f with
| '+' -> a + b
| '-' -> a - b
| '*' -> a * b
| '/' -> a / b
| _ -> failwith "illegal op"
let rec loop (ops : string []) r i j =
if i >= ops.Length then r else
let n = parse ops.[i]
loop ops (runop ops.[j].[0] r n) (i + 2) (j + 2)
let ops = s.Split ' '
loop ops (parse ops.[0]) 2 1
This ran in 361ms on my laptop, so the saving is significant but the function is still an order of magnitude slower than my own creation (see below), leading to the conclusion that the initial string splitting takes the bulk of the time.
Just for comparison, I also translated the OP's function from the posting you referenced to F#:
let calc_OP (s : string) =
let operate r op x =
match op with
| '+' -> r + x
| '-' -> r - x
| '*' -> r * x
| '/' -> r / x
| _ -> failwith "illegal op"
let rec loop c n r =
if n = -1 then
operate r s.[c + 1] (int (s.Substring (c + 3)))
else
operate r s.[c + 1] (int (s.Substring (c + 3, n - (c + 2))))
|> loop n (s.IndexOf (' ', n + 4))
let c = s.IndexOf ' '
loop c (s.IndexOf (' ', c + 4)) (int (s.Substring (0, c)))
This ran in 238ms on my laptop, so using substrings is not as slow as splitting the string but still it is far from optimal.
Finally my own implementation of an expression interpreter, taking into account that the fastest way of processing is doing it manually character by character, iterating the string only once, and that heap allocation (by way of creating new objects, such as strings or arrays) should be avoided inside the loop as much as possible:
let calc_Dumetrulo (s : string) =
let inline getnum (c : char) = int c - 48
let inline isnum c = c >= '0' && c <= '9'
let inline isop c =
c = '+' || c = '-' || c = '*' || c = '/'
let inline runop f a b =
match f with
| '+' -> a + b
| '-' -> a - b
| '*' -> a * b
| '/' -> a / b
| _ -> failwith "illegal op"
let rec parse i f a c =
if i >= s.Length then
if c = -1 then a else runop f a c
else
let k, j = s.[i], i + 1
if isnum k then
let n = if c = -1 then 0 else c
parse j f a (10 * n + getnum k)
elif isop k then parse j k a c
elif c = -1 then parse j f a c
else parse j f (runop f a c) -1
parse 0 '+' 0 -1
This ran in a satisfactory 28ms on my laptop. You can express this the same way in C#, except for the tail-recursion, which should be expressed by a for or while loop:
static int RunOp(char op, int a, int b)
{
switch (op)
{
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
default: throw new InvalidArgumentException("op");
}
}
static int Calc_Dumetrulo(string s)
{
int a = 0, c = -1;
char op = '+';
for (int i = 0; i < s.Length; i++)
{
char k = s[i];
if (k >= '0' && k <= '9')
c = (c == -1 ? 0 : 10 * c) + ((int)k - 48);
else if (k == '+' || k == '-' || k == '*' || k == '/')
op = k;
else if (c == -1) continue;
else
{
a = RunOp(op, a, c);
c = -1;
}
}
if (c != -1) a = RunOp(op, a, c);
return a;
}

I'm having trouble applying the square root function to an equation comprised of float (C#)

I'm getting an error (CS0117) 'Math' does not contain a definition for 'sqrt'
I'm trying to calculate the answer to an equation and therefore need to square root a combination of variables and display the answer
case 4:
P1 = float.Parse(TextP1.Text);
Vol1 = float.Parse(TextVol1.Text);
U1 = float.Parse(TextU1.Text);
Vel1 = float.Parse(TextVel1.Text);
h1 = float.Parse(TextH1.Text);
Q = float.Parse(TextQ.Text);
P2 = float.Parse(TextP2.Text);
Vol2 = float.Parse(TextVol2.Text);
U2 = float.Parse(TextU2.Text);
Vel2 = float.Parse(TextVel2.Text);
h2 = float.Parse(TextH2.Text);
W = float.Parse(TextW.Text);
Vel1 = Math.sqrt(((P2 * Vol2) + U2 + ((Vel2 * Vel2) / 2) + (g * h2) + W - Q - (g * h1) - U1 - (P1 * Vol1)) / 2);
TextU1.Text = U1.ToString();
break;
C# is case sensitive. Try Math.Sqrt instead of Math.sqrt.
https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx

Base 64 decode fails with invalid length

I'm attempt to convert a base64 string generated from javascript code using C# code, but I'm running into an invalid length message.
The string is MQA5ADIAMwA3ADgANwA6ADAA0
It should convert back to 1923787:0
I tried a number of online decoders and some of them worked but a couple failed with the same invalid length error. I'll not post links here, but needless to say they were able to convert it back to the expected string.
C# Decode
var t = "MQA5ADIAMwA3ADgANwA6ADAA0";
var x = Convert.FromBase64String(t);
Javascript encoder:
var encoder = function (mL) {
if (!mL || mL === '') {
return '';
}
var ei = [];
var V;
for (V = 0; V < mL.length; V++) {
ei.push(mL.charCodeAt(V) % 256);
ei.push(Math.floor(mL.charCodeAt(V) / 256));
}
ei.push(0);
ei.push(0);
var sf = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
var gF = [],
hO;
for (V = 0; V < ei.length - 1; V += 3) {
hO = ei[V] * 0x10000 + ei[V + 1] * 0x100 + ei[V + 2];
gF.push(sf.charAt(Math.floor(hO / 0x40000)));
gF.push(sf.charAt(Math.floor(hO / 0x1000) % 0x40));
gF.push(sf.charAt(Math.floor(hO / 0x40) % 0x40));
gF.push(sf.charAt(hO % 0x40));
}
var vr = Math.ceil(mL.length * 16 / 6);
while (gF.length > vr) {
gF.pop();
}
if ((gF.length % 4) === 3) {
gF.push('1');
} else if ((gF.length % 4) === 2) {
gF.push('2');
} else if ((gF.length % 4) === 0) {
gF.push('0');
}
return gF.join('');
};
First, change your for which does the encode to
for (V = 0; V < ei.length - 3; V += 3) {
then instead of
var vr = Math.ceil(mL.length * 16 / 6);
while (gF.length > vr) {
gF.pop();
}
if ((gF.length % 4) === 3) {
gF.push('1');
} else if ((gF.length % 4) === 2) {
gF.push('2');
} else if ((gF.length % 4) === 0) {
gF.push('0');
}
do
switch (ei.length % 3) {
case 0:
break;
case 1:
gF[gF.length - 2] = '=';
case 2:
gF[gF.length - 1] = '=';
break;
}
Now you'll get
encoder("1923787:0"); // "MQA5ADIAMwA3ADgANwA6ADA="
Which is valid Base64,
What's going on? Base64 uses = to designate the number of bytes we started with, in terms of how short we were from the next multiple of 3, so this swaps out the final characters (which were the zero symbol due to not having any bits) with those = signs.
The modification to the loop is to end the loop at the right place - you were overshooting with just - 1 because say you were at V >= ei.length - 3 but V < ei.length - 1, i.e. V = ei.length - 3 or V = ei.length - 2 you would enter the next iteration at V = ei.length or V = ei.length + 1, at which point ei[V], ei[V+1], ei[V+2] would be undefined
See if this helps.
string x = Encoding.UTF8.GetString(Convert.FromBase64String("MQA5ADIAMwA3ADgANwA6ADAA0"));
Link: How do I decode a base64 encoded string?
Your encoding routine is putting an extra 0 on the end of the string, remove it and the decode will work (into a Unicode string)
Example code:
var original = "1923787:0";
var bytesFromOriginal = System.Text.Encoding.Unicode.GetBytes(original);
var base64string = Convert.ToBase64String(bytesFromOriginal);
base64string = "MQA5ADIAMwA3ADgANwA6ADAA";
var bytesFromEncodedString = Convert.FromBase64String(base64string);
var decodedString = System.Text.Encoding.Unicode.GetString(bytesFromEncodedString);
The correct Base64 encoding of your input string is "MQA5ADIAMwA3ADgANwA6ADAA" - without the trailing zero that you show. For some reason your javascript code is adding that zero. I'm not sure why. But that makes it an invalid string.
I'm guessing the padding, which should be '=' is being added as '0' by the javascript algorithm. Just a thought though.

Calculate primes p and q from private exponent (d), public exponent (e) and the modulus (n)

How do I calculate the p and q parameters from e (publickey), d (privatekey) and modulus?
I have BigInteger keys at hand I can copy paste into code. One publickey, one privatekey and a modulus.
I need to calculate the RSA parameters p and q from this. But I suspect there is a library for that which I was unable to find with google. Any ideas? Thanks.
This does not have to be brute force, since I'm not after the private key. I just have a legacy system which stores a public, private key pair and a modulus and I need to get them into c# to use with RSACryptoServiceProvider.
So it comes down to calculating (p+q) by
public BigInteger _pPlusq()
{
int k = (this.getExponent() * this.getD() / this.getModulus()).IntValue();
BigInteger phiN = (this.getExponent() * this.getD() - 1) / k;
return phiN - this.getModulus() - 1;
}
but this doesn't seem to work. Can you spot the problem?
5 hours later... :)
Ok. How can I select a random number out of Zn* (http://en.wikipedia.org/wiki/Multiplicative_group_of_integers_modulo_n) in C#?
Let's assume that e is small (that's the common case; the Traditional public exponent is 65537). Let's also suppose that ed = 1 mod phi(n), where phi(n) = (p-1)(q-1) (this is not necessarily the case; the RSA requirements are that ed = 1 mod lcm(p-1,q-1) and phi(n) is only a multiple of lcm(p-1,q-1)).
Now you have ed = k*phi(n)+1 for some integer k. Since d is smaller than phi(n), you know that k < e. So you only have a small number of k to try. Actually, phi(n) is close to n (the difference being on the order of sqrt(n); in other words, when written out in bits, the upper half of phi(n) is identical to that of n) so you can compute k' with: k'=round(ed/n). k' is very close to k (i.e. |k'-k| <= 1) as long as the size of e is no more than half the size of n.
Given k, you easily get phi(n) = (ed-1)/k. It so happens that:
phi(n) = (p-1)(q-1) = pq - (p+q) + 1 = n + 1 - (p+q)
Thus, you get p+q = n + 1 - phi(n). You also have pq. It is time to remember that for all real numbers a and b, a and b are the two solutions of the quadratic equation X2-(a+b)X+ab. So, given p+q and pq, p and q are obtained by solving the quadratic equation:
p = ((p+q) + sqrt((p+q)2 - 4*pq))/2
q = ((p+q) - sqrt((p+q)2 - 4*pq))/2
In the general case, e and d may have arbitrary sizes (possibly greater than n), because all that RSA needs is that ed = 1 mod (p-1) and ed = 1 mod (q-1). There is a generic (and fast) method which looks a bit like the Miller-Rabin primality test. It is described in the Handbook of Applied Cryptography (chapter 8, section 8.2.2, page 287). That method is conceptually a bit more complex (it involves modular exponentiation) but may be simpler to implement (because there is no square root).
There is a procedure to recover p and q from n, e and d described in NIST Special Publication 800-56B R1 Recommendation for Pair-Wise Key Establishment Schemes Using Integer Factorization Cryptography in Appendix C.
The steps involved are:
Let k = de – 1. If k is odd, then go to Step 4.
Write k as k = 2tr, where r is the largest odd integer dividing k, and t ≥ 1. Or in simpler terms, divide k repeatedly by 2 until you reach an odd number.
For i = 1 to 100 do:
Generate a random integer g in the range [0, n−1].
Let y = gr mod n
If y = 1 or y = n – 1, then go to Step 3.1 (i.e. repeat this loop).
For j = 1 to t – 1 do:
Let x = y2 mod n
If x = 1, go to (outer) Step 5.
If x = n – 1, go to Step 3.1.
Let y = x.
Let x = y2 mod n
If x = 1, go to (outer) Step 5.
Continue
Output “prime factors not found” and stop.
Let p = GCD(y – 1, n) and let q = n/p
Output (p, q) as the prime factors.
I recently wrote an implementation in Java. Not directly useful for C# I realise, but perhaps it can be easily ported:
// Step 1: Let k = de – 1. If k is odd, then go to Step 4
BigInteger k = d.multiply(e).subtract(ONE);
if (isEven(k)) {
// Step 2 (express k as (2^t)r, where r is the largest odd integer
// dividing k and t >= 1)
BigInteger r = k;
BigInteger t = ZERO;
do {
r = r.divide(TWO);
t = t.add(ONE);
} while (isEven(r));
// Step 3
Random random = new Random();
boolean success = false;
BigInteger y = null;
step3loop: for (int i = 1; i <= 100; i++) {
// 3a
BigInteger g = getRandomBi(n, random);
// 3b
y = g.modPow(r, n);
// 3c
if (y.equals(ONE) || y.equals(n.subtract(ONE))) {
// 3g
continue step3loop;
}
// 3d
for (BigInteger j = ONE; j.compareTo(t) <= 0; j = j.add(ONE)) {
// 3d1
BigInteger x = y.modPow(TWO, n);
// 3d2
if (x.equals(ONE)) {
success = true;
break step3loop;
}
// 3d3
if (x.equals(n.subtract(ONE))) {
// 3g
continue step3loop;
}
// 3d4
y = x;
}
// 3e
BigInteger x = y.modPow(TWO, n);
if (x.equals(ONE)) {
success = true;
break step3loop;
}
// 3g
// (loop again)
}
if (success) {
// Step 5
p = y.subtract(ONE).gcd(n);
q = n.divide(p);
return;
}
}
// Step 4
throw new RuntimeException("Prime factors not found");
This code uses a few helper definitions/methods:
private static final BigInteger ONE = BigInteger.ONE;
private static final BigInteger TWO = BigInteger.valueOf(2);
private static final BigInteger ZERO = BigInteger.ZERO;
private static boolean isEven(BigInteger bi) {
return bi.mod(TWO).equals(ZERO);
}
private static BigInteger getRandomBi(BigInteger n, Random rnd) {
// From http://stackoverflow.com/a/2290089
BigInteger r;
do {
r = new BigInteger(n.bitLength(), rnd);
} while (r.compareTo(n) >= 0);
return r;
}
I've adapted the Java code provided by Duncan in C#, if anyone is interested:
public static void RecoverPQ(
BigInteger n,
BigInteger e,
BigInteger d,
out BigInteger p,
out BigInteger q
)
{
int nBitCount = (int)(BigInteger.Log(n, 2)+1);
// Step 1: Let k = de – 1. If k is odd, then go to Step 4
BigInteger k = d * e - 1;
if (k.IsEven)
{
// Step 2 (express k as (2^t)r, where r is the largest odd integer
// dividing k and t >= 1)
BigInteger r = k;
BigInteger t = 0;
do
{
r = r / 2;
t = t + 1;
} while (r.IsEven);
// Step 3
var rng = new RNGCryptoServiceProvider();
bool success = false;
BigInteger y = 0;
for (int i = 1; i <= 100; i++) {
// 3a
BigInteger g;
do
{
byte[] randomBytes = new byte[nBitCount / 8 + 1]; // +1 to force a positive number
rng.GetBytes(randomBytes);
randomBytes[randomBytes.Length - 1] = 0;
g = new BigInteger(randomBytes);
} while (g >= n);
// 3b
y = BigInteger.ModPow(g, r, n);
// 3c
if (y == 1 || y == n-1) {
// 3g
continue;
}
// 3d
BigInteger x;
for (BigInteger j = 1; j < t; j = j + 1) {
// 3d1
x = BigInteger.ModPow(y, 2, n);
// 3d2
if (x == 1) {
success = true;
break;
}
// 3d3
if (x == n-1) {
// 3g
continue;
}
// 3d4
y = x;
}
// 3e
x = BigInteger.ModPow(y, 2, n);
if (x == 1) {
success = true;
break;
}
// 3g
// (loop again)
}
if (success) {
// Step 5
p = BigInteger.GreatestCommonDivisor((y - 1), n);
q = n / p;
return;
}
}
throw new Exception("Cannot compute P and Q");
}
This uses the standard System.Numerics.BigInteger class.
This was tested by the following unit test:
BigInteger n = BigInteger.Parse("9086945041514605868879747720094842530294507677354717409873592895614408619688608144774037743497197616416703125668941380866493349088794356554895149433555027");
BigInteger e = 65537;
BigInteger d = BigInteger.Parse("8936505818327042395303988587447591295947962354408444794561435666999402846577625762582824202269399672579058991442587406384754958587400493169361356902030209");
BigInteger p;
BigInteger q;
RecoverPQ(n, e, d, out p, out q);
Assert.AreEqual(n, p * q);
I implemented the method described by Thomas Pornin.
The BigInteger class is Chew Keong TAN's C# version (check codeproject comments for bug fixes)
/// EXAMPLE (Hex Strings)
/// N(MODULUS) = "DB2CB41E112BACFA2BD7C3D3D7967E84FB9434FC261F9D090A8983947DAF8488D3DF8FBDCC1F92493585E134A1B42DE519F463244D7ED384E26D516CC7A4FF7895B1992140043AACADFC12E856B202346AF8226B1A882137DC3C5A57F0D2815C1FCD4BB46FA9157FDFFD79EC3A10A824CCC1EB3CE0B6B4396AE236590016BA69"
/// D(PRIVATE EXPONENT) = "18B44A3D155C61EBF4E3261C8BB157E36F63FE30E9AF28892B59E2ADEB18CC8C8BAD284B9165819CA4DEC94AA06B69BCE81706D1C1B668EB128695E5F7FEDE18A908A3011A646A481D3EA71D8A387D474609BD57A882B182E047DE80E04B4221416BD39DFA1FAC0300641962ADB109E28CAF50061B68C9CABD9B00313C0F46ED"
/// E(PUBLIC EXPONENT) = "010001"
/// RESULTS:
/// DP = "899324E9A8B70CA05612D8BAE70844BBF239D43E2E9CCADFA11EBD43D0603FE70A63963FE3FFA38550B5FEB3DA870D2677927B91542D148FA4BEA6DCD6B2FF57"
/// DQ = "E43C98265BF97066FC078FD464BFAC089628765A0CE18904F8C15318A6850174F1A4596D3E8663440115D0EEB9157481E40DCA5EE569B1F7F4EE30AC0439C637"
/// INVERSEQ = "395B8CF3240C325B0F5F86A05ABCF0006695FAB9235589A56759ECBF2CD3D3DFDE0D6F16F0BE5C70CEF22348D2D09FA093C01D909D25BC1DB11DF8A4F0CE552"
/// P = "ED6CF6699EAC99667E0AFAEF8416F902C00B42D6FFA2C3C18C7BE4CF36013A91F6CF23047529047660DE14A77D13B74FF31DF900541ED37A8EF89340C623759B"
/// Q = "EC52382046AA660794CC1A907F8031FDE1A554CDE17E8AA216AEDC92DB2E58B0529C76BD0498E00BAA792058B2766C40FD7A9CC2F6782942D91471905561324B"
public static RSACryptoServiceProvider CreateRSAPrivateKey(string mod, string privExponent, string pubExponent)
{
var rsa = new RSACryptoServiceProvider
{
PersistKeyInCsp = false
};
var n = new BigInteger(mod, 16);
var d = new BigInteger(privExponent, 16);
var e = new BigInteger(pubExponent, 16);
var zero = new BigInteger(0);
var one = new BigInteger(1);
var two = new BigInteger(2);
var four = new BigInteger(4);
BigInteger de = e*d;
BigInteger modulusplus1 = n + one;
BigInteger deminus1 = de - one;
BigInteger p = zero;
BigInteger q = zero;
BigInteger kprima = de/n;
var ks = new[] {kprima, kprima - one, kprima + one};
bool bfound = false;
foreach (BigInteger k in ks)
{
BigInteger fi = deminus1/k;
BigInteger pplusq = modulusplus1 - fi;
BigInteger delta = pplusq*pplusq - n*four;
BigInteger sqrt = delta.sqrt();
p = (pplusq + sqrt)/two;
if (n%p != zero) continue;
q = (pplusq - sqrt)/two;
bfound = true;
break;
}
if (bfound)
{
BigInteger dp = d%(p - one);
BigInteger dq = d%(q - one);
BigInteger inverseq = q.modInverse(p);
var pars = new RSAParameters
{
D = d.getBytes(),
DP = dp.getBytes(),
DQ = dq.getBytes(),
Exponent = e.getBytes(),
Modulus = n.getBytes(),
P = p.getBytes(),
Q = q.getBytes(),
InverseQ = inverseq.getBytes()
};
rsa.ImportParameters(pars);
return rsa;
}
throw new CryptographicException("Error generating the private key");
}

Solving brain teaser using linq

At the very outset let me express my sincere thanks to Marc Gravel,Dahlbyk and the rest for helping me to apply linq practically.
The following are few questions which I have faced in an interview to solve applying Linq. As I am not familiar with Linq I solved it without using Linq.
I appreciate the answers which helps me to solve them using Linq
Thanks in advance.
Question 1:
The Problem is to find different digits such that,in whatever order they are used to make a three-digit number,that number will not be divisible by:
3,5,7,11,13 or 17.
To ensure that there is no ambuigity,suppose the three digits
are a,b,and c.Then,none of the combination of the numbers:
say abc,acb,bac,bca,cab and cba will divide by 3,5,7,11,13 or 17.
Example :
When I take 248 none of its combination(284,428,482,842,824) will exactly divisible by 3,5,7,11,13 or 17.
public void FindingRareNumbers()
{
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= 9; j++)
{
for (int k = 1; k <= 9; k++)
{
//to form the three digit
string digit = i.ToString() + j.ToString() + k.ToString();
//converting to integer
int StrToDigit = Convert.ToInt32(digit);
char[] digitcombination = digit.ToCharArray();
string PossibleCombination = "";
bool testpassed = false;
int dcount = 0;
#region different possible combinations
for (int p = 0; p <= 2; p++)
{
for (int q = 0; q <= 2; q++)
{
for (int r = 0; r <= 2; r++)
{
// The following condition avoid the repeatance
// of digit like 111,111,111
if (p != q && p != r && r != q)
{
PossibleCombination =
digitcombination[p].ToString() +
digitcombination[q].ToString() +
digitcombination[r].ToString();
int num = Convert.ToInt32(PossibleCombination);
if (num % 3 != 0 && num % 5 != 0 && num % 7 != 0
&& num % 11 != 0 && num % 11 != 0
&& num % 13 != 0 && num % 17 != 0)
{
//count is increment for 6 times
// it satisfies the condition
dcount++;
testpassed = true;
}
}
}
}
}
#endregion combination
if (testpassed && dcount==6)
{
Console.WriteLine(StrToDigit);
}
}
}
}
}
(coding is working)
Question 2:
The task is to arrange the element in matrix so that all rows,columns,and diagonals add up to the same total.(Bit problem in coding ,I am trying to solve it).
------------------
1 2 3
-----------------
4 5 6
-----------------
7 8 9
-----------------
example :
The one of solutions is as follows:
-----------
2 9 4
-----------
7 5 3
----------
6 1 8
----------
I agree that Marc's solution to your first problem is a reasonable approach. But I think there's a larger question here, which is "how do I solve problems like this in a LINQ-ish manner?"
Notice how your solution is completely "procedural" and "imperative". Your code specifies a series of steps that you would execute, one after the other, with deep loops. Each step along the way is meaningless unless you understand its place in the larger whole.
There are two ideas I like to use when solving problems with LINQ:
Describe what the program is doing logically, rather than listing a series of commands
Characterize the problem as a query against a data set rather than as a procedure to follow.
So, what's our data set? We wish to filter out some elements from the set of all combinations of three digits.
How do we filter them? Permute the digits and then perform a divisibility check on each permutation.
OK, so now we have a structure for our program:
var query = from c in ThreeDigitCombinations()
where DivisibilityCheckPasses(c)
select c;
foreach(Combination result in query) Console.WriteLine(result);
And now you can continue breaking down each of those further, solving each sub-problem using LINQ in turn.
Same goes for your "magic square" problem; you're looking for a permutation that has a certain property, so write a generator of permutations, write a filter, and execute it.
For the first:
static IEnumerable<int> Permute(int x, int y, int z)
{
yield return x * 100 + y * 10 + z;
yield return x * 100 + z * 10 + y;
yield return y * 100 + x * 10 + z;
yield return y * 100 + z * 10 + x;
yield return z * 100 + x * 10 + y;
yield return z * 100 + y * 10 + x;
}
static void Main()
{
var divs = new[] {3,5,7,11,13,17};
// combinations of 1-9
var combinations =
from x in Enumerable.Range(1, 7)
from y in Enumerable.Range(x + 1, 8 - x)
from z in Enumerable.Range(y + 1, 9 - y)
select new { x, y, z };
// permute
var qry = from comb in combinations
where !Permute(comb.x, comb.y, comb.z).Any(
i => divs.Any(d => i % d == 0))
select comb;
foreach (var answer in qry)
{
Console.WriteLine("{0}, {1}, {2}", answer.x, answer.y, answer.z);
}
}
For the second - not elegant, but it works (returns the 8 permutations of the sample):
static void Main() {
var data = Enumerable.Range(1, 9);
var magicSquares =
// generate 1st row and deduce the target
from a in data let arrA = new[] { a }
from b in data.Except(arrA) let arrB = new[] { a,b }
from c in data.Except(arrB) let arrC = new[] { a,b,c }
let target = a + b + c
// generate 2nd row and filter to target matches
from d in data.Except(arrC) let arrD = new[] { a,b,c,d }
from e in data.Except(arrD) let arrE = new[] { a,b,c,d,e }
from f in data.Except(arrE) let arrF = new[] { a,b,c,d,e,f }
where d + e + f == target
// generate 3rd row and filter to target matches
from g in data.Except(arrF) let arrG = new[] { a,b,c,d,e,f,g }
from h in data.Except(arrG) let arrH = new[] { a,b,c,d,e,f,g,h }
from i in data.Except(arrH)
where g + h + i == target
// filter columns
&& a + d + g == target
&& b + e + h == target
&& c + f + i == target
// filter diagonals
&& a + e + i == target
&& c + e + g == target
select new {a,b,c,d,e,f,g,h,i};
foreach (var row in magicSquares)
{
Console.WriteLine("{0} {1} {2}", row.a, row.b, row.c);
Console.WriteLine("{0} {1} {2}", row.d, row.e, row.f);
Console.WriteLine("{0} {1} {2}", row.g, row.h, row.i);
Console.WriteLine();
}
}

Categories