-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRSA.cs
More file actions
64 lines (49 loc) · 1.67 KB
/
RSA.cs
File metadata and controls
64 lines (49 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace IntegerArithmeticRsaEncryption {
public static class RSA {
public static List<string> Encode(string value, BigInt publicExponent, BigInt modulo) {
var encodedParts = new List<string>();
foreach (var symbol in value) {
var result = BigInteger.ModPow(new BigInt(((int)symbol).ToString()).Value, publicExponent.Value, modulo.Value);
encodedParts.Add(result.ToString());
}
return encodedParts;
}
public static string Decode(IEnumerable<string> input, BigInt secretExponent, BigInt modulo) {
var decodedValue = new StringBuilder();
foreach (var item in input) {
var result = BigInteger.ModPow(new BigInt(item).Value, secretExponent.Value, modulo.Value);
decodedValue.Append((char)result);
}
return decodedValue.ToString();
}
public static BigInt CalculateSecretExponent(BigInt publicExponent, BigInt modulo) {
return BigInt.InverseElementOnModulo(publicExponent, modulo);
}
public static BigInt CalculatePublicExponent(BigInt modulo) {
var exponent = new BigInt("3");
var one = new BigInt("1");
for (var i = new BigInt("0"); i < modulo; i += one) {
if (EuclideanAlgorithm.GreatestCommonDivisor(exponent, modulo, out _, out _) == one)
return exponent;
exponent += one;
}
return exponent;
}
public static bool IsSimpleNumber(BigInt number) {
var zero = new BigInt("0");
var one = new BigInt("1");
var two = new BigInt("2");
if (number < two)
return false;
if (number == two)
return true;
for (var i = two; i < number; i += one)
if (number % i == zero)
return false;
return true;
}
}
}