public static void ExportAutoKey() { RSAParameters privateParams; RSAParameters publicParams; int keySize; using (RSA rsa = new RSACryptoServiceProvider()) { keySize = rsa.KeySize; // We've not done anything with this instance yet, but it should automatically // create the key, because we'll now asked about it. privateParams = rsa.ExportParameters(true); publicParams = rsa.ExportParameters(false); // It shouldn't be changing things when it generated the key. Assert.Equal(keySize, rsa.KeySize); } Assert.Null(publicParams.D); Assert.NotNull(privateParams.D); ValidateParameters(ref publicParams); ValidateParameters(ref privateParams); Assert.Equal(privateParams.Modulus, publicParams.Modulus); Assert.Equal(privateParams.Exponent, publicParams.Exponent); }
private static void GenerateKey(Func<RSA, int> getSize) { int keySize; using (var rsa = new RSACryptoServiceProvider()) { keySize = getSize(rsa); } using (var rsa = new RSACryptoServiceProvider(keySize)) { Assert.Equal(keySize, rsa.KeySize); // Some providers may generate the key in the constructor, but // all of them should have generated it before answering ExportParameters. RSAParameters keyParameters = rsa.ExportParameters(false); ImportExport.ValidateParameters(ref keyParameters); // KeySize should still be what we set it to originally. Assert.Equal(keySize, rsa.KeySize); // KeySize describes the size of the modulus in bits // So, 8 * the number of bytes in the modulus should be the same value. Assert.Equal(keySize, keyParameters.Modulus.Length * 8); } }
public static void PaddedExport() { // OpenSSL's numeric type for the storage of RSA key parts disregards zero-valued // prefix bytes. // // The .NET 4.5 RSACryptoServiceProvider type verifies that all of the D breakdown // values (P, DP, Q, DQ, InverseQ) are exactly half the size of D (which is itself // the same size as Modulus). // // These two things, in combination, suggest that we ensure that all .NET // implementations of RSA export their keys to the fixed array size suggested by their // KeySize property. RSAParameters diminishedDPParamaters = TestData.DiminishedDPParamaters; RSAParameters exported; using (RSA rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(diminishedDPParamaters); exported = rsa.ExportParameters(true); } // DP is the most likely to fail, the rest just otherwise ensure that Export // isn't losing data. AssertKeyEquals(ref diminishedDPParamaters, ref exported); }
public static void LargeKeyImportExport() { RSAParameters imported = TestData.RSA16384Params; using (RSA rsa = new RSACryptoServiceProvider()) { try { rsa.ImportParameters(imported); } catch (CryptographicException) { // The key is pretty big, perhaps it was refused. return; } RSAParameters exported = rsa.ExportParameters(false); Assert.Equal(exported.Modulus, imported.Modulus); Assert.Equal(exported.Exponent, imported.Exponent); Assert.Null(exported.D); exported = rsa.ExportParameters(true); AssertKeyEquals(ref imported, ref exported); } }
public static RSAParameters ToPublicRSAParameters(this string publicKeyXml) { using (var rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(publicKeyXml); return rsa.ExportParameters(includePrivateParameters: false); } }
//Asymetric void Main() { try { UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] dataToEncrypt = ByteConverter.GetBytes("Data to Encrypt"); byte[] encryptedData; byte[] decryptedData; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { encryptedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(false)); decryptedData = RSADecrypt(encryptedData, RSA.ExportParameters(true)); Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData)); } } catch (ArgumentNullException) { Console.WriteLine("Encryption failed."); } }
public static void RsaDecryptAfterExport() { byte[] output; using (var rsa = new RSACryptoServiceProvider()) { byte[] crypt = rsa.Encrypt(TestData.HelloBytes, true); // Export the key, this should not clear/destroy the key. RSAParameters ignored = rsa.ExportParameters(true); output = rsa.Decrypt(crypt, true); } Assert.Equal(TestData.HelloBytes, output); }
public static void Main(string[] args) { string path = args[0]; byte[] blob = null; using(FileStream fs = File.Open(path, FileMode.Open)) { blob = new byte[fs.Length]; fs.Read(blob, 0, blob.Length); } RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportCspBlob(blob); RSAParameters PrivateKey = rsa.ExportParameters(true); byte[] key = RSAKeyToASN1(PrivateKey); using(FileStream fs = File.Open(path + ".out", FileMode.Create)) { fs.Write(key, 0, key.Length); } Console.WriteLine("Your file is ready for you at " + path + ".out."); }
public void Pkcs1DecodingTest() { #pragma warning disable 0436 // Initialize the "Known Good" RSAParameters. byte[] capi1Blob = Convert.FromBase64String(AsymmetricKeyAlgorithmProviderTests.Helper.PrivateKeyFormatsAndBlobs[Tuple.Create(PCLCrypto.AsymmetricAlgorithm.RsaOaepSha1, CryptographicPrivateKeyBlobType.Capi1PrivateKey)]); var rsa = new RSACryptoServiceProvider(); rsa.ImportCspBlob(capi1Blob); RSAParameters rsaCapi = rsa.ExportParameters(true); // Now load up the tested one. byte[] pkcs1KeyBlob = Convert.FromBase64String(AsymmetricKeyAlgorithmProviderTests.Helper.PrivateKeyFormatsAndBlobs[Tuple.Create(PCLCrypto.AsymmetricAlgorithm.RsaOaepSha1, CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey)]); RSAParameters homeReadPkcs1 = KeyFormatter.ToPlatformParameters(KeyFormatter.Pkcs1.Read(pkcs1KeyBlob)); #pragma warning restore 0436 Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.Modulus), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.Modulus)); Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.Exponent), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.Exponent)); Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.D), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.D)); Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.P), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.P)); Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.Q), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.Q)); Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.DP), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.DP)); Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.DQ), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.DQ)); Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.InverseQ), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.InverseQ)); }
public void RSA_public_blob_to_jwk() { var bytes = Convert.FromBase64String(File.ReadAllText(@"C:\Temp\public.blob")); var csp = new RSACryptoServiceProvider(); csp.ImportCspBlob(bytes); var parameters = csp.ExportParameters(false); var keyset = new JsonWebKeySet { Keys = new JsonWebKey[] { new JsonWebKey { Algorithm = "RS256", KeyType = "RSA", IntendedUse = "sig", Exponent = Convert.ToBase64String(parameters.Exponent), Modulus = Convert.ToBase64String(parameters.Modulus), KeyIdentifier = "1" } } }; Console.WriteLine(JsonConvert.SerializeObject(keyset)); var jwk = keyset.Keys.Where(k => k.KeyType == "RSA" && k.IntendedUse == "sig").First(); csp.ImportParameters(new RSAParameters { Exponent = Convert.FromBase64String(jwk.Exponent), Modulus = Convert.FromBase64String(jwk.Modulus) }); bytes = csp.ExportCspBlob(false); File.WriteAllText(@"C:\Temp\public.from_jwk.blob", Convert.ToBase64String(bytes)); }
void loadP12(byte[] p12data, string password) { X509Certificate2Collection col = new X509Certificate2Collection(); col.Import(p12data, password, X509KeyStorageFlags.Exportable); foreach (X509Certificate2 cert in col) { if (cert.HasPrivateKey) { _certificate = cert; RSACryptoServiceProvider tmpKey = (RSACryptoServiceProvider)cert.PrivateKey; RSAParameters keyParams = tmpKey.ExportParameters(true); CspParameters p = new CspParameters(); p.ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider"; _key = new RSACryptoServiceProvider(p); _key.ImportParameters(keyParams); } } if (_key == null || _certificate == null) { throw new ArgumentException("key and/or certificate still missing after p12 processing"); } }
public void AllowGoodToken() { var fakeIssuer = "example.okta.com"; var fakeAudience = "aud://default"; using (RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider(2048)) { RSAParameters rsaKeyInfo = rsaCryptoServiceProvider.ExportParameters(true); var rsaSecurityKey = new RsaSecurityKey(rsaKeyInfo); var signingCredentials = new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256); var jwtContents = new JwtSecurityToken( issuer: fakeIssuer, audience: fakeAudience, expires: DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)), signingCredentials: signingCredentials); var jwt = new JwtSecurityTokenHandler().WriteToken(jwtContents); var fakeOktaWebOptions = new OktaWebOptions { OktaDomain = fakeIssuer, }; var handler = new StrictTokenHandler(); var validationParameters = new DefaultTokenValidationParameters(fakeOktaWebOptions, fakeIssuer) { IssuerSigningKey = signingCredentials.Key, ValidAudience = fakeAudience, }; handler.ValidateToken(jwt, validationParameters, out _); } }
/// <summary> /// XML格式私钥转PEM /// </summary> /// <param name="xml">XML格式私钥</param> /// <param name="saveFile">保存文件的物理路径</param> public static string Xml2PemPrivate(string xml, string saveFile) { var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(xml); var p = rsa.ExportParameters(true); var key = new RsaPrivateCrtKeyParameters( new BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent), new BigInteger(1, p.D), new BigInteger(1, p.P), new BigInteger(1, p.Q), new BigInteger(1, p.DP), new BigInteger(1, p.DQ), new BigInteger(1, p.InverseQ)); using (var sw = new StreamWriter(saveFile)) { var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw); pemWriter.WriteObject(key); } PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(key); byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded(); string privateKey = Convert.ToBase64String(serializedPrivateBytes); return(Format(privateKey, 2)); }
// Load private and or public key information from the key store. // This overloaded version of the method loads the information from the user // section if "useMachineStore" is false, otherwise it loads the information // from the machine section. The method will return false if the entry does // not exist. public bool LoadFromContainer(string containerName, bool useMachineStore) { // Create new cryptographic service provider parameters object CspParameters cspParameters = new CspParameters(); // Set the container name, which in this case is the MAC address cspParameters.KeyContainerName = containerName; // This flag indicates that the entry must exist. Without setting this // the application will return a random key. This flag is also what causes // an error to be thrown in the following try-catch. cspParameters.Flags = CspProviderFlags.UseExistingKey; // Set the machine store flag if necessary if (useMachineStore) { cspParameters.Flags |= CspProviderFlags.UseMachineKeyStore; } // If this throws an error then the entry does not exist try { // Create temporary RSA encryption in order to load the information from the // key store and import into classes' RSA encryption object. using (RSACryptoServiceProvider tempRsa = new RSACryptoServiceProvider(cspParameters)) { // Import key information from the key store to the current class RSA // encryption object. _rsa.ImportParameters(tempRsa.ExportParameters(!tempRsa.PublicOnly)); } } catch { // The entry does not exist return(false); } // The entry was retrieved return(true); }
public RSAParameters GenerateOtherPublicKey() { var folder = ruta; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } RSAParameters key = new RSAParameters(); using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048)) { //rsa.ImportParameters(GetPrivateKey()); var publicKey = rsa.ExportParameters(false); using (var str = new FileStream(Path.Combine(folder, $"publicKey.xml"), FileMode.Create)) { var xml = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); xml.Serialize(str, publicKey); } } return(key); }
/// <summary> /// Returns the RSA Key pair for a RSA CryptoServiceProvider /// Borrowed this small sample from .NET Crypto Extensions /// </summary> /// <param name="rsa">RSA CSP</param> /// <returns>RSA key pair</returns> private static AsymmetricCipherKeyPair GetRsaKeyPair( RSACryptoServiceProvider rsa) { RSAParameters rp = rsa.ExportParameters(true); BigInteger modulus = new BigInteger(1, rp.Modulus); BigInteger pubExp = new BigInteger(1, rp.Exponent); RsaKeyParameters pubKey = new RsaKeyParameters( false, modulus, pubExp); RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters( modulus, pubExp, new BigInteger(1, rp.D), new BigInteger(1, rp.P), new BigInteger(1, rp.Q), new BigInteger(1, rp.DP), new BigInteger(1, rp.DQ), new BigInteger(1, rp.InverseQ)); return(new AsymmetricCipherKeyPair(pubKey, privKey)); }
public RSAParameters ParseRSAKeyInfo(RSAKeySetIdentity rsaKeySet) { RSAParameters rsaParams; int startIndex = rsaKeySet.RSA_PrivateKey.IndexOf(BEGIN_RSA_PRIVATE_KEY, StringComparison.Ordinal); int endIndex = rsaKeySet.RSA_PrivateKey.IndexOf(END_RSA_PRIVATE_KEY, StringComparison.Ordinal); if (startIndex < 0 || endIndex < 0) { throw new ArgumentException("Invalid key data"); } string keyData = rsaKeySet.RSA_PrivateKey.Substring(startIndex + BEGIN_RSA_PRIVATE_KEY.Length, endIndex - startIndex - BEGIN_RSA_PRIVATE_KEY.Length).Replace("\r\n", ""); byte[] keyBlobBytes = Convert.FromBase64String(keyData); using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportCspBlob(keyBlobBytes); rsaParams = rsa.ExportParameters(true); } return(rsaParams); }
public ISignatureAlgorithm ToSignatureAlgorithm(SignatureAlgorithmDataRecord dataRecord, SharedSecretEncryptionKey encryptionKey, int?recordVersion) { if (dataRecord == null) { throw new ArgumentNullException(nameof(dataRecord)); } switch (dataRecord.Type) { case string str when str.Equals("rsa", StringComparison.OrdinalIgnoreCase): using (var rsaForVerification = new RSACryptoServiceProvider()) { rsaForVerification.FromXml(dataRecord.Param); var paramsForVerification = rsaForVerification.ExportParameters(includePrivateParameters: false); return(SignatureAlgorithm.CreateForVerification(paramsForVerification, new HashAlgorithmName(dataRecord.Hash))); } case string str when str.Equals("ecdsa", StringComparison.OrdinalIgnoreCase): using (var ecdsaForVerification = ECDsa.Create()) { ecdsaForVerification.FromXml(dataRecord.Param); var paramsForVerification = ecdsaForVerification.ExportParameters(includePrivateParameters: false); return(SignatureAlgorithm.CreateForVerification(paramsForVerification, new HashAlgorithmName(dataRecord.Hash))); } case string str when str.Equals("hmac", StringComparison.OrdinalIgnoreCase): var unencryptedKey = GetUnencryptedParameter(dataRecord, encryptionKey); return(SignatureAlgorithm.CreateForVerification(unencryptedKey, new HashAlgorithmName(dataRecord.Hash))); default: throw new NotSupportedException($"The specified signature algorithm type ({dataRecord.Type ?? "[null]"}) cannot be deserialized."); } }
public async Task CanRoundTripRSA() { using (var rsa = new RSACryptoServiceProvider()) { var publicKeyParams = rsa.ExportParameters(false); var rsaAlg = RSASignatureAlgorithm.CreateForVerification(HashAlgorithmName.SHA384, publicKeyParams); var client = new Client( "c1", "app one", rsaAlg, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), RequestTargetEscaping.RFC2396, new Claim("company", "Dalion"), new Claim("scope", "HttpMessageSigning")); await _sut.Register(client); var actual = await _sut.Get(client.Id); actual.Should().BeEquivalentTo(client, options => options.ComparingByMembers <Client>()); actual.SignatureAlgorithm.Should().BeAssignableTo <RSASignatureAlgorithm>(); actual.SignatureAlgorithm.As <RSASignatureAlgorithm>().GetPublicKey().ToXml().Should().Be(rsa.ExportParameters(false).ToXml()); actual.SignatureAlgorithm.As <RSASignatureAlgorithm>().HashAlgorithm.Should().Be(HashAlgorithmName.SHA384); } }
/* * 构造RSA公钥私钥集合(c#、java互通) */ public static Hashtable RSAInitKey() { Hashtable ht = new Hashtable(); RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAKeyInfo = RSA.ExportParameters(true); try { ht.Add("publickey", Convert.ToBase64String(RSA.ExportCspBlob(false))); ht.Add("privatekey", Convert.ToBase64String(RSA.ExportCspBlob(true))); ht.Add("d", Convert.ToBase64String(RSAKeyInfo.D)); ht.Add("dp", Convert.ToBase64String(RSAKeyInfo.DP)); ht.Add("dq", Convert.ToBase64String(RSAKeyInfo.DQ)); ht.Add("p", Convert.ToBase64String(RSAKeyInfo.P)); ht.Add("q", Convert.ToBase64String(RSAKeyInfo.Q)); ht.Add("inverseq", Convert.ToBase64String(RSAKeyInfo.InverseQ)); ht.Add("modulus", Convert.ToBase64String(RSAKeyInfo.Modulus)); } catch { Console.WriteLine("rsa - Hashtable-An element with key already exists"); } return(ht); }
public CryptoManager() { m_RSA_Exch_Def = new RSAPKCS1KeyExchangeDeformatter(); m_RSA_Exch_For = new RSAPKCS1KeyExchangeFormatter(); m_RSA = new RSACryptoServiceProvider(); m_RSA.KeySize = m_KeySize; //m_RSA.PersistKeyInCsp = true; m_SHA = new SHA256Managed(); m_RIJ = new RijndaelManaged(); m_RIJ.Padding = PaddingMode.PKCS7; m_RIJ.Mode = CipherMode.CBC; m_RIJ.IV = new byte[16]; m_RIJ.BlockSize = 128; m_RIJ.KeySize = 256; m_RIJ.GenerateKey(); //m_PublicKey = m_RSA.ExportCspBlob(false); //m_PrivateKey = m_RSA.ExportCspBlob(true); m_PublicKey = Encoding.UTF8.GetBytes(m_RSA.ToXmlString(false)); m_PrivateKey = Encoding.UTF8.GetBytes(m_RSA.ToXmlString(true)); m_KeyPair = m_RSA.ExportParameters(true); }
public bool ProvjeriPotpisPoruke() { //Dohvaćanje privatnog ključa RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); var javniKljuc = rsa.ExportParameters(true); var sr = new System.IO.StringReader(System.IO.File.ReadAllText(@"javni_kljuc.txt")); var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); javniKljuc = (RSAParameters)xs.Deserialize(sr); rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(javniKljuc); //Citanje kriptiranog teksta i potpisane poruke string kriptiraniTekst = System.IO.File.ReadAllText(@"asimetricno_kriptiranje.txt"); byte[] kriptiraniTekstBajtniOblik = Convert.FromBase64String(kriptiraniTekst); byte[] digitalniPotpis = System.IO.File.ReadAllBytes(@"digitalniPotpis.txt"); //Provjera potpisa return(rsa.VerifyData(kriptiraniTekstBajtniOblik, "SHA512", digitalniPotpis)); }
public async Task JwtTokenGenerator_ShouldBeOk_WhenIsSuTagIsPresentAndIsTrue() { // Arrange var options = Options.Create(new JwtOptions() { TokenLifeTime = 1 }); var publicAndPrivate = new RSACryptoServiceProvider(2048); var key = new RsaSecurityKey(publicAndPrivate.ExportParameters(true)); var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256); var handler = new JwtSecurityTokenHandler(); var sut = new JwtTokenGenerator(options, signingCredentials, handler); // Act var jwtToken = sut.CreateJwtToken(); // Assert var jsonToken = handler.ReadToken(jwtToken); var tokens = handler.ReadToken(jwtToken) as JwtSecurityToken; var isSuClaimValue = tokens.Claims.First(claim => claim.Type == "isSU").Value; Assert.True(isSuClaimValue == "true"); }
private void Test(string Name, int Size) { CspParameters CspParams = new CspParameters() { Flags = CspProviderFlags.UseMachineKeyStore | CspProviderFlags.NoPrompt, KeyContainerName = Name }; Stopwatch Watch = new Stopwatch(); Watch.Start(); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(Size, CspParams); Watch.Stop(); double Ms = (1000.0d * Watch.ElapsedTicks) / Stopwatch.Frequency; RSAParameters Parameters = rsa.ExportParameters(true); Console.Out.WriteLine("Size: " + Size.ToString()); Console.Out.WriteLine("Time: " + Ms.ToString("F2") + " ms"); Console.Out.WriteLine("P Len: " + Parameters.P.Length.ToString()); Console.Out.WriteLine("Q Len: " + Parameters.Q.Length.ToString()); }
public OrderDomains(Options options) { this.options = options; var serviceCollection = new ServiceCollection(); serviceCollection.AddHttpClient(); ServiceProvider services = serviceCollection.BuildServiceProvider(); IHttpClientFactory httpClientFactory = services.GetRequiredService <System.Net.Http.IHttpClientFactory>(); cloudflareClient = new CloudflareClientFactory(options.Username, options.ApiKey, new CloudflareRestClientFactory(httpClientFactory), CloudflareAPIEndpoint.V4Endpoint) .Create(); // RSA service provider var rsaCryptoServiceProvider = new RSACryptoServiceProvider(2048); if (string.IsNullOrEmpty(options.Key)) { Program.LogLine("Generating new key for ACME."); var exportKey = rsaCryptoServiceProvider.ExportCspBlob(true); var strKey = Convert.ToBase64String(exportKey); File.WriteAllText("acmekey.key", strKey); } else { var key = Convert.FromBase64String(File.ReadAllText(options.Key)); rsaCryptoServiceProvider.ImportCspBlob(key); } var rsaKey = RSA.Create(rsaCryptoServiceProvider.ExportParameters(true)); acmeClient = new ACMEClient( new Uri(options.Environment == AcmeEnvironment.ProductionV2 ? ACMEEnvironment.ProductionV2 : ACMEEnvironment.StagingV2), rsaKey, new HttpClient()); }
public void Checking_Message_That_Was_Signed_By_Hospital_For_Should_Return_Success() { // given var cryptoProvider = GetCryptoProvider(); RSAParameters rsaPrivateKeyInfo = cryptoProvider.ExportParameters(true); string publicKeyPem = ExportPublicKey(cryptoProvider); Patient patient = new Patient("joe", "smith", "*****@*****.**"); // simulate having an ID from the DB Hospital hospital = new Hospital("Acme Hospital", publicKeyPem); patient.Id = 124; Document doc1 = new Document(patient.Id, hospital); var message = doc1.ToJson(); string signedMessage = SignData(message, rsaPrivateKeyInfo); // when var signatureService = GetSignatureService(); RSACryptoServiceProvider importedKey = signatureService.ImportPublicKey(publicKeyPem); var result = signatureService.VerifySignature(message, signedMessage, importedKey.ExportParameters(false)); // then result.Should().BeTrue(); }
/// <summary> /// 得到RSA的解谜的密匙对 /// </summary> /// <returns></returns> public static RSAKey GetRASKey() { RSACryptoServiceProvider.UseMachineKeyStore = true; //声明一个指定大小的RSA容器 RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(DWKEYSIZE); //取得RSA容易里的各种参数,根据参数生成公钥和私钥。参数列表 //public byte[] D; d,私钥指数 //public byte[] DP; d mod (p - 1) mod函数是一个求余函数 因为7 除以 3 商2余1,余数1即MOD运算后的结果。 //public byte[] DQ; d mod (q - 1) //public byte[] Exponent; e,公钥指数 //public byte[] InverseQ; (InverseQ)(q) = 1 mod p //public byte[] Modulus; P*Q //public byte[] P; 第一个质数 //public byte[] Q; 第二个质数 RSAParameters p = rsaProvider.ExportParameters(true); return new RSAKey() { PublicKey = ComponentKey(p.Exponent, p.Modulus), PrivateKey = ComponentKey(p.D, p.Modulus) }; }
public static String ToXmlString(RSACryptoServiceProvider rsa, bool includePrivateParameters) { // we extend appropriately for private components RSAParameters rsaParams = rsa.ExportParameters(includePrivateParameters); StringBuilder sb = new StringBuilder(); sb.Append("<RSAKeyValue>"); // Add the modulus sb.Append("<Modulus>" + Convert.ToBase64String(rsaParams.Modulus) + "</Modulus>"); // Add the exponent sb.Append("<Exponent>" + Convert.ToBase64String(rsaParams.Exponent) + "</Exponent>"); if (includePrivateParameters) { // Add the private components sb.Append("<P>" + Convert.ToBase64String(rsaParams.P) + "</P>"); sb.Append("<Q>" + Convert.ToBase64String(rsaParams.Q) + "</Q>"); sb.Append("<DP>" + Convert.ToBase64String(rsaParams.DP) + "</DP>"); sb.Append("<DQ>" + Convert.ToBase64String(rsaParams.DQ) + "</DQ>"); sb.Append("<InverseQ>" + Convert.ToBase64String(rsaParams.InverseQ) + "</InverseQ>"); sb.Append("<D>" + Convert.ToBase64String(rsaParams.D) + "</D>"); } sb.Append("</RSAKeyValue>"); return(sb.ToString()); }
public static void ExportPrivateKey(RSACryptoServiceProvider rsa, string kId, string outputPath, byte[] password, byte[] salt) { var rsaParams = rsa.ExportParameters(true); var ms = new MemoryStream(); BinaryWriter w = new BinaryWriter(ms); w.WriteLengthPrefixedBuffer(rsaParams.D); w.WriteLengthPrefixedBuffer(rsaParams.DP); w.WriteLengthPrefixedBuffer(rsaParams.DQ); w.WriteLengthPrefixedBuffer(rsaParams.Exponent); w.WriteLengthPrefixedBuffer(rsaParams.InverseQ); w.WriteLengthPrefixedBuffer(rsaParams.Modulus); w.WriteLengthPrefixedBuffer(rsaParams.P); w.WriteLengthPrefixedBuffer(rsaParams.Q); w.Flush(); var aes = Aes.Create(); aes.Key = password; aes.GenerateIV(); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; var transform = aes.CreateEncryptor(); var encrypted = new MemoryStream(); encrypted.Write(aes.IV, 0, (int)aes.IV.Length); using (CryptoStream stream = new CryptoStream(encrypted, transform, CryptoStreamMode.Write)) { stream.Write(ms.ToArray(), 0, (int)ms.Length); stream.FlushFinalBlock(); } File.WriteAllText(Path.Combine(outputPath, kId + ".key.private"), Convert.ToBase64String(salt) + "." + Convert.ToBase64String(encrypted.ToArray())); }
private void button_Code_Click(object sender, EventArgs e) { RSACryptoServiceProvider RSA1 = new RSACryptoServiceProvider(); string message = textBox_ToCode.Text; char[] dataASCII = message.ToCharArray(0, message.Length); int i = 0; byte[] data = new byte[message.Length]; foreach (var item in dataASCII) { data[i] = Convert.ToByte((int)item); i++; } byte[] EncryptedASCII = RSA1.Encrypt(data, true); // szyfrowanie kodu ASCII i = 0; char[] encrypted = new char[EncryptedASCII.Length]; foreach (var item in EncryptedASCII) { encrypted[i] = (char)item; //encrypted[i] = (char)(item+3); // dodatkowe działanie + szyfr cezara i++; } string enMessage = string.Join("", encrypted); textBox_Coded.Text = enMessage; MyParameters = RSA1.ExportParameters(true); textBox_e.Text = "e = " + BitConverter.ToString(MyParameters.Exponent, 0); textBox_p.Text = "n = " + BitConverter.ToString(MyParameters.Modulus, 0); }
// Uncomment the following 2 lines and run API to generate your encryption codes. // Copy and past output to your Web.config file //[WebMethod] public void generate_1024_Key() {streamJson(getEncryptedString(1024));} //[WebMethod] public void generate_2048_Key() {streamJson(getEncryptedString(2048));} private string getEncryptedString(int EncryptionPadding) { var csp = new RSACryptoServiceProvider(EncryptionPadding); var key = csp.ExportParameters(true); string KeyString; { var sw = new System.IO.StringWriter(); var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); xs.Serialize(sw, key); KeyString = sw.ToString(); } return(string.Format("<RSAKeyValue><Exponent>{0}</Exponent><Modulus>{1}</Modulus><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>", Convert.ToBase64String(key.Exponent), Convert.ToBase64String(key.Modulus), Convert.ToBase64String(key.P), Convert.ToBase64String(key.Q), Convert.ToBase64String(key.DP), Convert.ToBase64String(key.DQ), Convert.ToBase64String(key.InverseQ), Convert.ToBase64String(key.D) ) ); }
internal static bool GetKey(bool isServer, out RSAParameters CSPRSAPARAM) { CSPRSAPARAM = default(RSAParameters); RSACryptoServiceProvider rsaCrypt = null; bool result; try { string _rsaKey = ConfigurationSettings.AppSettings["RSAKey"].ToString(); if (_rsaKey != string.Empty) { rsaCrypt = new RSACryptoServiceProvider(); rsaCrypt.FromXmlString(_rsaKey.Replace("(", "<").Replace(")", ">")); CSPRSAPARAM = rsaCrypt.ExportParameters(isServer); result = true; } else { result = false; } } catch (Exception ex) { string _msg = ex.ToString(); result = false; } finally { if (rsaCrypt != null) { rsaCrypt.Clear(); } rsaCrypt = null; } return(result); }
public static void Run() { var importedKey = PEM.Read(@"resources\example.org.key", "RSA PRIVATE KEY"); Console.WriteLine("Imported key length: {0}", importedKey.Length); using var rsa = new RSACryptoServiceProvider(); rsa.ImportRSAPrivateKey(importedKey, out _); var parameters = rsa.ExportParameters(true); var parametersLength = parameters.D.Length + parameters.DP.Length + parameters.DQ.Length + parameters.Exponent.Length + parameters.InverseQ.Length + parameters.Modulus.Length + parameters.P.Length + parameters.Q.Length; Console.WriteLine(); Console.WriteLine("Parameters length: {0}", parametersLength); Console.WriteLine("Modulus: {0} ({1})", parameters.Modulus.Length, importedKey.IndexOf(parameters.Modulus)); Console.WriteLine("Exponent: {0} ({1})", parameters.Exponent.Length, importedKey.IndexOf(parameters.Exponent)); Console.WriteLine("D: {0} ({1})", parameters.D.Length, importedKey.IndexOf(parameters.D)); Console.WriteLine("P: {0} ({1})", parameters.P.Length, importedKey.IndexOf(parameters.P)); Console.WriteLine("Q: {0} ({1})", parameters.Q.Length, importedKey.IndexOf(parameters.Q)); Console.WriteLine("DP: {0} ({1})", parameters.DP.Length, importedKey.IndexOf(parameters.DP)); Console.WriteLine("DQ: {0} ({1})", parameters.DQ.Length, importedKey.IndexOf(parameters.DQ)); Console.WriteLine("InverseQ: {0} ({1})", parameters.InverseQ.Length, importedKey.IndexOf(parameters.InverseQ)); var exportedKey = rsa.ExportRSAPrivateKey(); Console.WriteLine(); Console.WriteLine("Exported key length: {0}", exportedKey.Length); Console.WriteLine("Matches exported key: {0}", importedKey.IndexOf(exportedKey) == 0); }
public string Encrypt(string strData) { var byteData = Encoding.UTF8.GetBytes(strData); using (var rsa = new RSACryptoServiceProvider(1024)) { try { var rsaParameters = rsa.ExportParameters(false); rsa.FromXmlString(publicKey); var encryptedData = rsa.Encrypt(byteData, false); var base64Encrypted = Convert.ToBase64String(encryptedData); return(base64Encrypted); } finally { rsa.PersistKeyInCsp = false; } } }
public RSACryptoServiceProvider CreateKey() { RSACryptoServiceProvider rsa = null; if (!File.Exists(_keyFile)) { Trace.Info("Creating new RSA key using 2048-bit key length"); rsa = new RSACryptoServiceProvider(2048); // Now write the parameters to disk SaveParameters(rsa.ExportParameters(true)); Trace.Info("Successfully saved RSA key parameters to file {0}", _keyFile); } else { Trace.Info("Found existing RSA key parameters file {0}", _keyFile); rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(LoadParameters()); } return(rsa); }
/// <summary> /// 创建加密钥,解密钥 /// </summary> public void CreateRSAKey() { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); RSAParameters keys = rsa.ExportParameters(true); //公钥 String pkxml = "<root>\n<Modulus>" + ToHexString(keys.Modulus) + "</Modulus>"; pkxml += "\n<Exponent>" + ToHexString(keys.Exponent) + "</Exponent>\n</root>"; //私钥 String psxml = "<root>\n<Modulus>" + ToHexString(keys.Modulus) + "</Modulus>"; psxml += "\n<Exponent>" + ToHexString(keys.Exponent) + "</Exponent>"; psxml += "\n<D>" + ToHexString(keys.D) + "</D>"; psxml += "\n<DP>" + ToHexString(keys.DP) + "</DP>"; psxml += "\n<P>" + ToHexString(keys.P) + "</P>"; psxml += "\n<Q>" + ToHexString(keys.Q) + "</Q>"; psxml += "\n<DQ>" + ToHexString(keys.DQ) + "</DQ>"; psxml += "\n<InverseQ>" + ToHexString(keys.InverseQ) + "</InverseQ>\n</root>"; SaveToFile("publickey.xml", pkxml); SaveToFile("privatekey.xml", psxml); }
public UserInformation Login(string username, string password, out UserDatabase data) { UserDatabase dataComp = new UserDatabase(this.userDatabasePath); var user = dataComp.GetUser(username); if (user != null && user.IsPasswordValid(password)) { var userCert = new X509Certificate2(user.PublicCertificate); if (userCert == null) { throw new Exception("Certificate error."); } if (CertificateValidator.VerifyCertificate(userCert) == false) { throw new Exception("Certificate is invalid."); } byte[] keyRaw = File.ReadAllBytes(this.privateKeyPath); var privateParameters = new KeyFileParser(keyRaw).GetParameters(); RSACryptoServiceProvider publicKeyProvider = (RSACryptoServiceProvider)userCert.PublicKey.Key; if (!RsaMachine.AreKeysMatched(publicKeyProvider.ExportParameters(false), privateParameters)) { throw new Exception("The given private key does not match this user's certificate."); } data = dataComp; return(new UserInformation(user, privateParameters)); } else { throw new Exception("Invalid username or password."); } }
private string GenerateToken(Person p) { IIdentity identity = new ClaimsIdentity("local"); var user = new ClaimsIdentity(identity); user.AddClaim(new Claim("role", "admin")); user.AddClaim(new Claim("role", "user")); var rsa = new RSACryptoServiceProvider(2048); var key = new RsaSecurityKey(rsa.ExportParameters(true)); var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); var tokenDescriptor = new SecurityTokenDescriptor() { Issuer = "http://localhost:5000", Audience = "api", SigningCredentials = signingCredentials, Subject = user }; var securityToken = handler.CreateJwtSecurityToken(tokenDescriptor); var token = handler.WriteToken(securityToken); return(token); }
public RsaData(int keySize = 2048) { RSACryptoServiceProvider.UseMachineKeyStore = false; var rsaProvider = new RSACryptoServiceProvider(keySize); rsaProvider.PersistKeyInCsp = false; // Execution time depends on the keySize RsaParams = rsaProvider.ExportParameters(true); // Let's use little-endian RsaParams.D = RsaParams.D.Reverse().ToArray(); RsaParams.DP = RsaParams.DP.Reverse().ToArray(); RsaParams.DQ = RsaParams.DQ.Reverse().ToArray(); RsaParams.Exponent = RsaParams.Exponent.Reverse().ToArray(); RsaParams.InverseQ = RsaParams.InverseQ.Reverse().ToArray(); RsaParams.Modulus = RsaParams.Modulus.Reverse().ToArray(); RsaParams.P = RsaParams.P.Reverse().ToArray(); RsaParams.Q = RsaParams.Q.Reverse().ToArray(); // We just need it for rsa data generation rsaProvider = null; }
public static RSAParameters ToPublicRsaParameters(this RSAParameters privateKey) { using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(privateKey); return rsa.ExportParameters(includePrivateParameters: false); } }
/// <summary> /// 得到RSA的解谜的密匙对 /// </summary> /// <returns></returns> public static RSAKey GetRASKey() { RSACryptoServiceProvider.UseMachineKeyStore = true; //声明一个指定大小的RSA容器 RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(DWKEYSIZE); //取得RSA容易里的各种参数 RSAParameters p = rsaProvider.ExportParameters(true); return new RSAKey() { PrivateKey = ToBase64Key(rsaProvider.ToXmlString(true)), PublicKey = ToBase64Key(rsaProvider.ToXmlString(false)), PublicKeyExponent = BytesToHexString(p.Exponent), PublicKeyModulus = BytesToHexString(p.Modulus) }; }
public static void NonExportable_Ephemeral() { CspParameters cspParameters = new CspParameters { Flags = CspProviderFlags.UseNonExportableKey, }; using (var rsa = new RSACryptoServiceProvider(cspParameters)) { // Ephemeral keys don't successfully request the exportable bit. Assert.ThrowsAny<CryptographicException>(() => rsa.CspKeyContainerInfo.Exportable); Assert.Throws<CryptographicException>(() => rsa.ExportCspBlob(true)); Assert.Throws<CryptographicException>(() => rsa.ExportParameters(true)); } }
/// <summary> /// Generates a new set of keys /// </summary> /// <returns></returns> public static RSAParameters CreateKeys() { CspParameters xCSP = new CspParameters(); RSACryptoServiceProvider xRSA = new RSACryptoServiceProvider(xCSP); return xRSA.ExportParameters(true); }
public static void ImportReset() { using (RSA rsa = new RSACryptoServiceProvider()) { RSAParameters exported = rsa.ExportParameters(true); RSAParameters imported; // Ensure that we cause the KeySize value to change. if (rsa.KeySize == 1024) { imported = TestData.RSA2048Params; } else { imported = TestData.RSA1024Params; } Assert.NotEqual(imported.Modulus.Length * 8, rsa.KeySize); Assert.NotEqual(imported.Modulus, exported.Modulus); rsa.ImportParameters(imported); Assert.Equal(imported.Modulus.Length * 8, rsa.KeySize); exported = rsa.ExportParameters(true); AssertKeyEquals(ref imported, ref exported); } }
public static void ThreadLoad () { RSA rsa = new RSACryptoServiceProvider (384); rsa.ExportParameters (false); }
private static void RSATest() { var publicPrivateRsa = new RSACryptoServiceProvider ( new CspParameters() { KeyContainerName = "PublicPrivateKeys", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ) { PersistKeyInCsp = true, }; var publicRsa = new RSACryptoServiceProvider( new CspParameters() { KeyContainerName = "PublicKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ) { PersistKeyInCsp = true }; //Export the key. publicRsa.ImportParameters(publicPrivateRsa.ExportParameters(false)); Console.WriteLine(publicRsa.ToXmlString(false)); Console.WriteLine(publicPrivateRsa.ToXmlString(false)); //Dispose those two CSPs. using (publicRsa) { publicRsa.Clear(); } using (publicPrivateRsa) { publicRsa.Clear(); } //Retrieve keys publicPrivateRsa = new RSACryptoServiceProvider( new CspParameters() { KeyContainerName = "PublicPrivateKeys", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ); publicRsa = new RSACryptoServiceProvider( new CspParameters() { KeyContainerName = "PublicKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ); Console.WriteLine(publicRsa.ToXmlString(false)); Console.WriteLine(publicPrivateRsa.ToXmlString(false)); using (publicRsa) { publicRsa.Clear(); } using (publicPrivateRsa) { publicRsa.Clear(); } }
private void RequestSecureConnection() { if (!_connected) return; _rsa = new RSACryptoServiceProvider(1024); RSAParameters keyInfo = _rsa.ExportParameters(false); byte[] data = PackageFactory.Pack(PackageType.RequestSecureConnection, new SecurityRequestData(keyInfo.Exponent, keyInfo.Modulus)); BeginSend(data); }
/* static void Main() { try { //Create a UnicodeEncoder to convert between byte array and string. UnicodeEncoding ByteConverter = new UnicodeEncoding(); //Create byte arrays to hold original, encrypted, and decrypted data. byte[] dataToEncrypt = ByteConverter.GetBytes("Data to Encrypt"); byte[] encryptedData; byte[] decryptedData; //Create a new instance of RSACryptoServiceProvider to generate //public and private key data. RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); //Pass the data to ENCRYPT, the public key information //(using RSACryptoServiceProvider.ExportParameters(false), //and a boolean flag specifying no OAEP padding. encryptedData = RSAEncrypt(dataToEncrypt,RSA.ExportParameters(false), false); //Pass the data to DECRYPT, the private key information //(using RSACryptoServiceProvider.ExportParameters(true), //and a boolean flag specifying no OAEP padding. decryptedData = RSADecrypt(encryptedData,RSA.ExportParameters(true), false); //Display the decrypted plaintext to the console. Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData)); } catch(ArgumentNullException) { //Catch this exception in case the encryption did //not succeed. Console.WriteLine("Encryption failed."); } } */ public void RSAcreatekeys(int size) { //Generate a public/private key pair. RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(size); rsaks = size; //Save the public key information to an RSAParameters structure. rsaki = RSA.ExportParameters(true); }
public static void UnusualExponentImportExport() { // Most choices for the Exponent value in an RSA key use a Fermat prime. // Since a Fermat prime is 2^(2^m) + 1, it always only has two bits set, and // frequently has the form { 0x01, [some number of 0x00s], 0x01 }, which has the same // representation in both big- and little-endian. // // The only real requirement for an Exponent value is that it be coprime to (p-1)(q-1). // So here we'll use the (non-Fermat) prime value 433 (0x01B1) to ensure big-endian export. RSAParameters unusualExponentParameters = TestData.UnusualExponentParameters; RSAParameters exported; using (RSA rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(unusualExponentParameters); exported = rsa.ExportParameters(true); } // Exponent is the most likely to fail, the rest just otherwise ensure that Export // isn't losing data. AssertKeyEquals(ref unusualExponentParameters, ref exported); }
public static void NonExportable_Persisted() { CspParameters cspParameters = new CspParameters { KeyContainerName = Guid.NewGuid().ToString(), Flags = CspProviderFlags.UseNonExportableKey, }; using (new RsaKeyLifetime(cspParameters)) { using (var rsa = new RSACryptoServiceProvider(cspParameters)) { Assert.False(rsa.CspKeyContainerInfo.Exportable, "rsa.CspKeyContainerInfo.Exportable"); Assert.Throws<CryptographicException>(() => rsa.ExportCspBlob(true)); Assert.Throws<CryptographicException>(() => rsa.ExportParameters(true)); } } }
public static RSAParameters CreatePrivateKeyParams(RsaKeyLengths rsaKeyLength = RsaKeyLengths.Bit2048) { using (var rsa = new RSACryptoServiceProvider((int)rsaKeyLength)) { return rsa.ExportParameters(includePrivateParameters: true); } }
public static void MultiExport() { RSAParameters imported = TestData.RSA1024Params; using (RSA rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(imported); RSAParameters exportedPrivate = rsa.ExportParameters(true); RSAParameters exportedPrivate2 = rsa.ExportParameters(true); RSAParameters exportedPublic = rsa.ExportParameters(false); RSAParameters exportedPublic2 = rsa.ExportParameters(false); RSAParameters exportedPrivate3 = rsa.ExportParameters(true); RSAParameters exportedPublic3 = rsa.ExportParameters(false); AssertKeyEquals(ref imported, ref exportedPrivate); Assert.Equal(imported.Modulus, exportedPublic.Modulus); Assert.Equal(imported.Exponent, exportedPublic.Exponent); Assert.Null(exportedPublic.D); ValidateParameters(ref exportedPublic); AssertKeyEquals(ref exportedPrivate, ref exportedPrivate2); AssertKeyEquals(ref exportedPrivate, ref exportedPrivate3); AssertKeyEquals(ref exportedPublic, ref exportedPublic2); AssertKeyEquals(ref exportedPublic, ref exportedPublic3); } }
/// <summary> /// Enroll the authenticator with the server /// </summary> public bool Enroll(EnrollState state) { // clear error state.Error = null; try { var data = new NameValueCollection(); var cookies = state.Cookies = state.Cookies ?? new CookieContainer(); string response; if (string.IsNullOrEmpty(state.OAuthToken) == true) { // get session response = Request(COMMUNITY_BASE + "/login/home?goto=0", "GET", null, cookies); // get the user's RSA key data.Add("username", state.Username); response = Request(COMMUNITY_BASE + "/login/getrsakey", "POST", data, cookies); var rsaresponse = JObject.Parse(response); if (rsaresponse.SelectToken("success").Value<bool>() != true) { throw new InvalidEnrollResponseException("Cannot get steam information for user: "******"steamid").Value<string>(); // encrypt password with RSA key RNGCryptoServiceProvider random = new RNGCryptoServiceProvider(); byte[] encryptedPassword; using (var rsa = new RSACryptoServiceProvider()) { var passwordBytes = Encoding.ASCII.GetBytes(state.Password); var p = rsa.ExportParameters(false); p.Exponent = Authenticator.StringToByteArray(rsaresponse.SelectToken("publickey_exp").Value<string>()); p.Modulus = Authenticator.StringToByteArray(rsaresponse.SelectToken("publickey_mod").Value<string>()); rsa.ImportParameters(p); encryptedPassword = rsa.Encrypt(passwordBytes, false); } // login request data = new NameValueCollection(); data.Add("password", Convert.ToBase64String(encryptedPassword)); data.Add("username", state.Username); data.Add("twofactorcode", ""); data.Add("emailauth", (state.EmailAuthText != null ? state.EmailAuthText : string.Empty)); data.Add("loginfriendlyname", "#login_emailauth_friendlyname_mobile"); data.Add("captchagid", (state.CaptchaId != null ? state.CaptchaId : "-1")); data.Add("captcha_text", (state.CaptchaText != null ? state.CaptchaText : "enter above characters")); data.Add("emailsteamid", (state.EmailAuthText != null ? state.SteamId : string.Empty)); data.Add("rsatimestamp", rsaresponse.SelectToken("timestamp").Value<string>()); data.Add("remember_login", "false"); data.Add("oauth_client_id", "DE45CD61"); data.Add("oauth_scope", "read_profile write_profile read_client write_client"); data.Add("donotache", new DateTime().ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds.ToString()); response = Request(COMMUNITY_BASE + "/mobilelogin/dologin/", "POST", data, cookies); Dictionary<string, object> loginresponse = JsonConvert.DeserializeObject<Dictionary<string, object>>(response); // require captcha if (loginresponse.ContainsKey("captcha_needed") == true && (bool)loginresponse["captcha_needed"] == true) { state.RequiresCaptcha = true; state.CaptchaId = (string)loginresponse["captcha_gid"]; state.CaptchaUrl = COMMUNITY_BASE + "/public/captcha.php?gid=" + state.CaptchaId; } else { state.RequiresCaptcha = false; state.CaptchaId = null; state.CaptchaUrl = null; state.CaptchaText = null; } // require email auth if (loginresponse.ContainsKey("emailauth_needed") == true && (bool)loginresponse["emailauth_needed"] == true) { if (loginresponse.ContainsKey("emaildomain") == true) { var emaildomain = (string)loginresponse["emaildomain"]; if (string.IsNullOrEmpty(emaildomain) == false) { state.EmailDomain = emaildomain; } } state.RequiresEmailAuth = true; } else { state.EmailDomain = null; state.RequiresEmailAuth = false; } // require email auth if (loginresponse.ContainsKey("requires_twofactor") == true && (bool)loginresponse["requires_twofactor"] == true) { state.Requires2FA = true; } else { state.Requires2FA = false; } // if we didn't login, return the result if (loginresponse.ContainsKey("login_complete") == false || (bool)loginresponse["login_complete"] == false || loginresponse.ContainsKey("oauth") == false) { if (loginresponse.ContainsKey("oauth") == false) { state.Error = "No OAuth token in response"; } if (loginresponse.ContainsKey("message") == true) { state.Error = (string)loginresponse["message"]; } return false; } // get the OAuth token - is stringified json string oauth = (string)loginresponse["oauth"]; var oauthjson = JObject.Parse(oauth); state.OAuthToken = oauthjson.SelectToken("oauth_token").Value<string>(); } // login to webapi data.Clear(); data.Add("access_token", state.OAuthToken); response = Request(WEBAPI_BASE + "/ISteamWebUserPresenceOAuth/Logon/v0001", "POST", data); if (state.RequiresActivation == false) { // add a new authenticator data.Clear(); string deviceId = BuildRandomId(); data.Add("access_token", state.OAuthToken); data.Add("steamid", state.SteamId); data.Add("authenticator_type", "1"); data.Add("device_identifier", deviceId); response = Request(WEBAPI_BASE + "/ITwoFactorService/AddAuthenticator/v0001", "POST", data); var tfaresponse = JObject.Parse(response); if (response.IndexOf("revocation_code") == -1) { // invalid response state.OAuthToken = null; // force new login state.RequiresLogin = true; state.Cookies = null; state.Error = "Invalid response from Steam: " + response; return false; } // save data into this authenticator var secret = tfaresponse.SelectToken("response.shared_secret").Value<string>(); this.SecretKey = Convert.FromBase64String(secret); this.Serial = tfaresponse.SelectToken("response.serial_number").Value<string>(); this.DeviceId = deviceId; this.RevocationCode = state.RevocationCode = tfaresponse.SelectToken("response.revocation_code").Value<string>(); // calculate server drift long servertime = tfaresponse.SelectToken("response.server_time").Value<long>() * 1000; ServerTimeDiff = servertime - CurrentTime; LastServerTime = DateTime.Now.Ticks; // send authorisation email data.Clear(); data.Add("access_token", state.OAuthToken); data.Add("steamid", state.SteamId); data.Add("email_type", "1"); data.Add("include_activation", "1"); response = Request(WEBAPI_BASE + "/ITwoFactorService/SendEmail/v0001", "POST", data); state.RequiresActivation = true; return false; } // finalize adding the authenticator data.Clear(); data.Add("access_token", state.OAuthToken); data.Add("steamid", state.SteamId); data.Add("activation_code", state.ActivationCode); // try and authorise ServerTimeDiff -= 40000; // start at previous interval var retries = 0; while (state.RequiresActivation == true && retries < ENROLL_ACTIVATE_RETRIES) { data.Add("authenticator_code", this.CalculateCode(false)); data.Add("authenticator_time", this.ServerTime.ToString()); response = Request(WEBAPI_BASE + "/ITwoFactorService/FinalizeAddAuthenticator/v0001", "POST", data); var finalizeresponse = JObject.Parse(response); if (response.IndexOf("status") != -1 && finalizeresponse.SelectToken("response.status").Value<int>() == INVALID_ACTIVATION_CODE) { state.Error = "Invalid activation code"; return false; } // reset our time if (response.IndexOf("server_time") != -1) { long servertime = finalizeresponse.SelectToken("response.server_time").Value<long>() * 1000; ServerTimeDiff = servertime - CurrentTime; LastServerTime = DateTime.Now.Ticks; } // check success if (finalizeresponse.SelectToken("response.success").Value<bool>() == true) { if (response.IndexOf("want_more") != -1 && finalizeresponse.SelectToken("response.want_more").Value<bool>() == true) { ServerTimeDiff += 30000L; retries++; continue; } state.RequiresActivation = false; break; } ServerTimeDiff += 30000L; retries++; } if (state.RequiresActivation == true) { state.Error = "There was a problem activating. There might be an issue with the Steam servers. Please try again later."; return false; } // mark and successful and return key state.Success = true; state.SecretKey = Authenticator.ByteArrayToString(this.SecretKey); // send confirmation email data.Clear(); data.Add("access_token", state.OAuthToken); data.Add("steamid", state.SteamId); data.Add("email_type", "2"); response = Request(WEBAPI_BASE + "/ITwoFactorService/SendEmail/v0001", "POST", data); return true; } catch (InvalidRequestException ex) { throw new InvalidEnrollResponseException("Error enrolling new authenticator", ex); } }
public static void PublicOnlyPrivateExport() { RSAParameters imported = new RSAParameters { Modulus = TestData.RSA1024Params.Modulus, Exponent = TestData.RSA1024Params.Exponent, }; using (RSA rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(imported); Assert.Throws<CryptographicException>(() => rsa.ExportParameters(true)); } }
public static void RSAParametersToBlob_PublicPrivate() { byte[] blob; using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(TestData.RSA1024Params); blob = rsa.ExportCspBlob(true); } RSAParameters exported; using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportCspBlob(blob); Assert.False(rsa.PublicOnly); exported = rsa.ExportParameters(true); } RSAParameters expected = TestData.RSA1024Params; ImportExport.AssertKeyEquals(ref expected, ref exported); }
public static bool VerifyLicenseKeyText(this string licenseKeyText, out LicenseKey key) { var publicRsaProvider = new RSACryptoServiceProvider(); publicRsaProvider.FromXmlString(LicensePublicKey); var publicKeyParams = publicRsaProvider.ExportParameters(false); key = licenseKeyText.ToLicenseKey(); var originalData = key.GetHashKeyToSign().ToUtf8Bytes(); var signedData = Convert.FromBase64String(key.Hash); return VerifySignedHash(originalData, signedData, publicKeyParams); }
public static void RSAParametersToBlob_PublicOnly() { byte[] blob; using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(TestData.RSA1024Params); blob = rsa.ExportCspBlob(false); } RSAParameters exported; using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportCspBlob(blob); Assert.True(rsa.PublicOnly); exported = rsa.ExportParameters(false); } RSAParameters expected = new RSAParameters { Modulus = TestData.RSA1024Params.Modulus, Exponent = TestData.RSA1024Params.Exponent, }; ImportExport.AssertKeyEquals(ref expected, ref exported); }
/// <summary> /// Enroll the authenticator with the server /// </summary> public bool Enroll(EnrollState state) { // clear error state.Error = null; try { var data = new NameValueCollection(); var cookies = state.Cookies = state.Cookies ?? new CookieContainer(); string response; if (string.IsNullOrEmpty(state.OAuthToken) == true) { // get session if (cookies.Count == 0) { cookies.Add(new Cookie("mobileClientVersion", "3067969+%282.1.3%29", "/", ".steamcommunity.com")); cookies.Add(new Cookie("mobileClient", "android", "/", ".steamcommunity.com")); cookies.Add(new Cookie("steamid", "", "/", ".steamcommunity.com")); cookies.Add(new Cookie("steamLogin", "", "/", ".steamcommunity.com")); cookies.Add(new Cookie("Steam_Language", "english", "/", ".steamcommunity.com")); cookies.Add(new Cookie("dob", "", "/", ".steamcommunity.com")); NameValueCollection headers = new NameValueCollection(); headers.Add("X-Requested-With", "com.valvesoftware.android.steam.community"); response = Request("https://steamcommunity.com/login?oauth_client_id=DE45CD61&oauth_scope=read_profile%20write_profile%20read_client%20write_client", "GET", null, cookies, headers); } // get the user's RSA key data.Add("username", state.Username); response = Request(COMMUNITY_BASE + "/login/getrsakey", "POST", data, cookies); var rsaresponse = JObject.Parse(response); if (rsaresponse.SelectToken("success").Value<bool>() != true) { throw new InvalidEnrollResponseException("Cannot get steam information for user: "******"steamid").Value<string>(); // encrypt password with RSA key RNGCryptoServiceProvider random = new RNGCryptoServiceProvider(); byte[] encryptedPassword; using (var rsa = new RSACryptoServiceProvider()) { var passwordBytes = Encoding.ASCII.GetBytes(state.Password); var p = rsa.ExportParameters(false); p.Exponent = Authenticator.StringToByteArray(rsaresponse.SelectToken("publickey_exp").Value<string>()); p.Modulus = Authenticator.StringToByteArray(rsaresponse.SelectToken("publickey_mod").Value<string>()); rsa.ImportParameters(p); encryptedPassword = rsa.Encrypt(passwordBytes, false); } // login request data = new NameValueCollection(); data.Add("password", Convert.ToBase64String(encryptedPassword)); data.Add("username", state.Username); data.Add("twofactorcode", ""); data.Add("emailauth", (state.EmailAuthText != null ? state.EmailAuthText : string.Empty)); data.Add("loginfriendlyname", "#login_emailauth_friendlyname_mobile"); data.Add("captchagid", (state.CaptchaId != null ? state.CaptchaId : "-1")); data.Add("captcha_text", (state.CaptchaText != null ? state.CaptchaText : "enter above characters")); data.Add("emailsteamid", (state.EmailAuthText != null ? state.SteamId ?? string.Empty : string.Empty)); data.Add("rsatimestamp", rsaresponse.SelectToken("timestamp").Value<string>()); data.Add("remember_login", "false"); data.Add("oauth_client_id", "DE45CD61"); data.Add("oauth_scope", "read_profile write_profile read_client write_client"); data.Add("donotache", new DateTime().ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds.ToString()); response = Request(COMMUNITY_BASE + "/login/dologin/", "POST", data, cookies); Dictionary<string, object> loginresponse = JsonConvert.DeserializeObject<Dictionary<string, object>>(response); if (loginresponse.ContainsKey("emailsteamid") == true) { state.SteamId = loginresponse["emailsteamid"] as string; } // require captcha if (loginresponse.ContainsKey("captcha_needed") == true && (bool)loginresponse["captcha_needed"] == true) { state.RequiresCaptcha = true; state.CaptchaId = (string)loginresponse["captcha_gid"]; state.CaptchaUrl = COMMUNITY_BASE + "/public/captcha.php?gid=" + state.CaptchaId; } else { state.RequiresCaptcha = false; state.CaptchaId = null; state.CaptchaUrl = null; state.CaptchaText = null; } // require email auth if (loginresponse.ContainsKey("emailauth_needed") == true && (bool)loginresponse["emailauth_needed"] == true) { if (loginresponse.ContainsKey("emaildomain") == true) { var emaildomain = (string)loginresponse["emaildomain"]; if (string.IsNullOrEmpty(emaildomain) == false) { state.EmailDomain = emaildomain; } } state.RequiresEmailAuth = true; } else { state.EmailDomain = null; state.RequiresEmailAuth = false; } // require email auth if (loginresponse.ContainsKey("requires_twofactor") == true && (bool)loginresponse["requires_twofactor"] == true) { state.Requires2FA = true; } else { state.Requires2FA = false; } // if we didn't login, return the result if (loginresponse.ContainsKey("login_complete") == false || (bool)loginresponse["login_complete"] == false || loginresponse.ContainsKey("oauth") == false) { if (loginresponse.ContainsKey("oauth") == false) { state.Error = "No OAuth token in response"; } if (loginresponse.ContainsKey("message") == true) { state.Error = (string)loginresponse["message"]; } return false; } // get the OAuth token - is stringified json string oauth = (string)loginresponse["oauth"]; var oauthjson = JObject.Parse(oauth); state.OAuthToken = oauthjson.SelectToken("oauth_token").Value<string>(); if (oauthjson.SelectToken("steamid") != null) { state.SteamId = oauthjson.SelectToken("steamid").Value<string>(); } } // login to webapi data.Clear(); data.Add("access_token", state.OAuthToken); response = Request(WEBAPI_BASE + "/ISteamWebUserPresenceOAuth/Logon/v0001", "POST", data); var sessionid = cookies.GetCookies(new Uri(COMMUNITY_BASE + "/"))["sessionid"].Value; if (state.RequiresActivation == false) { data.Clear(); data.Add("op", "has_phone"); data.Add("arg", "null"); data.Add("sessionid", sessionid); response = Request(COMMUNITY_BASE + "/steamguard/phoneajax", "POST", data, cookies); var jsonresponse = JObject.Parse(response); bool hasPhone = jsonresponse.SelectToken("has_phone").Value<Boolean>(); if (hasPhone == false) { state.OAuthToken = null; // force new login state.RequiresLogin = true; state.Cookies = null; state.Error = "Your Steam account must have a SMS-capable phone number attached. Go into Account Details of the Steam client or Steam website and click Add a Phone Number."; return false; } //response = Request(COMMUNITY_BASE + "/steamguard/phone_checksms?bForTwoFactor=1&bRevoke2fOnCancel=", "GET", null, cookies); // add a new authenticator data.Clear(); string deviceId = BuildRandomId(); data.Add("access_token", state.OAuthToken); data.Add("steamid", state.SteamId); data.Add("authenticator_type", "1"); data.Add("device_identifier", deviceId); data.Add("sms_phone_id", "1"); response = Request(WEBAPI_BASE + "/ITwoFactorService/AddAuthenticator/v0001", "POST", data); var tfaresponse = JObject.Parse(response); if (response.IndexOf("status") == -1 && tfaresponse.SelectToken("response.status").Value<int>() == 84) { // invalid response state.OAuthToken = null; // force new login state.RequiresLogin = true; state.Cookies = null; state.Error = "Unable to send SMS. Check your phone is registered on your Steam account."; return false; } if (response.IndexOf("shared_secret") == -1) { // invalid response state.OAuthToken = null; // force new login state.RequiresLogin = true; state.Cookies = null; state.Error = "Invalid response from Steam: " + response; return false; } // save data into this authenticator var secret = tfaresponse.SelectToken("response.shared_secret").Value<string>(); this.SecretKey = Convert.FromBase64String(secret); this.Serial = tfaresponse.SelectToken("response.serial_number").Value<string>(); this.DeviceId = deviceId; state.RevocationCode = tfaresponse.SelectToken("response.revocation_code").Value<string>(); // add the steamid into the data var steamdata = JObject.Parse(tfaresponse.SelectToken("response").ToString()); if (steamdata.SelectToken("steamid") == null) { steamdata.Add("steamid", state.SteamId); } if (steamdata.SelectToken("steamguard_scheme") == null) { steamdata.Add("steamguard_scheme", "2"); } this.SteamData = steamdata.ToString(Newtonsoft.Json.Formatting.None); // calculate server drift long servertime = tfaresponse.SelectToken("response.server_time").Value<long>() * 1000; ServerTimeDiff = servertime - CurrentTime; LastServerTime = DateTime.Now.Ticks; state.RequiresActivation = true; return false; } // finalize adding the authenticator data.Clear(); data.Add("access_token", state.OAuthToken); data.Add("steamid", state.SteamId); data.Add("activation_code", state.ActivationCode); // try and authorise var retries = 0; while (state.RequiresActivation == true && retries < ENROLL_ACTIVATE_RETRIES) { data.Add("authenticator_code", this.CalculateCode(false)); data.Add("authenticator_time", this.ServerTime.ToString()); response = Request(WEBAPI_BASE + "/ITwoFactorService/FinalizeAddAuthenticator/v0001", "POST", data); var finalizeresponse = JObject.Parse(response); if (response.IndexOf("status") != -1 && finalizeresponse.SelectToken("response.status").Value<int>() == INVALID_ACTIVATION_CODE) { state.Error = "Invalid activation code"; return false; } // reset our time if (response.IndexOf("server_time") != -1) { long servertime = finalizeresponse.SelectToken("response.server_time").Value<long>() * 1000; ServerTimeDiff = servertime - CurrentTime; LastServerTime = DateTime.Now.Ticks; } // check success if (finalizeresponse.SelectToken("response.success").Value<bool>() == true) { if (response.IndexOf("want_more") != -1 && finalizeresponse.SelectToken("response.want_more").Value<bool>() == true) { ServerTimeDiff += 30000L; retries++; continue; } state.RequiresActivation = false; break; } ServerTimeDiff += 30000L; retries++; } if (state.RequiresActivation == true) { state.Error = "There was a problem activating. There might be an issue with the Steam servers. Please try again later."; return false; } // mark and successful and return key state.Success = true; state.SecretKey = Authenticator.ByteArrayToString(this.SecretKey); // send confirmation email data.Clear(); data.Add("access_token", state.OAuthToken); data.Add("steamid", state.SteamId); data.Add("email_type", "2"); response = Request(WEBAPI_BASE + "/ITwoFactorService/SendEmail/v0001", "POST", data); return true; } catch (UnauthorisedRequestException ex) { throw new InvalidEnrollResponseException("You are not allowed to add an authenticator. Have you enabled 'community-generated content' in Family View?", ex); } catch (InvalidRequestException ex) { throw new InvalidEnrollResponseException("Error enrolling new authenticator", ex); } }
/// <summary> /// Load the trade confirmations /// </summary> /// <param name="state">current Steam session</param> /// <returns></returns> public string LoadTrades(SteamSession state) { // clear error state.Error = null; try { var data = new NameValueCollection(); var cookies = state.Cookies = state.Cookies ?? new CookieContainer(); string response; if (string.IsNullOrEmpty(state.OAuthToken) == true) { // get session if (cookies.Count == 0) { cookies.Add(new Cookie("mobileClientVersion", "3067969+%282.1.3%29", "/", ".steamcommunity.com")); cookies.Add(new Cookie("mobileClient", "android", "/", ".steamcommunity.com")); cookies.Add(new Cookie("steamid", "", "/", ".steamcommunity.com")); cookies.Add(new Cookie("steamLogin", "", "/", ".steamcommunity.com")); cookies.Add(new Cookie("Steam_Language", "english", "/", ".steamcommunity.com")); cookies.Add(new Cookie("dob", "", "/", ".steamcommunity.com")); NameValueCollection headers = new NameValueCollection(); headers.Add("X-Requested-With", "com.valvesoftware.android.steam.community"); response = Request("https://steamcommunity.com/login?oauth_client_id=DE45CD61&oauth_scope=read_profile%20write_profile%20read_client%20write_client", "GET", null, cookies, headers); } // get the user's RSA key data.Add("username", state.Username); response = Request(COMMUNITY_BASE + "/login/getrsakey", "POST", data, cookies); var rsaresponse = JObject.Parse(response); if (rsaresponse.SelectToken("success").Value<bool>() != true) { throw new InvalidTradesResponseException("Cannot get steam information for user: "******"publickey_exp").Value<string>()); p.Modulus = Authenticator.StringToByteArray(rsaresponse.SelectToken("publickey_mod").Value<string>()); rsa.ImportParameters(p); byte[] encryptedPassword = rsa.Encrypt(passwordBytes, false); encryptedPassword64 = Convert.ToBase64String(encryptedPassword); } // login request data = new NameValueCollection(); data.Add("password", encryptedPassword64); data.Add("username", state.Username); data.Add("twofactorcode", state.AuthCode ?? string.Empty); data.Add("emailauth", (state.EmailAuthText != null ? state.EmailAuthText : string.Empty)); data.Add("loginfriendlyname", "#login_emailauth_friendlyname_mobile"); data.Add("captchagid", (state.CaptchaId != null ? state.CaptchaId : "-1")); data.Add("captcha_text", (state.CaptchaText != null ? state.CaptchaText : "enter above characters")); data.Add("emailsteamid", (state.EmailAuthText != null ? state.SteamId ?? string.Empty : string.Empty)); data.Add("rsatimestamp", rsaresponse.SelectToken("timestamp").Value<string>()); data.Add("remember_login", "false"); data.Add("oauth_client_id", "DE45CD61"); data.Add("oauth_scope", "read_profile write_profile read_client write_client"); data.Add("donotache", new DateTime().ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds.ToString()); response = Request(COMMUNITY_BASE + "/login/dologin/", "POST", data, cookies); Dictionary<string, object> loginresponse = JsonConvert.DeserializeObject<Dictionary<string, object>>(response); if (loginresponse.ContainsKey("emailsteamid") == true) { state.SteamId = loginresponse["emailsteamid"] as string; } // require captcha if (loginresponse.ContainsKey("captcha_needed") == true && (bool)loginresponse["captcha_needed"] == true) { state.RequiresCaptcha = true; state.CaptchaId = (string)loginresponse["captcha_gid"]; state.CaptchaUrl = COMMUNITY_BASE + "/public/captcha.php?gid=" + state.CaptchaId; } else { state.RequiresCaptcha = false; state.CaptchaId = null; state.CaptchaUrl = null; state.CaptchaText = null; } // require email auth if (loginresponse.ContainsKey("emailauth_needed") == true && (bool)loginresponse["emailauth_needed"] == true) { if (loginresponse.ContainsKey("emaildomain") == true) { var emaildomain = (string)loginresponse["emaildomain"]; if (string.IsNullOrEmpty(emaildomain) == false) { state.EmailDomain = emaildomain; } } state.RequiresEmailAuth = true; } else { state.EmailDomain = null; state.RequiresEmailAuth = false; } // require email auth if (loginresponse.ContainsKey("requires_twofactor") == true && (bool)loginresponse["requires_twofactor"] == true) { state.Requires2FA = true; } else { state.Requires2FA = false; } // if we didn't login, return the result if (loginresponse.ContainsKey("login_complete") == false || (bool)loginresponse["login_complete"] == false || loginresponse.ContainsKey("oauth") == false) { if (loginresponse.ContainsKey("oauth") == false) { state.Error = "No OAuth token in response"; } if (loginresponse.ContainsKey("message") == true) { state.Error = (string)loginresponse["message"]; } return null; } // get the OAuth token string oauth = (string)loginresponse["oauth"]; var oauthjson = JObject.Parse(oauth); state.OAuthToken = oauthjson.SelectToken("oauth_token").Value<string>(); if (oauthjson.SelectToken("steamid") != null) { state.SteamId = oauthjson.SelectToken("steamid").Value<string>(); // add the steamid into the data if missing var steamdata = JObject.Parse(this.SteamData); if (steamdata.SelectToken("steamid") == null) { steamdata.Add("steamid", state.SteamId); this.SteamData = steamdata.ToString(Newtonsoft.Json.Formatting.None); } } } // get servertime //var timeresponse = Request(SYNC_URL, "POST"); //var timejson = JObject.Parse(timeresponse); //long servertime = timejson.SelectToken("response.server_time").Value<long>(); long servertime = (CurrentTime + ServerTimeDiff) / 1000L; var jids = JObject.Parse(this.SteamData).SelectToken("identity_secret"); string ids = (jids != null ? jids.Value<string>() : string.Empty); var timehash = CreateTimeHash(servertime, "conf", ids); data.Clear(); data.Add("p", this.DeviceId); data.Add("a", state.SteamId); data.Add("k", timehash); data.Add("t", servertime.ToString()); data.Add("m", "android"); data.Add("tag", "conf"); return Request(COMMUNITY_BASE + "/mobileconf/conf", "GET", data, state.Cookies); } catch (InvalidRequestException ex) { state.Error = ex.Message; throw new InvalidTradesResponseException("Error trading", ex); } }