public static string ToPEM (RSAKeyPair RSAKeyPair) { var Provider = RSAKeyPair.Provider; Assert.Null(Provider, NoProviderSpecified.Throw); var RSAParameters = Provider.ExportParameters(true); Assert.Null(RSAParameters, PrivateKeyNotAvailable.Throw); var NewProvider = new RSACryptoServiceProvider(); NewProvider.ImportParameters(RSAParameters); RSAParameters.Dump(); var RSAPrivateKey = new RSAPrivateKey(RSAParameters); var Builder = new StringBuilder(); Builder.Append("-----BEGIN RSA PRIVATE KEY-----"); var KeyDER = RSAPrivateKey.DER(); Builder.AppendBase64(KeyDER); Builder.Append("\n-----END RSA PRIVATE KEY-----\n"); return Builder.ToString(); }
public User(string name) { _rsaKeyPair = RSAKeyPairGenerator.GenerateRSAKeyPair(); _name = name; _logger.Info("Created user '{0}'. RSA public key: {1}", name, _rsaKeyPair.Public.ToString()); }
public static void Init(ClientConfig config) { if (appSettings == null) { appSettings = new Dictionary <string, string>(); } client = ClientFactory.GetConfigurationServiceClient(config.ConfigurationServer, config.ConfigurationServerPort); if (GetServerKey() == null) { throw new InvalidOperationException("Unable to retrieve server key"); } //masterEncryptedAppHash = serverKey.EncryptWithPublicKey(config.ApplicationHash); if (clientKey == null) { string masterEncryptedAppHash = serverKey.EncryptWithPublicKey(config.ApplicationHash); RSAKeyPair tempKey = new RSAKeyPair(); clientKey = GetClientKey(masterEncryptedAppHash, tempKey); } // if the clientKey is still null // we were unable to get it from the service if (clientKey == null) { throw new InvalidOperationException("Unable to retrieve client key. Make sure that you are using the correct application hash"); } }
public void Test_RSA_Parameters_Is_Set() { //arrange RSAParameters parameters = new RSAParameters(); RSAKeyPair keys = new RSAKeyPair(parameters); Assert.Equal(parameters, keys.RSAParameters); }
public static void AbandonSettings() { client = null; config = null; appSettings = null; lastResponse = null; serverKey = null; clientKey = null; }
public void RestoreKeyPair() { using (RSAKeyPair original = new RSAKeyPair()) using (RSAKeyPair restored = new RSAKeyPair(original.PrivateKey)) { CollectionAssert.AreEqual(original.PrivateKey, restored.PrivateKey); CollectionAssert.AreEqual(original.PublicKey, restored.PublicKey); } }
/// <summary> /// Encrypt the specified text using the given encoding to get the bytes, and using the given /// key pair. /// </summary> /// <param name="text">Text to encrypt.</param> /// <param name="encoding">Encoding of the string.</param> /// <param name="keyPair">Key pair to use for the encryption.</param> public byte[] Encrypt(string text, Encoding encoding, RSAKeyPair keyPair) { if (keyPair == null) { throw new ArgumentNullException(nameof(keyPair)); } return(Encrypt(text, encoding, keyPair.PublicKey)); }
/// <summary> /// Decrypt the specified bytes using the given key pair. /// </summary> /// <param name="bytes">Bytes to decrypt.</param> /// <param name="keyPair">Key pair to use for the decryption.</param> public byte[] Decrypt(byte[] bytes, RSAKeyPair keyPair) { if (keyPair == null) { throw new ArgumentNullException(nameof(keyPair)); } return(Decrypt(bytes, keyPair.PrivateKey)); }
/// <summary> /// Decrypt the specified bytes using the key pair into a string, encoded using the /// given encoding. /// </summary> /// <param name="bytes">Bytes to decrypt.</param> /// <param name="encoding">Encoding of the string.</param> /// <param name="keyPair">Key pair to use for the decryption.</param> public string Decrypt(byte[] bytes, Encoding encoding, RSAKeyPair keyPair) { if (keyPair == null) { throw new ArgumentNullException(nameof(keyPair)); } return(Decrypt(bytes, encoding, keyPair.PrivateKey)); }
public void Encrypt() { using (RSAKeyPair kp = new RSAKeyPair()) { string data = "Hello my name is Maitland"; byte[] dataEncrypted = kp.Encrypt(data, Encoding.UTF8); string dataConvertedToUTF8 = Encoding.UTF8.GetString(dataEncrypted); Assert.AreNotEqual(data, dataConvertedToUTF8); } }
public void ClientKeyPassword( [Argument("site", "s", Description = "The root http address of the website copy.")] string site, [Argument("password", "p", Description = "The password to be used.")] string passwordText) { string keyfile = Path.Combine(StoragePath(site), "client-publishing.key"); using (RSAKeyPair clientKey = new RSAKeyPair(keyfile, true)) clientKey.SetClientPassword(Encoding.UTF8.GetBytes(passwordText)); }
public void DecodeRSA() { for (int i = 0; i < 100; i++) { RSAKeyPair kp = new RSAKeyPair(512); string mneomnic = Mnemonic.Encode(kp.PrivateKey); byte[] privateKey1 = Mnemonic.Decode(mneomnic); CollectionAssert.AreEqual(kp.PrivateKey, privateKey1); } }
public void NewKeyPair() { using (RSAKeyPair kp = new RSAKeyPair()) using (RSAKeyPair kp2 = new RSAKeyPair()) { Assert.AreNotEqual(new byte[0], kp.PrivateKey); Assert.AreNotEqual(new byte[0], kp.PublicKey); CollectionAssert.AreNotEqual(kp2.PrivateKey, kp.PrivateKey); CollectionAssert.AreNotEqual(kp2.PublicKey, kp.PublicKey); } }
public static string EncryptString(RSAKeyPair keys, string str) { var encryptedStr = ""; try { using (var rsa = PEMLoader.GetRSAFromPEM(keys.PublicKey)) { var encryptedBytes = rsa.Encrypt(str.ToBytes(), RSAEncryptionPadding.Pkcs1); encryptedStr = encryptedBytes.ToBase64(); } } catch { } return(encryptedStr); }
public static RSAKeyPair GenerateKeys(int keySize = 2048) { RSAKeyPair keys = null; using (var rsa = RSA.Create()) { rsa.KeySize = keySize; var privateKey = PEMExporter.Export(rsa, true); var publicKey = PEMExporter.Export(rsa, false); keys = new RSAKeyPair(privateKey, publicKey); } return(keys); }
public RSAKeyPair GenerateKeyPair(int size) { var rsaKeyPair = new RSAKeyPair(); using (var RSA = new RSACryptoServiceProvider(size)) { rsaKeyPair.PublicKey = RSA.ToXmlString(false); rsaKeyPair.PrivateKey = RSA.ToXmlString(true); } return(rsaKeyPair); }
public void EncodeRSA() { RSAKeyPair kp = new RSAKeyPair(); string mneomnic = Mnemonic.Encode(kp.PrivateKey); Assert.IsTrue(mneomnic.Length > 0); RSAKeyPair kp2 = new RSAKeyPair(); string mnemonic2 = Mnemonic.Encode(kp2.PrivateKey); Assert.AreNotEqual(mneomnic, mnemonic2); }
public static string DecryptString(RSAKeyPair keys, string encryptedStr) { var decryptedStr = ""; try { using (var rsa = PEMLoader.GetRSAFromPEM(keys.PrivateKey)) { var encryptedBytes = encryptedStr.FromBase64(); var decryptedBytes = rsa.Decrypt(encryptedBytes, RSAEncryptionPadding.Pkcs1); decryptedStr = decryptedBytes.ToEncoding(); } } catch { } return(decryptedStr); }
public void TestKeyLoadingAndEncrypting() { var privateKey = @" -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEA3BGLEjYSMZGI9EELAbq9/teH/EPA5aa+XTfOoe6PBRDmPIvl vCuy+u37DLDqry1zf5spaDSLYVMhiiLDcisLAb0n1TDOHTdSPMTWq7k9ACe0lPOT d0uPaFwWRBtKXdj/ZmzfEqkwMyUFGTQXeol6c4R3ddnp6fnkZKm1neI+cQ2emvrU FFbH1NsrC8Kb0F1ysBvePGIvpsf2xc42+pl6tkyhGdnu41Tg78qeYBJWJuxSgcqV /uq9RB5vwfAKefpQK25eyUXX1cFGOOOJk4ZKepVkKXYwrkjlg6YUczTeOd4ai0Z5 x28d8o3pDv44gd7g1nHmeHiMDePQSzW8kHWbtwIDAQABAoIBAGAS3Jb3uhufwJ15 o9d+ciHGcFyGK7lWgTbq/S+emRuKFCmMnZ/3p+x6ZqZUui/99LVZxMr0XYEArNzE bnTyK5z3umMNKn6Av0s+V8WiWeoua1y3tcJX32SdBy92hpHQATfzAbQA3sUFPWOS ZUmeqTGzO//cQY1fBgGYQWyK792kV+ZcgrfPprohuX4vMkZgiq9X8bSQZeyllnFl Ve5a3lBfehENN5T9oAO5Z79zskKczsuC8ENF8sue8y2hGVWcP1wxynl16N7a/Q7c 7ZBeeaEyzgbwaBD+uOqgRJ95+9aVSp0vv95lO4hevNvHzNjBcjnxZA1yul54qzpF 9s61RGkCgYEA+7zIa1HQv/B3YD1uDhuaUj3kKVr0gvFmUZ38OBWJWuvAO4Fp/Plh PNBpVdzBF+gxld0xjieEPYD86MYWNUZbXb/EL9tkWs5MRCuNPtHabXXc1KD6lO6h M/6goD5zIisq9DksfylpUNlVDJttkVDh5veYCOXcET/Z8iIHbJ8ZM4MCgYEA38t7 2bh0RiI2t6+NpOSmxW6fvW4Q5HzNFlM1j83WN933c3ftly7rA/vvTe1zLM/1G4Cs 7qAKJnN5AoSqkmbCnMUmANZ9A0Njr6w83jgqBk49UsEbvmGZhW5/n1Fkg/7ezaVI vRnmwOykiNu1lUzUnRJGv74pRZ5UXkg8gKEy3L0CgYAPRrh+0rsxOp1z6KZqEsC9 puXWoJ9f5thHsaehm6T3MIE82zCcWmHNN/R8cmYBVmTT7FVahAlhVheC5KpqVzeq K73zDYQ8gnJcXKw4mLGBnPpmqNIsAYMkzZnfv4prE2WK5oFNwiyS7G1d03zFqbvb sUC3oYNGRLKsH+aFb+4ukwKBgCj/eBLsrbBjeC6yZHp+wOaOW4kybrnM+y1J1Rgh F0toyHpI0CfQGpHCR5a5F05wUnDVY9jbTMC6isKhVzY2yRQ7MbkZkhFU+SAnp4b2 NwysrKNKaTC5ZIyDL7IaERX1TQ/TZb3uzs0tDP9dcKiHSLP1syxRQ/JTDRWwmhTe cxjpAoGBAITD5UmUoKA9Ve/yGhtd7fAlOoXs+zNuRhzEUnaSAORh/mV57hZQhdDA HsCuVMNxscvownXuSm73Jl3cTO4SpgyDwo9KUGDBvKf+21WaHQ0d+c06TGqi36Yt 1BNpV0hZC1+jws+de01q6iBK9RZ2iQVRMPL+xFpqNHj8PAtPl8A6 -----END RSA PRIVATE KEY----- "; var publicKey = @" -----BEGIN PUBLIC KEY----- MIIBKwIBAAKCAQEA3BGLEjYSMZGI9EELAbq9/teH/EPA5aa+XTfOoe6PBRDmPIvl vCuy+u37DLDqry1zf5spaDSLYVMhiiLDcisLAb0n1TDOHTdSPMTWq7k9ACe0lPOT d0uPaFwWRBtKXdj/ZmzfEqkwMyUFGTQXeol6c4R3ddnp6fnkZKm1neI+cQ2emvrU FFbH1NsrC8Kb0F1ysBvePGIvpsf2xc42+pl6tkyhGdnu41Tg78qeYBJWJuxSgcqV /uq9RB5vwfAKefpQK25eyUXX1cFGOOOJk4ZKepVkKXYwrkjlg6YUczTeOd4ai0Z5 x28d8o3pDv44gd7g1nHmeHiMDePQSzW8kHWbtwIDAQABAgMBAAECAwEAAQIDAQAB AgMBAAECAwEAAQIDAQAB -----END PUBLIC KEY----- "; var keys = new RSAKeyPair(privateKey, publicKey); var text = "test of encryption"; var encryptedText = RSACipher.EncryptString(keys, text); var decryptedText = RSACipher.DecryptString(keys, encryptedText); Assert.IsFalse(string.IsNullOrWhiteSpace(encryptedText)); Assert.IsFalse(string.IsNullOrWhiteSpace(decryptedText)); Assert.AreEqual(text, decryptedText); }
static void Main(string[] args) { Console.WriteLine("Starting server debugger"); if (args.Length < 1) { Console.WriteLine("Minecraft Login Debugger: -debug|-d MinecraftServerDebugger.exe [Port]"); Console.WriteLine("Asynchronous key test kit: -encryptionTestKit|-etk [filename]"); return; } Console.WriteLine("Generating Rsa Key Pair..."); _keyPair = ProtocolSecurity.GenerateRSAKeyPair(); Console.WriteLine("Keypair generated"); switch (args[0]) { case "-debug": case "-d": if (args.Length < 2) Console.WriteLine("Port missing"); else WaitForClient(int.Parse(args[1])); break; case "-encryptionTestKit": case "-etk": string path = args.Length < 2 ? "keys.txt" : args[1]; using (TextWriter stream = new StreamWriter(File.Create(path))) { stream.WriteLine("Private RSA Key: " + FormatArray(_keyPair.GetPrivate())); stream.WriteLine("Public RSA Key: " + FormatArray(_keyPair.GetPublic())); stream.WriteLine("------------------------------------------------------"); byte[] randomBuffer = new byte[4]; new Random().NextBytes(randomBuffer); stream.WriteLine("Demo verification token: " + FormatArray(randomBuffer)); stream.WriteLine("Public key encrypted verification token: " + FormatArray(ProtocolSecurity.RSAEncrypt(randomBuffer, _keyPair.GetPublic(), false))); using (ConsoleHelpers.ChangeForegroundColor(ConsoleColor.Green)) Console.WriteLine("Finished"); } break; default: Console.WriteLine("Unknown parameter"); break; } Console.WriteLine("Press Any Key to exit"); Console.ReadKey(true); }
public ContentState(ContentStorage content) { //_executionLock = new SimpleReadWriteLocking(); _executionLock = IgnoreLocking.Instance; _rsaKeyPair = ReadKeyFile(); _content = content ?? ReadCurrent(); _channel = new IpcEventChannel(Path.Combine(Settings.RegistryPath, "IISChannel"), BitConverter.ToString(Hash.MD5(Encoding.UTF8.GetBytes(StoragePath)).ToArray())); _channel.OnError += (o, e) => Log.Error(e.GetException()); _channel[Events.ContentUpdate].OnEvent += OnContentUpdated; _channel[Events.CompletionAck].OnEvent += (o, e) => { }; _channel.StartListening(); }
private void EntryPoint() { _mouseMoveCount = 0; KeyPair kp; if (_algorithm == PublicKeyAlgorithm.DSA) { kp = DSAKeyPair.GenerateNew(_bits, _rnd); } else { kp = RSAKeyPair.GenerateNew(_bits, _rnd); } _parent.SetResultKey(new SSH2UserAuthKey(kp)); }
public SitePublisher(string storagePath, string site) { _storagePath = storagePath; _siteUri = new Uri(site, UriKind.Absolute); _content = new ContentStorage(storagePath, true); _keyfile = Path.Combine(storagePath, "client-publishing.key"); if (File.Exists(_keyfile)) { _rsaKeyPair = new RSAKeyPair(_keyfile, true); // we publish on the hash of both client and server keys so that if the handler is invoked there is already // a high-probability that the keyset will match. _publishUri = "/api/publish/" + Safe64Encoding.EncodeBytes(_rsaKeyPair.KeyPairHash.ToArray()) + "/"; } }
/// <summary> /// Creates a RSA key pair /// </summary> /// <returns></returns> public static RSAKeyPair GenerateRSAKeyPair() { var KeyPair = new RSAKeyPair(); var cspParams = new CspParameters { ProviderType = 1 }; using (var rsaProvider = new RSACryptoServiceProvider(2048, cspParams)) { KeyPair.Public = Convert.ToBase64String(rsaProvider.ExportCspBlob(false)); KeyPair.Private = Convert.ToBase64String(rsaProvider.ExportCspBlob(true)); } return(KeyPair); }
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 Decrypt() { using (RSAKeyPair kp = new RSAKeyPair()) using (RSAKeyPair kp2 = new RSAKeyPair()) { string data = "Hello I am Maitland I make code"; byte[] dataEncrypted = kp.Encrypt(data, Encoding.UTF8); string dataDecrypted = kp.Decrypt(dataEncrypted, Encoding.UTF8); Assert.AreEqual(data, dataDecrypted); Assert.ThrowsException <CryptographicException>(() => { kp2.Decrypt(dataEncrypted, Encoding.UTF8); }); } }
private static RSAKeyPair GetServerKey() { if (serverKey == null) { serverKey = new RSAKeyPair(); serverKey.PrivateKeyXml = string.Empty; ConfigurationResponse response = client.GetServerKey(); if (response.Result == ConfigurationResult.Error) { lastResponse = response; return(null); } serverKey.PublicKeyXml = response.ServerKey; } return(serverKey); }
public async Task <ActionResult <MainResponse> > CreateTestWord(CreateNewSessionRequest request) { User user = HttpContext.GetUser(); if (user == null) { return(StatusCode(401)); } KeySession keySession = _context.KeySessions.FirstOrDefault(p => p.VerificationData == request.IdentificationWord); if (keySession == null) { RSAKeyPair keyPair = new RSAKeyPair() { EncryptedPrivateKey = request.EncryptedPrivateKey, LastKeyPair = null, LastPublicKeySign = null, PublicKey = request.PublicKey }; _context.RSAKeyPairs.Add(keyPair); keySession = new KeySession() { CreationDate = DateTime.Now, VerificationData = request.IdentificationWord, RSAKeyPair = keyPair }; user.KeySession = keySession; user.UserState = Enums.UserStates.Online; user.AvailableKeys--; _context.Users.Update(user); await _context.KeySessions.AddAsync(keySession); await _context.SaveChangesAsync(); } UserSecretKeyResponse secretKeyResponse = new UserSecretKeyResponse() { UnknownKey = false }; return(MainResponse.GetSuccess(secretKeyResponse)); }
//Tutorial: Generating a new RSA key for user authentication private static void GenerateRSAKey() { //RSA KEY GENERATION TEST byte[] testdata = Encoding.ASCII.GetBytes("CHRISTIAN VIERI"); RSAKeyPair kp = RSAKeyPair.GenerateNew(2048, new Random()); //sign and verify test byte[] sig = kp.Sign(testdata); kp.Verify(sig, testdata); //export / import test SSH2UserAuthKey key = new SSH2UserAuthKey(kp); key.WritePublicPartInOpenSSHStyle(new FileStream("newrsakey.pub", FileMode.Create)); key.WritePrivatePartInSECSHStyleFile(new FileStream("newrsakey.bin", FileMode.Create), "comment", "passphrase"); //read test SSH2UserAuthKey newpk = SSH2UserAuthKey.FromSECSHStyleFile("newrsakey.bin", "passphrase"); }
public async Task <ActionResult <MainResponse> > UserRegister(UserRegisterRequest registerRequest) { if (_context.Users.Any(p => p.Login == registerRequest.Login)) { return(MainResponse.GetError(Enums.RequestError.LoginExists)); } RSAKeyPair keyPair = new RSAKeyPair() { EncryptedPrivateKey = registerRequest.EncryptedPrivateKey, LastKeyPair = null, LastPublicKeySign = null, PublicKey = registerRequest.PublicKey }; _context.RSAKeyPairs.Add(keyPair); User user = new User() { Id = Hash.Sha1(Hash.Sha256(registerRequest.Login + RandomUtilities.GetCryptoRandomString(53))), RegistrationDate = DateTime.Now, Email = registerRequest.Email, FirstName = registerRequest.FirstName, LastName = registerRequest.LastName, Login = registerRequest.Login, HashKeySeed = registerRequest.HashKeySeed, UserSalt = RandomUtilities.GetCryptoRandomString(16), IdentificationWord = registerRequest.IdentificationWord, UserIv = registerRequest.Iv, AvailableKeys = 1000, RSAKeyPair = keyPair }; user.Password = GetPassword(registerRequest.Password, user.UserSalt); _context.Users.Add(user); await _context.SaveChangesAsync().ConfigureAwait(false); return(MainResponse.GetSuccess()); }
public static RSAKeyPair GenKeys(RSAKeySize keySize) { try { using (var provider = new RSACryptoServiceProvider((int)keySize)) { RSAKeyPair keys = new RSAKeyPair(); var publicKey = provider.ToXmlString(false); var privateKey = provider.ToXmlString(true); var publicKeyWithSize = IncludeKeyInEncryptionString(publicKey); var privateKeyWithSize = IncludeKeyInEncryptionString(privateKey); keys.PublicKey = publicKeyWithSize; keys.PrivateKey = privateKeyWithSize; return(keys); } } catch (CryptographicException) { return(null); } }
/// <summary> /// Read PuTTY SSH2 private key parameters. /// </summary> /// <param name="passphrase">passphrase for decrypt the key file</param> /// <param name="keyPair">key pair</param> /// <param name="comment">comment or empty if it didn't exist</param> public void Load(string passphrase, out KeyPair keyPair, out string comment) { if (keyFile == null) { throw new SSHException("A key file is not loaded yet"); } int version; string keyTypeName; KeyType keyType; string encryptionName; CipherAlgorithm?encryption; byte[] publicBlob; byte[] privateBlob; string privateMac; string privateHash; using (StreamReader sreader = GetStreamReader()) { //*** Read header and key type ReadHeaderLine(sreader, out version, out keyTypeName); if (keyTypeName == "ssh-rsa") { keyType = KeyType.RSA; } else if (keyTypeName == "ssh-dss") { keyType = KeyType.DSA; } else { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected key type)"); } //*** Read encryption ReadItemLine(sreader, "Encryption", out encryptionName); if (encryptionName == "aes256-cbc") { encryption = CipherAlgorithm.AES256; } else if (encryptionName == "none") { encryption = null; } else { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected encryption)"); } //*** Read comment ReadItemLine(sreader, "Comment", out comment); //*** Read public lines string publicLinesStr; ReadItemLine(sreader, "Public-Lines", out publicLinesStr); int publicLines; if (!Int32.TryParse(publicLinesStr, out publicLines) || publicLines < 0) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid public lines)"); } ReadBlob(sreader, publicLines, out publicBlob); //*** Read private lines string privateLinesStr; ReadItemLine(sreader, "Private-Lines", out privateLinesStr); int privateLines; if (!Int32.TryParse(privateLinesStr, out privateLines) || privateLines < 0) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid private lines)"); } ReadBlob(sreader, privateLines, out privateBlob); //*** Read private MAC ReadPrivateMACLine(sreader, version, out privateMac, out privateHash); } if (encryption.HasValue) { byte[] key = PuTTYPassphraseToKey(passphrase); byte[] iv = new byte[16]; Cipher cipher = CipherFactory.CreateCipher(SSHProtocol.SSH2, encryption.Value, key, iv); if (privateBlob.Length % cipher.BlockSize != 0) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid key data size)"); } cipher.Decrypt(privateBlob, 0, privateBlob.Length, privateBlob, 0); } bool verified = Verify(version, privateMac, privateHash, passphrase, keyTypeName, encryptionName, comment, publicBlob, privateBlob); if (!verified) { if (encryption.HasValue) { throw new SSHException(Strings.GetString("WrongPassphrase")); } else { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (HMAC verification failed)"); } } if (keyType == KeyType.RSA) { SSH2DataReader reader = new SSH2DataReader(publicBlob); byte[] magic = reader.ReadString(); if (!ByteArrayUtil.AreEqual(magic, Encoding.ASCII.GetBytes("ssh-rsa"))) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (missing magic)"); } BigInteger e = reader.ReadMPInt(); BigInteger n = reader.ReadMPInt(); reader = new SSH2DataReader(privateBlob); BigInteger d = reader.ReadMPInt(); BigInteger p = reader.ReadMPInt(); BigInteger q = reader.ReadMPInt(); BigInteger iqmp = reader.ReadMPInt(); BigInteger u = p.modInverse(q); keyPair = new RSAKeyPair(e, d, n, u, p, q); } else if (keyType == KeyType.DSA) { SSH2DataReader reader = new SSH2DataReader(publicBlob); byte[] magic = reader.ReadString(); if (!ByteArrayUtil.AreEqual(magic, Encoding.ASCII.GetBytes("ssh-dss"))) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (missing magic)"); } BigInteger p = reader.ReadMPInt(); BigInteger q = reader.ReadMPInt(); BigInteger g = reader.ReadMPInt(); BigInteger y = reader.ReadMPInt(); reader = new SSH2DataReader(privateBlob); BigInteger x = reader.ReadMPInt(); keyPair = new DSAKeyPair(p, g, q, y, x); } else { throw new SSHException("Unknown file type. This should not happen."); } }
public static void Init(ClientConfig config) { if (appSettings == null) appSettings = new Dictionary<string, string>(); client = ClientFactory.GetConfigurationServiceClient(config.ConfigurationServer, config.ConfigurationServerPort); if (GetServerKey() == null) throw new InvalidOperationException("Unable to retrieve server key"); //masterEncryptedAppHash = serverKey.EncryptWithPublicKey(config.ApplicationHash); if (clientKey == null) { string masterEncryptedAppHash = serverKey.EncryptWithPublicKey(config.ApplicationHash); RSAKeyPair tempKey = new RSAKeyPair(); clientKey = GetClientKey(masterEncryptedAppHash, tempKey); } // if the clientKey is still null // we were unable to get it from the service if (clientKey == null) throw new InvalidOperationException("Unable to retrieve client key. Make sure that you are using the correct application hash"); }
private static RijndaelKeyVectorPair GetClientKey(string masterEncryptedAppHash, RSAKeyPair tempKey) { if (clientKey == null) { ConfigurationResponse clientKeyResponse = client.GetClientKey(masterEncryptedAppHash, tempKey.PublicKeyXml); clientKey = clientKeyResponse.ClientKey; if (clientKey != null) { clientKey.Base64InitializationVector = tempKey.DecryptWithPrivateKey(clientKey.Base64InitializationVector); clientKey.Base64Key = tempKey.DecryptWithPrivateKey(clientKey.Base64Key); } } return clientKey; }
private static RSAKeyPair GetServerKey() { if (serverKey == null) { serverKey = new RSAKeyPair(); serverKey.PrivateKeyXml = string.Empty; ConfigurationResponse response = client.GetServerKey(); if (response.Result == ConfigurationResult.Error) { lastResponse = response; return null; } serverKey.PublicKeyXml = response.ServerKey; } return serverKey; }