//RSA加密,随机生成公私钥对并作为出参返回 public static string RSA_Encrypt(string str_Plain_Text, out string str_Public_Key, out string str_Private_Key) { str_Public_Key = ""; str_Private_Key = ""; UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] DataToEncrypt = ByteConverter.GetBytes(str_Plain_Text); try { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); str_Public_Key = Convert.ToBase64String(RSA.ExportCspBlob(false)); str_Private_Key = Convert.ToBase64String(RSA.ExportCspBlob(true)); //OAEP padding is only available on Microsoft Windows XP or later. byte[] bytes_Cypher_Text = RSA.Encrypt(DataToEncrypt, false); str_Public_Key = Convert.ToBase64String(RSA.ExportCspBlob(false)); str_Private_Key = Convert.ToBase64String(RSA.ExportCspBlob(true)); string str_Cypher_Text = Convert.ToBase64String(bytes_Cypher_Text); return str_Cypher_Text; } catch (CryptographicException e) { Console.WriteLine(e.Message); return null; } }
/// <summary> /// Generate keys into specified files. /// </summary> /// <param name="publicKeyFileName">Name of the file that will contain public key</param> /// <param name="privateKeyFileName">Name of the file that will contain private key</param> public void GenerateKeys(out byte[] publicKey, out byte[] privateKey) { // Variables CspParameters cspParams = null; RSACryptoServiceProvider rsaProvider = null; try { // Create a new key pair on target CSP cspParams = new CspParameters() { ProviderType = 1, // PROV_RSA_FULL Flags = CspProviderFlags.UseArchivableKey, // can be exported KeyNumber = (int)KeyNumber.Exchange // can be safely stored and exchanged }; rsaProvider = new RSACryptoServiceProvider(cspParams); rsaProvider.PersistKeyInCsp = false; // Export public key only publicKey = rsaProvider.ExportCspBlob(false); privateKey = rsaProvider.ExportCspBlob(true); } catch (Exception ex) { Debug.Fail(string.Format("Exception occured while generating keys: {0}", ex.Message)); publicKey = null; privateKey = null; } finally { if (rsaProvider != null) rsaProvider.PersistKeyInCsp = false; } }
public UpdateSigningKey() { RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); PrivateKey = provider.ExportCspBlob(true); PublicKey = provider.ExportCspBlob(false); Name = "New Key"; }
public static void GenerateKeyPairFiles(FileInfo privateKeyFile, FileInfo publicKeyFile) { using (var rsa = new RSACryptoServiceProvider()) { rsa.ExportCspBlob(true).CompressToFile(privateKeyFile); rsa.ExportCspBlob(false).CompressToFile(publicKeyFile); } }
public void GenerateKeys() { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); string privateKey = Convert.ToBase64String(rsa.ExportCspBlob(true)); Console.WriteLine("\nPrivateKey:\n{0}", privateKey); string publicKey = Convert.ToBase64String(rsa.ExportCspBlob(false)); Console.WriteLine("\nPublicKey:\n{0}", publicKey); }
//Generates keys to be used for testing purposes public static Settings GenerateKeyPair() { var cspParams = new CspParameters { ProviderType = 1 }; var rsaProvider = new RSACryptoServiceProvider(1024, cspParams); var publicKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(false)); var privateKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(true)); return new Settings { PublicKey = publicKey, PrivateKey = privateKey }; }
public Tuple<string, string> CreateKeys() { CspParameters cspParams = new CspParameters {ProviderType = 1}; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(1024, cspParams); string publicKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(false)); string privateKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(true)); return new Tuple<string, string>(privateKey, publicKey); }
public string CreateKeyPair() { CspParameters cspParams = new CspParameters { ProviderType = 1 }; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(1024, cspParams); string publicKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(false)); string privateKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(true)); return privateKey + ":" + publicKey; }
public override void ImportFromXml(IKeyStore keyStore, string xml, int keySize = 1024) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize)) { rsa.PersistKeyInCsp = false; rsa.FromXmlString(xml); keyStore.PublicKey.Key = rsa.ExportCspBlob(false); if(!rsa.PublicOnly) keyStore.PrivateKey.Key = rsa.ExportCspBlob(true); } }
public override void CreateNewKeyPair(IKeyStore keyStore, int keySize = 1024) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize)) { rsa.PersistKeyInCsp = false; keyStore.PublicKey.Key = rsa.ExportCspBlob(false); keyStore.PrivateKey.Key = rsa.ExportCspBlob(true); keyStore.KeySize = keySize; } }
public string SignN3Rsa(string data) { var cspParams = new CspParameters {KeyContainerName = "XML_DSIG_RSA_KEY"}; var key = new RSACryptoServiceProvider(cspParams); var cspBlob = key.ExportCspBlob(false); var base64Blob = Convert.ToBase64String(cspBlob); var rsaFormatter = new RSAPKCS1SignatureFormatter(key); rsaFormatter.SetHashAlgorithm("MD5"); var hash = Md5Helper.GetMd5Hash(data); var base64Hash = Convert.ToBase64String(hash); var sign = rsaFormatter.CreateSignature(hash); var base64Sign = Convert.ToBase64String(sign); var signData = new SignData { data = data, public_key = base64Blob, hash = base64Hash, sign = base64Sign }; return new SerializationHelper<SignData>().Serialize(signData); }
public byte[] ExportPrivateKey() { using (var rsa = new RSACryptoServiceProvider(RSA_KEY_SIZE)) { return rsa.ExportCspBlob(true); } }
public static ICspProxyFactory Create(int keySize) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize)) { return new DefaultFactory(rsa.ExportCspBlob(true), rsa.KeySize); } }
/// <summary> /// Generates a 1024 bit the strong-name key pair that can be written to an SNK file. /// </summary> /// <returns>A strong-name key pair array.</returns> public static byte[] GenerateStrongNameKeyPair() { using (var provider = new RSACryptoServiceProvider(1024, new CspParameters() { KeyNumber = 2 })) { return provider.ExportCspBlob(!provider.PublicOnly); } }
/// <summary> /// Create a new certificate. /// </summary> /// <param name="language">Language preferred by the certificate holder.</param> /// <param name="passphrase">Passphrase to encrypt the key with or null for no encryption.</param> public Certificate(Language language, string passphrase) { CreationDate = DateTime.Now; Id = Guid.NewGuid(); RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(); rsaProvider.KeySize = 4096; PublicKey = rsaProvider.ExportCspBlob(false); PrivateKeyStatus = PrivateKeyStatus.Unencrypted; if (passphrase == null) { this.privateKeyData = rsaProvider.ExportCspBlob(true); } else { EncryptPrivateKey(passphrase, rsaProvider); Unlock(passphrase); } this.signatures = new List<Signature>(); this.attributes = new List<CertificateAttribute>(); AddAttribute(new Int32CertificateAttribute(CertificateAttributeName.Language, (int)language)); }
public void BeforeCompile(IBeforeCompileContext context) { string keyPath = Environment.GetEnvironmentVariable("NUGET_BUILD_KEY_PATH"); string delaySignString = Environment.GetEnvironmentVariable("NUGET_BUILD_DELAY_SIGN"); if (!string.IsNullOrEmpty(keyPath)) { FileInfo keyFile = new FileInfo(keyPath); if (keyFile.Exists) { bool delaySign = delaySignString != null && StringComparer.OrdinalIgnoreCase.Equals("true", delaySignString); // Console.WriteLine("Signing assembly with: {0} Delay sign: {1}", keyFile.FullName, delaySign ? "true" : "false"); var parms = new CspParameters(); parms.KeyNumber = 2; var provider = new RSACryptoServiceProvider(parms); byte[] array = provider.ExportCspBlob(!provider.PublicOnly); var strongNameProvider = new DesktopStrongNameProvider(); var options = context.Compilation.Options.WithStrongNameProvider(strongNameProvider) .WithCryptoKeyFile(keyFile.FullName) .WithDelaySign(delaySign); // Enfore viral strong naming var specificDiagnosticOptions = new Dictionary<string, ReportDiagnostic>(options.SpecificDiagnosticOptions); specificDiagnosticOptions["CS8002"] = ReportDiagnostic.Error; options = options.WithSpecificDiagnosticOptions(specificDiagnosticOptions); context.Compilation = context.Compilation.WithOptions(options); } else { // The key was not found. Throw a compile error. var descriptor = new DiagnosticDescriptor( id: "SN1001", title: "Missing key file", messageFormat: "Key file '{0}' could not be found", category: "CA1001: \"StrongNaming\"", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); // TODO: what should this reference for the location? var textSpan = new TextSpan(); var position = new LinePosition(0, 0); var span = new LinePositionSpan(position, position); var location = Location.Create(context.ProjectContext.ProjectFilePath, textSpan, span); var diagnsotic = Diagnostic.Create(descriptor, location, keyPath); context.Diagnostics.Add(diagnsotic); } } }
public static StrongNameKeyPair GenerateStrongNameKeyPair() { using (var provider = new RSACryptoServiceProvider(1024, new CspParameters { KeyNumber = 2 })) { byte[] keyPairArray = provider.ExportCspBlob(true); return new StrongNameKeyPair(keyPairArray); } }
public override byte[] CreateNewKeyPair(int keySize = 1024) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize)) { rsa.PersistKeyInCsp = false; return rsa.ExportCspBlob(true); } }
public static KeyPair CreateNew(int length) { KeyPair ret; using (var rsa = new RSACryptoServiceProvider(length)) { try { var pub = rsa.ExportCspBlob(false); var priv = rsa.ExportCspBlob(true); ret = new KeyPair(Base32.ToBase32String(Compress(pub)), Base32.ToBase32String(Compress(priv))); } finally { rsa.PersistKeyInCsp = false; } } return ret; }
/// <summary> /// Begins the connection to the chat server /// </summary> /// <param name="hostname">Hostname to connect to</param> /// <param name="port">Destination port</param> /// <param name="user">The username</param> /// <param name="pass">The password</param> internal static void Connect(string hostname, int port, string user, string pass) { try { // Initializes a new RSA cryptography class to allow the server to securely send you the symetrical encryption key var rsa = new RSACryptoServiceProvider(1024); // Gets the Csp blob from the rsa without a private key for transportation to the server var publickey = rsa.ExportCspBlob(false); // Connects the client to the server client = new TcpClient(hostname, port); // Gets the stream for use with server communication var s = client.GetStream(); // Sends the csp to the server s.Write(new[] { (byte)publickey.Length }, 0, 1); s.Write(publickey, 0, publickey.Length); // Gets the AES key back from the server var aes = GetConnectionKey(s, rsa.ExportParameters(false)); if (aes == null) { return; } var euser = Encryption.EncryptStringToBytesAes(user + ":" + pass, aes.Key, aes.IV, e); s.Write(euser, 0, euser.Length); var r = new byte[4096]; var br = s.Read(r, 0, 4096); if (br == 0) { MessageBox.Show("The server unexpectedly closed the connection during login."); return; } var uar = Encryption.DecryptStringFromBytesAes(r, br, aes.Key, aes.IV, e); if (uar.ToLower() != "IM_OLD_GREGG__PLEASED_TO_MEET_YA".ToLower()) { MessageBox.Show(uar.ToLower() == "USER_BANNED".ToLower() ? "Unfortunately, your username is banned from the server" : "Your username or password was incorrect"); return; } Aes = aes; Connected = true; } catch (Exception exception) { MessageBox.Show("There was an error connecting to the server.\n" + exception.Message); } }
public string Replace(string input, string fragmentInput, byte[] knownHash, bool debugMode, out byte[] rsaBlob, out string token) { //Create seed, create RSA blob, replace logic var csp = new CspParameters(); csp.Flags = CspProviderFlags.UseMachineKeyStore; using (var rsa = new RSACryptoServiceProvider(2048, csp)) { var random = new Random(); var seed = random.Next(int.MinValue, int.MaxValue); rsaBlob = rsa.ExportCspBlob(true); var publicBlob = rsa.ExportCspBlob(false); var publicKey = Convert.ToBase64String(publicBlob); var fragmentLogic = SwapCode(fragmentInput, seed, string.Empty, debugMode); token = GenerateToken(fragmentLogic, knownHash); return SwapCode(input, seed, publicKey, debugMode); } }
private static void AsymmetricEncryption() { byte[] signature; byte[] publicAndPrivateKey; byte[] publicKeyOnly; var hashImplementation = SHA1.Create(); // create a signature, create our public and private keys - we could save these out as XML, etc. using (var rsaProvider = new RSACryptoServiceProvider()) { signature = rsaProvider.SignData(dataToProtectAsArray, hashImplementation); publicAndPrivateKey = rsaProvider.ExportCspBlob(true); publicKeyOnly = rsaProvider.ExportCspBlob(false); } // create a new RSA using (var rsaProvider = new RSACryptoServiceProvider()) { // import our public key rsaProvider.ImportCspBlob(publicKeyOnly); // has it been tampered with? if (!rsaProvider.VerifyData(dataToProtectAsArray, hashImplementation, signature)) { Console.WriteLine("Data has been tampered with"); } // now let's tamper with our data dataToProtectAsArray[5] = 255; if (!rsaProvider.VerifyData(dataToProtectAsArray, hashImplementation, signature)) { Console.WriteLine("Data has been tampered with"); } } hashImplementation.Dispose(); }
public void Initialize() { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(4096)) testCspBlob = rsa.ExportCspBlob(true); // Prepare random memory streams Random random = new Random(); byte[] bufferFirst = new byte[sampleStreamSize]; random.NextBytes(bufferFirst); streamSample = new MemoryStream(bufferFirst); }
/// <summary> /// Generates keybytes for the private key /// </summary> public void SetKeyBytes() { //Generate a new private key using(var r = new RSACryptoServiceProvider(2048, new CspParameters() { Flags = CspProviderFlags.CreateEphemeralKey | CspProviderFlags.NoPrompt})){ try { var privateKeyBytes = r.ExportCspBlob(true); this.KeyBytes = SymmetricEncryption.EncryptForDatabase(privateKeyBytes); } finally{ r.PersistKeyInCsp = false; } } }
public static void Main(String []args) { int keysize = 1024; if(args.Length == 1) { try { keysize = Int32.Parse(args[0]); } catch { Console.WriteLine("Default key size is 1024, specify 512 or 2048 as an input parameter."); return; } } RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keysize); // Create public key file byte[] rsa_public = rsa.ExportCspBlob(false); FileStream public_file = File.Open("rsa_public", FileMode.Create); public_file.Write(rsa_public, 0, rsa_public.Length); public_file.Close(); // Create private key file byte[] rsa_private = rsa.ExportCspBlob(true); FileStream private_file = File.Open("rsa_private", FileMode.Create); private_file.Write(rsa_private, 0, rsa_private.Length); private_file.Close(); }
static byte[] CreateKeyPair( string containerName, int keySize ) { if ( ( keySize % 8 ) != 0 ) { throw new CryptographicException( "Invalid key size. Valid size is 384 to 16384 mod 8. Default 1024." ); } CspParameters parms = new CspParameters(); parms.KeyContainerName = containerName; parms.KeyNumber = 2; RSACryptoServiceProvider provider = new RSACryptoServiceProvider( keySize, parms ); byte[] array = provider.ExportCspBlob( !provider.PublicOnly ); return array; }
public override void ImportFromBytes(IKeyStore keyStore, byte[] bytes, int keySize = 1024) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize)) { rsa.PersistKeyInCsp = false; rsa.ImportCspBlob(bytes); keyStore.PublicKey.Key = rsa.ExportCspBlob(false); if (!rsa.PublicOnly) keyStore.PrivateKey.Key = bytes; } }
public void SecureStartup() { if(SEKey != null) { return; } SEKey = new RSACryptoServiceProvider(); byte[] blob = SEKey.ExportCspBlob(false); RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider(); rsa_pub.ImportCspBlob(blob); CertificateMaker cm = new CertificateMaker("United States", "UFL", "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub, "brunet:node:abcdefghijklmnopqrs"); Certificate cert = cm.Sign(cm, SEKey); CACert = cert; }
/// <summary> /// 通过一个容器Key来存取公钥私钥对 /// <remarks>没有时会自动创建</remarks> /// </summary> /// <param name="keyContainerName">通过容器Key获取公私钥对</param> public RSAEncryptor(string keyContainerName) { //RSACryptoServiceProvider.UseMachineKeyStore = true; var cp = new CspParameters { KeyContainerName = keyContainerName }; _provider = new RSACryptoServiceProvider(DWKEYSIZE, cp); //PublicKey = _provider.ExportCspBlob(false); PrivateKey = _provider.ExportCspBlob(true); //取得RSA容易里的各种参数 var pm = _provider.ExportParameters(true); KeyModulus = pm.Modulus; KeyPublicExponent = pm.Exponent; KeyPrivateD = pm.D; PublicKey = GetPublicKey(pm.Modulus, pm.Exponent); }
public HttpResponseMessage GenerateOAuthCertificate() { string certificate; using (var rsa = new RSACryptoServiceProvider()) certificate = Convert.ToBase64String(rsa.ExportCspBlob(true)); var message = GetEmptyMessage(); message.Content = new StringContent(certificate, Encoding.UTF8); message.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "oauth-certificate.txt" }; message.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return message; }
private async Task CreateKeyForUser() { var csp = new System.Security.Cryptography.RSACryptoServiceProvider(1024); var rsakeyparam = csp.ExportParameters(true); var privkey = RSAConverter.ExportPrivateKey(csp); //var publicKey = RSAConverter.ExportPublicKey(csp); var publickeybytes = csp.ExportCspBlob(false); var publicKey = Convert.ToBase64String(publickeybytes); SelectedUser.RsaPublicKey = publicKey; var rsakeydata = System.Text.Encoding.UTF8.GetBytes(privkey); await JSRuntime.SaveFile(rsakeydata, $"{SelectedUser.Username}.pem"); SaveUser(); }