internal ChoicesRSA(int clientVersionMax, int cipherSuite, byte[][] chain, RSAPrivateKey rk) : base(cipherSuite, chain) { this.clientVersionMax = clientVersionMax; this.rk = rk; }
public void Serializing_and_deserializing_a_private_key_should_result_in_equal_keys() { // Arrange var rsa = new RSACryptoServiceProvider(2048); var rsaParameters = rsa.ExportParameters(true); var asn1Parser = new Asn1Parser(); var rsaParser = new RSAPrivateKeyParser(asn1Parser); var asn1Serializer = new Asn1Serializer(); var asn1Rsa = new RSAPrivateKey(rsaParameters); // Act var serializedPEM = asn1Serializer.Serialize(asn1Rsa).ToArray().EncodeAsPEM(PEMExtensions.RSAPrivateKey); var parsedRsaKey = rsaParser.ParsePem(new MemoryStream(Encoding.ASCII.GetBytes(serializedPEM))); //TODO this test sometimes has a missing leading '0' byte. // Assert parsedRsaKey.Key.Exponent.Should().Equal(rsaParameters.Exponent); parsedRsaKey.Key.Modulus.Should().Equal(rsaParameters.Modulus); parsedRsaKey.Key.P.Should().Equal(rsaParameters.P); parsedRsaKey.Key.D.Should().Equal(rsaParameters.D); parsedRsaKey.Key.DP.Should().Equal(rsaParameters.DP); parsedRsaKey.Key.Q.Should().Equal(rsaParameters.Q); parsedRsaKey.Key.DQ.Should().Equal(rsaParameters.DQ); parsedRsaKey.Key.InverseQ.Should().Equal(rsaParameters.InverseQ); }
public void TestKeyStoreAddRemove() { string keyname = this.GetType().FullName + ".TestKeyCreateAndDelete"; using (RSAPrivateKey key = new RSAPrivateKey()) { Assert.IsFalse(key.DeleteFromStore()); key.WriteToStore(keyname); CspParameters cp = new CspParameters(); cp.KeyContainerName = keyname; cp.Flags = CspProviderFlags.UseExistingKey; using (RSAPrivateKey key2 = RSAPrivateKey.FromStore(cp)) Assert.AreEqual(key.ToXml(), key2.ToXml()); using (RSAPrivateKey key2 = RSAPrivateKey.FromStore(keyname)) { Assert.AreEqual(key.ToXml(), key2.ToXml()); Assert.IsTrue(key2.DeleteFromStore()); key2.Dispose(); } } }
public void SetPassword(byte[] passbytes) { Check.ArraySize(passbytes, 1, 2048); Check.Assert <InvalidOperationException>(_passwordRequired && _privateBits != null && _privateKey == null); try { byte[] keybytes; using (Password pwd = new Password(false, passbytes)) { pwd.IV = IV.ToByteArray(); keybytes = pwd.Decrypt(_privateBits, Salt.Size.b256); } Check.Assert <InvalidDataException>(_privateHash.Equals(Hash.SHA256(keybytes))); _privateKey = RSAPrivateKey.FromBytes(keybytes); Check.Assert <InvalidDataException>(_publicHash.Equals(Hash.SHA256(_privateKey.PublicKey.ToArray()))); passbytes = Encryption.CurrentUser.Encrypt(passbytes); RegistryStorage store = new RegistryStorage(Settings.RegistryPath); store.Write("CryptoKey", _privateHash.ToString(), Convert.ToBase64String(passbytes)); } catch (Exception err) { Log.Error(err); throw new InvalidDataException(); } }
private static byte[] Compute(byte[] data, RSAPrivateKey privateKey, int blockSize) { // // 私钥加密/解密公式为:mi = ci^d ( mod n ) // // 先将 c(二进制表示)分成数据块 c1, c2, ..., ci ,然后进行运算。 // BigInteger d = new BigInteger(privateKey.D); BigInteger n = new BigInteger(privateKey.Modulus); int blockOffset = 0; using (MemoryStream stream = new MemoryStream()) { while (blockOffset < data.Length) { int blockLen = Math.Min(blockSize, data.Length - blockOffset); byte[] blockData = new byte[blockLen]; Buffer.BlockCopy(data, blockOffset, blockData, 0, blockLen); BigInteger ci = new BigInteger(blockData); BigInteger mi = ci.modPow(d, n);//mi = ci^d ( mod n ) byte[] block = mi.getBytes(); stream.Write(block, 0, block.Length); blockOffset += blockLen; } return(stream.ToArray()); } }
public IContentResponse HandlePasswordSet(NameValueCollection headers, Stream inputStream) { INameValueStore store = new RegistryStorage(Settings.RegistryPath); int contentLen = int.Parse(headers["Content-Length"]); if (contentLen == 0) { using (RSAPrivateKey _temporaryKey = new RSAPrivateKey(2048)) { store.Write("Transfers", "temp-key", Convert.ToBase64String(_temporaryKey.ToArray())); return(new DynamicResponse("application/public-key", _temporaryKey.PublicKey.ToArray())); } } string tempkey; if (contentLen <= 2048 && store.Read("Transfers", "temp-key", out tempkey)) { byte[] bytes = IOStream.Read(inputStream, contentLen); using (RSAPrivateKey _temporaryKey = RSAPrivateKey.FromBytes(Convert.FromBase64String(tempkey))) bytes = _temporaryKey.Decrypt(bytes); _content.KeyPair.SetServerPassword(bytes); } return(DynamicResponse.Empty); }
public RSA GetOrCreateKey(string keyName) { var rsa = new RSACryptoServiceProvider(2048); var keyFileName = Path.Combine(basePath, $"{keyName}.pem"); Debug.WriteLine(keyFileName); if (File.Exists(keyFileName)) { Verbose($"using existing key file {keyFileName}"); var keyXml = File.ReadAllText(keyFileName); var privateKey = RSAPrivateKey.ParsePem(keyXml); rsa.ImportParameters(privateKey.Key); } else { var privateKey = new RSAPrivateKey(rsa.ExportParameters(true)); Verbose($"writing new key to file {keyFileName}"); var pemEncodedPrivateKey = privateKey.ToPemString(); File.WriteAllText(keyFileName, pemEncodedPrivateKey); } return(rsa); }
public void Can_read_jwt_base64url_encoded_key() { var key = RSAPrivateKey.ParsePem(jwtPrivateKey).Key; Assert.Equal(@"{ ""D"": ""D+onAtVye4ic7VR7V50DF9bOnwRwNXrARcDhq9LWNRrRGElESYYTQ6EbatXS3MCyjjX2eMhu/aF5YhXBwkppwxg+EOmXeh+MzL7Zh284OuPbkglAaGhV9bb6/5CpuGb1esyPbYW+Ty2PC0GSZfIXkXs76jXAu9TOBvD0ybc2Ylk="", ""DP"": ""ZZ2XIpsitLyPpuiMOvBbzPavd4gY6Z8KWrfYzJoI/Q9FuBo6rKwl4BFoToD7WIUS+hpkagwWiz+6zLoX1dbOZw=="", ""DQ"": ""CmH5fSSjAkLRi54PKJ8TFUeOP15h9sQzydI8zJU+upvDEKZsZc/UhT/SySDOxQ4G/523Y0sz/OZtSWcol/UMgQ=="", ""Exponent"": ""AQAB"", ""InverseQ"": ""Lesy++GdvoIDLfJX5GBQpuFgFenRiRDabxrE9MNUZ2aPFaFp+DyAe+b4nDwuJaW2LURbr8AEZga7oQj0uYxcYw=="", ""Modulus"": ""3ZWrUY0Y6IKN1qI4BhxR2C7oHVFgGPYkd38uGq1jQNSqEvJFcN93CYm16/G78FAFKWqwsJb3Wx+nbxDn6LtP4AhULB1H0K0g7/jLklDAHvI8yhOKlvoyvsUFPWtNxlJyh5JJXvkNKV/4Oo12e69f8QCuQ6NpEPl+cSvXIqUYBCs="", ""P"": ""8sINkf+7d0NjhNvsqN/NgiyXa5Ui1UTlisG+LW9j44WOFwMFfHdb8tEXp8UwfiuTLue7lUkx7azCtBgLRa/N9w=="", ""Q"": ""6avx20OHo61Yela/4k5kQDtjEf1N0LfI+BcWZtxsS3jDM3i1Hp0KSu5rsCPb8acJo5RO26gGVrfAsDcIXKC+bQ=="" }", JsonConvert.SerializeObject(new { key.D, key.DP, key.DQ, key.Exponent, key.InverseQ, key.Modulus, key.P, key.Q }, Formatting.Indented)); }
public static BigInteger CreateSignature(BigInteger originalNumber, RSAPrivateKey privateKey) { var originalNumberHashValue = originalNumber.GetHashCode(); BigInteger signature = BigInteger.ModPow(originalNumberHashValue, privateKey.D, privateKey.N); return(signature); }
public RSAKey(RSAPrivateKey privateKey) : this(privateKey.PublicKey) { _hasPrivateKey = true; _privateBits = null; _privateKey = privateKey; _privateHash = Hash.SHA256(_privateKey.ToArray()); }
private static byte[] GetKeyAsDER(RSAParameters key) { var asn1Key = new RSAPrivateKey(key); var serializer = new Asn1Serializer(); var keyBytes = serializer.Serialize(asn1Key).ToArray(); return(keyBytes); }
public CryptokiPrivateKeySignature(Session session, String alias) { this.session = session; CryptokiCollection template = new CryptokiCollection(); template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PRIVATE_KEY)); template.Add(new ObjectAttribute(ObjectAttribute.CKA_KEY_TYPE, Key.CKK_RSA)); template.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, alias)); privateKey = (RSAPrivateKey)session.Objects.Find(template); }
public static string Decrypt(string encryptedMessage, RSAPrivateKey privateKey) { BigInteger numericEquivalent = NumberStringEqualizer.StringToBigIntegerEquivalent(encryptedMessage); BigInteger originalNumber = BigInteger.ModPow(numericEquivalent, privateKey.D, privateKey.N); string originalMessage = NumberStringEqualizer.BigIntToStringEquivalent(originalNumber); return(originalMessage); }
// [Fact] public async Task D() { var privateKey = RSA.Create(RSAPrivateKey.Decode(TestData.PrivateRSA256KeyText)); var client = new AcmeClient(privateKey, directoryUrl: "https://acme-staging-v02.api.letsencrypt.org/directory"); var accountUrl = await client.GetAccountUrlAsync(); throw new Exception(JsonObject.FromObject(new { accountUrl }).ToString()); }
public static byte[] Decrypt(byte[] data, RSAPrivateKey privateKey) { if (data == null) { throw new ArgumentNullException("data"); } if (privateKey == null) { throw new ArgumentNullException("privateKey"); } BigInteger d = new BigInteger(privateKey.D); BigInteger n = new BigInteger(privateKey.Modulus); int inputBlockSize = privateKey.Modulus.Length + 1; int outputBlockMaxSize = privateKey.Modulus.Length - 1; if (data.Length % inputBlockSize != sizeof(Int32)) { return(null); } using (MemoryStream stream = new MemoryStream()) { int inputBlockOffset = 0; int outputBlockOffset = 0; int lastOutputBlockSize = BitConverter.ToInt32(data, inputBlockOffset); inputBlockOffset += sizeof(Int32); if (lastOutputBlockSize > outputBlockMaxSize) { return(null); } while (inputBlockOffset < data.Length) { byte[] inputBlockData = new byte[inputBlockSize]; Buffer.BlockCopy(data, inputBlockOffset, inputBlockData, 0, inputBlockSize); inputBlockOffset += inputBlockSize; BigInteger ci = new BigInteger(inputBlockData); BigInteger mi = BigInteger.ModPow(ci, d, n);//mi = ci^d ( mod n ) byte[] outputBlockData = mi.ToByteArray(); stream.Write(outputBlockData, 0, outputBlockData.Length); outputBlockOffset += inputBlockOffset >= data.Length ? lastOutputBlockSize : outputBlockMaxSize; stream.Seek(outputBlockOffset, SeekOrigin.Begin); } stream.SetLength(outputBlockOffset); return(stream.ToArray()); } }
public void Save(RSAParameters key, string keyName, KeyFormat format) { var keyFileName = Path.Combine(basePath, $"{keyName}." + GetExtension(format)); var privateKey = new RSAPrivateKey(key); using (var stream = File.OpenWrite(keyFileName)) { privateKey.WriteTo(stream, format); } }
public void Can_read_a_private_key_from_a_PEM_file() { var rsa = RSAPrivateKey.ParsePem(new MemoryStream(Encoding.ASCII.GetBytes(TestPrivateKey))); // Assert rsa.Key.Exponent.Should().Equal(1, 0, 1); rsa.Key.Modulus.Length.Should().Be(256); rsa.Key.Modulus[0].Should().Be(0xb2); rsa.Key.Modulus[255].Should().Be(0xab); rsa.Key.P.Length.Should().Be(128); }
public void TestPKICertificate() { byte[] rawdata = new byte[8001]; new Random().NextBytes(rawdata); byte[] cypher; using (RSAPublicKey publicKey = new RSAPublicKey(TestCertPublicKey())) cypher = publicKey.Encrypt(rawdata); using (RSAPrivateKey privateKey = new RSAPrivateKey(TestCertPrivateKey())) Assert.AreEqual(rawdata, privateKey.Decrypt(cypher)); }
private static RSA GetPrivateKey() { var key = RSAPrivateKey.ParsePem(@"-----BEGIN RSA PRIVATE KEY----- MIICWwIBAAKBgQDdlatRjRjogo3WojgGHFHYLugdUWAY9iR3fy4arWNA1KoS8kVw33cJibXr8bvwUAUparCwlvdbH6dvEOfou0/gCFQsHUfQrSDv+MuSUMAe8jzKE4qW+jK+xQU9a03GUnKHkkle+Q0pX/g6jXZ7r1/xAK5Do2kQ+X5xK9cipRgEKwIDAQABAoGAD+onAtVye4ic7VR7V50DF9bOnwRwNXrARcDhq9LWNRrRGElESYYTQ6EbatXS3MCyjjX2eMhu/aF5YhXBwkppwxg+EOmXeh+MzL7Zh284OuPbkglAaGhV9bb6/5CpuGb1esyPbYW+Ty2PC0GSZfIXkXs76jXAu9TOBvD0ybc2YlkCQQDywg2R/7t3Q2OE2+yo382CLJdrlSLVROWKwb4tb2PjhY4XAwV8d1vy0RenxTB+K5Mu57uVSTHtrMK0GAtFr833AkEA6avx20OHo61Yela/4k5kQDtjEf1N0LfI+BcWZtxsS3jDM3i1Hp0KSu5rsCPb8acJo5RO26gGVrfAsDcIXKC+bQJAZZ2XIpsitLyPpuiMOvBbzPavd4gY6Z8KWrfYzJoI/Q9FuBo6rKwl4BFoToD7WIUS+hpkagwWiz+6zLoX1dbOZwJACmH5fSSjAkLRi54PKJ8TFUeOP15h9sQzydI8zJU+upvDEKZsZc/UhT/SySDOxQ4G/523Y0sz/OZtSWcol/UMgQJALesy++GdvoIDLfJX5GBQpuFgFenRiRDabxrE9MNUZ2aPFaFp+DyAe+b4nDwuJaW2LURbr8AEZga7oQj0uYxcYw== -----END RSA PRIVATE KEY-----"); var rsa = RSA.Create(); rsa.ImportParameters(key.Key); return(rsa); }
// [Fact] public async Task B() { var privateKey = RSA.Create(RSAPrivateKey.Decode(TestData.PrivateRSA256KeyText)); var client = new AcmeClient(privateKey, directoryUrl: "https://acme-staging-v02.api.letsencrypt.org/directory"); var accountUrl = await client.CreateAccountAsync(new CreateAccountRequest(termsOfServiceAgreed : true, new[] { "mailto:[email protected]" }, false)); throw new Exception(JsonObject.FromObject(new { accountUrl }).ToString()); }
public static void TestClassInit(TestContext context) { _rsaProvider = new RSACryptoServiceProvider(); string publicKeyXml = _rsaProvider.ToXmlString(false); string privateKeyXml = _rsaProvider.ToXmlString(true); _rsaPublicXml = publicKeyXml; _rsaPrivateXml = privateKeyXml; _rsaPublic = RSAPublicKey.FromXmlString(publicKeyXml); _rsaPrivate = RSAPrivateKey.FromXmlString(privateKeyXml); }
private void buttonDecryptChoosePblicKey_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Title = "Choose private key"; openFileDialog.Filter = "Private key (*.private)|*.private"; openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory; if (openFileDialog.ShowDialog() == DialogResult.OK) { labelDecryptPrivateKey.Text = Path.GetFileName(openFileDialog.FileName); privateKey = RSAPrivateKey.LoadFromFile(openFileDialog.FileName); //label5.Text = AES.AES.Decrypt(textBoxEDecryptPassphrase.Text, privateKey.encryptedN); } }
public async Task GetNonce() { var privateKey = RSA.Create(RSAPrivateKey.Decode(TestData.PrivateRSA256KeyText)); var client = new AcmeClient(privateKey, directoryUrl: "https://acme-staging-v02.api.letsencrypt.org/directory"); await client.InitializeAsync(); var nonce = await client.GetNonceAsync(); await Task.Delay(1100); Assert.True(nonce.Age.TotalSeconds > 1); Assert.NotNull(nonce.Value); }
// [Fact] public async Task C() { var client = new AcmeClient( privateKey: RSA.Create(RSAPrivateKey.Decode(TestData.PrivateRSA256KeyText)), accountUrl: "https://acme-staging-v02.api.letsencrypt.org/acme/acct/5363173", directoryUrl: "https://acme-staging-v02.api.letsencrypt.org/directory" ); var request = new CreateOrderRequest(new[] { new Identifier("dns", "test.accelerator.net") }, null, null); var order = await client.CreateOrderAsync(request); throw new Exception(JsonObject.FromObject(new { order, order.Url }).ToString()); }
/** * Decrypt message Tab */ private void buttonDecryptImportPublicKey_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Title = "Choose encrypted text"; openFileDialog.Filter = "Encrypted text (*.txt)|*.txt"; openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory; if (openFileDialog.ShowDialog() == DialogResult.OK) { privateKey = RSAPrivateKey.LoadFromFile(openFileDialog.FileName); using (StreamReader sr = File.OpenText(openFileDialog.FileName)) { textBoxDecryptText.Text = sr.ReadToEnd(); } } }
/// <summary> /// Generate a new key with the given length. /// </summary> /// <param name="length">Length of the key to be generated. Usually given in bits, but depends on the algorithm.</param> /// <returns>New RSAPrivateKey with the PublicKey-property set to the corresponding RSAPublicKey.</returns> public Key generateKey(short length) { Debug.Assert(length >= 2048, "The key must be at least 2048 bits in length."); Debug.Assert(((length % 1024) == 0), "The key must be a power of 1024."); RsaKeyPairGenerator generator = new RsaKeyPairGenerator(); generator.Init(new KeyGenerationParameters(new SecureRandom(), length)); AsymmetricCipherKeyPair pair = generator.GenerateKeyPair(); RSAPrivateKey privateKey = new RSAPrivateKey(pair.Private); RSAPublicKey publicKey = new RSAPublicKey(pair.Public); privateKey.PublicKey = publicKey; return privateKey; }
public static byte[] Decrypt(byte[] data, RSAPrivateKey privateKey) { if (data == null) { throw new ArgumentNullException("data"); } if (privateKey == null) { throw new ArgumentNullException("privateKey"); } int blockSize = privateKey.Modulus.Length; return(Compute(data, privateKey, blockSize)); }
public static RSAPrivateKey GetPrivateKey(RSAParameters param) { var retVal = new RSAPrivateKey() { Modulus = Convert.ToBase64String(param.Modulus), Exponent = Convert.ToBase64String(param.Exponent), P = Convert.ToBase64String(param.P), Q = Convert.ToBase64String(param.Q), DP = Convert.ToBase64String(param.DP), DQ = Convert.ToBase64String(param.DQ), InverseQ = Convert.ToBase64String(param.InverseQ), D = Convert.ToBase64String(param.D), }; return(retVal); }
public static RSAKeyPair GenerateRSAKeyPair() { var p = BigIntegerRandomGenerator.GetBigRandomPrime(); var q = BigIntegerRandomGenerator.GetBigRandomPrime(); var n = BigInteger.Multiply(p, q); var eulerFuncValue = BigInteger.Multiply(p - 1, q - 1); var e = BigInteger.Pow(2, 16) + 1; while (true) { var gcd = BigInteger.GreatestCommonDivisor(eulerFuncValue, e); if (gcd != 1) { _logger.Info("gcd(e, euler)={0} Generating new random number", gcd); e = BigIntegerRandomGenerator.GetBigRandomPrime(); } else { break; } } var d = ExtendedGCD.ModInverse(e, eulerFuncValue); _logger.Info("d={0}", d); /* * var checkRes = BigInteger.Multiply(d, e); * * * checkRes = BigInteger.Remainder(checkRes, eulerFuncValue); * * _logger.Info("Check: {0}", checkRes); */ var publicKey = new RSAPublicKey(n, e); var privateKey = new RSAPrivateKey(n, d); var keyPair = new RSAKeyPair(publicKey, privateKey); return(keyPair); }
public void TestPrivateKeyExport() { RSAPrivateKey pk = new RSAPrivateKey(); string xml = pk.ToXml(); RSAPrivateKey copy = RSAPrivateKey.FromXml(xml); Assert.AreEqual(xml, copy.ToXml()); byte[] bytes = pk.ToArray(); Assert.AreEqual(596, bytes.Length); copy = RSAPrivateKey.FromBytes(bytes); Assert.AreEqual(bytes, copy.ToArray()); copy = RSAPrivateKey.FromParameters(pk.ExportParameters()); Assert.AreEqual(bytes, copy.ToArray()); }
public byte[] InstallCertificateWithPrivateKey( string certificatePath, string certificateStoreName, RSAParameters privateKey) { var xCert = new X509Certificate2(certificatePath); var bCertBytes = xCert.Export(X509ContentType.Cert); var privk = new RSAPrivateKey(privateKey); var pemEncodedPrivateKey = privk.ToPemString(); midMethods = new Container { Cert = Oocx.Pkcs.Pem.Encode(bCertBytes, "CERTIFICATE"), Key = pemEncodedPrivateKey }; return(null); }