private async Task ProcessNeedMongoMarkingsStateAsync(CryptContext context, string databaseName, CancellationToken cancellationToken) { var database = _mongocryptdClient.GetDatabase(databaseName); var commandBytes = context.GetOperation().ToArray(); var commandDocument = new RawBsonDocument(commandBytes); var command = new BsonDocumentCommand <BsonDocument>(commandDocument); BsonDocument response = null; for (var attempt = 1; response == null; attempt++) { try { response = await database.RunCommandAsync(command, cancellationToken : cancellationToken).ConfigureAwait(false); } catch (TimeoutException) when(attempt == 1) { _mongocryptdFactory.SpawnMongocryptdProcessIfRequired(); await WaitForMongocryptdReadyAsync().ConfigureAwait(false); } } RestoreDbNodeInResponse(commandDocument, response); FeedResult(context, response); }
public static void InstallServantCertificate(string name) { var store = OpenStore(OpenFlags.ReadWrite); X509Certificate2 cert; using (var ctx = new CryptContext()) { ctx.Open(); cert = ctx.CreateSelfSignedCertificate( new SelfSignedCertProperties { IsPrivateKeyExportable = true, KeyBitLength = 4096, Name = new X500DistinguishedName(string.Format("CN=\"{0}\"; C=\"{0}\"; O=\"{0}\"; OU=\"{0}\";", name)), ValidFrom = DateTime.Today, ValidTo = DateTime.Today.AddYears(10), }); //ensure pfx in cert. byte[] pfx = cert.Export(X509ContentType.Pfx); byte[] pkbytes = cert.Export(X509ContentType.Cert); System.IO.File.WriteAllBytes(string.Format(".\\{0}.cer", name), pkbytes); cert = new X509Certificate2(pfx, (string)null, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet); } cert.FriendlyName = name; store.Add(cert); store.Close(); System.Threading.Thread.Sleep(1000); // Wait for certificate to be installed }
public static void InstallServantCertificate() { var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); //CRASH! // Servant certifikatet kan ikke bindes til Azure serveren, ved mindre det bliver eksporteret og importeret først. Den siger det der med local user blablal.. X509Certificate2 cert; using (var ctx = new CryptContext()) { ctx.Open(); cert = ctx.CreateSelfSignedCertificate( new SelfSignedCertProperties { IsPrivateKeyExportable = true, KeyBitLength = 4096, Name = new X500DistinguishedName("CN=\"Servant\"; C=\"Denmark\"; O=\"Denmark\"; OU=\"Denmark\";"), ValidFrom = DateTime.Today, ValidTo = DateTime.Today.AddYears(10) }); } cert.FriendlyName = "Servant"; store.Add(cert); store.Close(); System.Threading.Thread.Sleep(1000); // Wait for certificate to be installed }
protected void testDes() { //string testStr = "asdfasdf5"; //byte[] inBytes = System.Text.Encoding.UTF8.GetBytes(testStr); //byte[] key = { 0x65, 0xC1, 0x78, 0xB2, 0x84, 0xD1, 0x97, 0xCC }; byte[] key = { 26, 32, 127, 193, 251, 239, 174, 97 }; //byte[] inBytes = { 0x3f, 0x79, 0xd5, 0xe2, 0x4a, 0x8c, 0xb6, 0xc1, 0x3f, 0x79, 0xd5, 0xe2, 0x4a, 0x8c, 0xb6, 0xc1 }; byte[] inBytes = { 0x0c, 0x00, 0x00, 0x00, 0x03, 0x35, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }; byte[] outBytes = new byte[16]; uint inSize = (uint)inBytes.Length; DES_key_schedule des5Key = new DES_key_schedule(); // RC5 key Dec.DES_set_key_unchecked(key, des5Key); CryptContext cryptContext = new CryptContext(); cryptContext.m_cryptAlgorithm = CryptAlgorithm.DES; cryptContext.setCryptKey(key); //Crypt.encryptData(inBytes, 0, 16, ref outBytes, des5Key, CryptAlgorithm.DES); //Crypt.decryptData(outBytes, 0, 16, ref inBytes, des5Key, CryptAlgorithm.DES); //testStr = System.Text.Encoding.UTF8.GetString(inBytes); Crypt.decryptData(inBytes, 0, 16, ref outBytes, cryptContext); }
public static CertificateStore CreateCertificate() { using (var ctx = new CryptContext()) { ctx.Open(); var cert = ctx.CreateSelfSignedCertificate( new SelfSignedCertProperties { IsPrivateKeyExportable = true, KeyBitLength = 4096, Name = new X500DistinguishedName(CERT_DISTINGUISHED_NAME), ValidFrom = DateTime.Today.AddDays(-1), ValidTo = DateTime.Today.AddYears(1), }); X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); var storePermissions = new StorePermission(PermissionState.Unrestricted); storePermissions.Flags = StorePermissionFlags.OpenStore; storePermissions.Assert(); store.Open(OpenFlags.ReadWrite); X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Add(cert); store.AddRange(collection); store.Close(); return(new CertificateStore(cert)); } }
/// <summary> /// Creates a self-signed certificate /// http://stackoverflow.com/questions/13806299/how-to-create-a-self-signed-certificate-using-c /// </summary> /// <param name="subjectName"></param> /// <returns></returns> public static X509Certificate2 CreateSelfSignedCertificate(params string[] commonNames) { using (var ctx = new CryptContext()) { ctx.Open(); var nameBuilder = new StringBuilder(); foreach (var commonName in commonNames) { nameBuilder.AppendLine($"CN={commonName}"); } var certificate = ctx.CreateSelfSignedCertificate( new SelfSignedCertProperties { IsPrivateKeyExportable = true, KeyBitLength = 4096, Name = new X500DistinguishedName(nameBuilder.ToString(), X500DistinguishedNameFlags.UseNewLines), ValidFrom = DateTime.Today.AddDays(-1), ValidTo = DateTime.Today.AddYears(1) }); return(certificate); } }
private void ProcessNeedMongoKeysState(CryptContext context, CancellationToken cancellationToken) { var filterBytes = context.GetOperation().ToArray(); var filterDocument = new RawBsonDocument(filterBytes); var filter = new BsonDocumentFilterDefinition <BsonDocument>(filterDocument); var cursor = _keyVaultCollection.Value.FindSync(filter, cancellationToken: cancellationToken); var results = cursor.ToList(cancellationToken); FeedResults(context, results); }
// protected methods protected void FeedResult(CryptContext context, BsonDocument document) { var writerSettings = new BsonBinaryWriterSettings { GuidRepresentation = GuidRepresentation.Unspecified }; var documentBytes = document.ToBson(writerSettings: writerSettings); context.Feed(documentBytes); context.MarkDone(); }
private void ProcessNeedKmsState(CryptContext context, CancellationToken cancellationToken) { var requests = context.GetKmsMessageRequests(); foreach (var request in requests) { SendKmsRequest(request, cancellationToken); } requests.MarkDone(); }
private async Task ProcessNeedKmsStateAsync(CryptContext context, CancellationToken cancellationToken) { var requests = context.GetKmsMessageRequests(); foreach (var request in requests) { await SendKmsRequestAsync(request, cancellationToken).ConfigureAwait(false); } requests.MarkDone(); }
public static void decryptData(byte[] decryptByte, uint startPos, uint inLen, ref byte[] outBytes, CryptContext cryptContext) { if (CryptAlgorithm.RC5 == cryptContext.m_cryptAlgorithm) { Crypt.RC5_ECB_Symmetry_Decode_Byte(decryptByte, startPos, inLen, ref outBytes, cryptContext.m_cryptKeyArr[(int)cryptContext.m_cryptAlgorithm] as RC5_32_KEY, cryptContext); } else { Crypt.DES_ECB_Symmetry_Decode_OpenSSL(decryptByte, startPos, inLen, ref outBytes, cryptContext.m_cryptKeyArr[(int)cryptContext.m_cryptAlgorithm] as DES_key_schedule, cryptContext); } }
private async Task ProcessNeedMongoKeysStateAsync(CryptContext context, CancellationToken cancellationToken) { var filterBytes = context.GetOperation().ToArray(); var filterDocument = new RawBsonDocument(filterBytes); var filter = new BsonDocumentFilterDefinition <BsonDocument>(filterDocument); var cursor = await _keyVaultCollection.Value.FindAsync(filter, cancellationToken : cancellationToken).ConfigureAwait(false); var results = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false); FeedResults(context, results); }
// protected methods protected void FeedResult(CryptContext context, BsonDocument document) { #pragma warning disable 618 var writerSettings = new BsonBinaryWriterSettings(); if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2) { writerSettings.GuidRepresentation = GuidRepresentation.Unspecified; } #pragma warning restore 618 var documentBytes = document.ToBson(writerSettings: writerSettings); context.Feed(documentBytes); context.MarkDone(); }
protected void FeedResults(CryptContext context, IEnumerable <BsonDocument> documents) { var writerSettings = new BsonBinaryWriterSettings { GuidRepresentation = GuidRepresentation.Unspecified }; foreach (var document in documents) { var documentBytes = document.ToBson(writerSettings: writerSettings); context.Feed(documentBytes); } context.MarkDone(); }
// rc5 加密后大小不会变化的 static public bool RC5_ECB_Symmetry_Encode_Byte(byte[] encryptByte, uint startPos, uint inLen, ref byte[] outBytes, RC5_32_KEY rgbKey, CryptContext cryptContext) { try { RC5.RC5_32_ecb_encrypt_one(encryptByte, startPos, inLen, ref outBytes, rgbKey, RC5.RC5_ENCRYPT, cryptContext); return true; } catch { Ctx.m_instance.m_logSys.error("RC5_ECB_Symmetry_Encode_Byte error"); return false; } }
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { backgroundThreadId = GetCurrentThreadId(); using (CryptContext ctx = new CryptContext()) { ctx.Open(); Certificate = ctx.CreateSelfSignedCertificate(CertProperties); } BeginInvoke(new Action(BackroundWorkerFinished), null); }
// private methods private void ProcessNeedCollectionInfoState(CryptContext context, string databaseName, CancellationToken cancellationToken) { var database = _client.GetDatabase(databaseName); var filterBytes = context.GetOperation().ToArray(); var filterDocument = new RawBsonDocument(filterBytes); var filter = new BsonDocumentFilterDefinition <BsonDocument>(filterDocument); var options = new ListCollectionsOptions { Filter = filter }; var cursor = database.ListCollections(options, cancellationToken); var results = cursor.ToList(cancellationToken); FeedResults(context, results); }
private async Task ProcessNeedCollectionInfoStateAsync(CryptContext context, string databaseName, CancellationToken cancellationToken) { var database = _client.GetDatabase(databaseName); var filterBytes = context.GetOperation().ToArray(); var filterDocument = new RawBsonDocument(filterBytes); var filter = new BsonDocumentFilterDefinition <BsonDocument>(filterDocument); var options = new ListCollectionsOptions { Filter = filter }; var cursor = await database.ListCollectionsAsync(options, cancellationToken).ConfigureAwait(false); var results = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false); FeedResults(context, results); }
protected virtual void ProcessState(CryptContext context, string databaseName, CancellationToken cancellationToken) { switch (context.State) { case CryptContext.StateCode.MONGOCRYPT_CTX_NEED_KMS: ProcessNeedKmsState(context, cancellationToken); break; case CryptContext.StateCode.MONGOCRYPT_CTX_NEED_MONGO_KEYS: ProcessNeedMongoKeysState(context, cancellationToken); break; default: throw new InvalidOperationException($"Unexpected context state: {context.State}."); } }
protected byte[] ProcessStates(CryptContext context, string databaseName, CancellationToken cancellationToken) { byte[] result = null; while (context.State != CryptContext.StateCode.MONGOCRYPT_CTX_DONE) { if (context.State == CryptContext.StateCode.MONGOCRYPT_CTX_READY) { result = ProcessReadyState(context); } else { ProcessState(context, databaseName, cancellationToken); } } return(result); }
protected async Task <byte[]> ProcessStatesAsync(CryptContext context, string databaseName, CancellationToken cancellationToken) { byte[] result = null; while (context.State != CryptContext.StateCode.MONGOCRYPT_CTX_DONE) { if (context.State == CryptContext.StateCode.MONGOCRYPT_CTX_READY) { result = ProcessReadyState(context); } else { await ProcessStateAsync(context, databaseName, cancellationToken).ConfigureAwait(false); } } return(result); }
// protected methods protected override void ProcessState(CryptContext context, string databaseName, CancellationToken cancellationToken) { switch (context.State) { case CryptContext.StateCode.MONGOCRYPT_CTX_NEED_MONGO_COLLINFO: ProcessNeedCollectionInfoState(context, databaseName, cancellationToken); break; case CryptContext.StateCode.MONGOCRYPT_CTX_NEED_MONGO_MARKINGS: ProcessNeedMongoMarkingsState(context, databaseName, cancellationToken); break; default: base.ProcessState(context, databaseName, cancellationToken); break; } }
private static X509Certificate2 GenerateCertificate() { string certName = new Uri(WebApiShared.BaseAddress).DnsSafeHost; using (var ctx = new CryptContext()) { ctx.Open(); return(ctx.CreateSelfSignedCertificate( new SelfSignedCertProperties { IsPrivateKeyExportable = true, KeyBitLength = 4096, Name = new X500DistinguishedName($"cn={certName}"), ValidFrom = DateTime.Today.AddDays(-1), ValidTo = DateTime.Today.AddYears(1), })); } }
protected void testRc5() { string testStr = "asdfasdf5"; //byte[] inBytes = System.Text.Encoding.UTF8.GetBytes(testStr); byte[] inBytes = { 0x3f, 0x79, 0xd5, 0xe2, 0x4a, 0x8c, 0xb6, 0xc1, 0x3f, 0x79, 0xd5, 0xe2, 0x4a, 0x8c, 0xb6, 0xc1 }; byte[] outBytes = new byte[8]; uint inSize = (uint)inBytes.Length; RC5_32_KEY rc5Key = new RC5_32_KEY(); // RC5 key RC5.RC5_32_set_key(rc5Key, 16, Crypt.RC5_KEY, RC5.RC5_12_ROUNDS); // 生成秘钥 CryptContext cryptContext = new CryptContext(); Crypt.encryptData(inBytes, 0, 16, ref outBytes, cryptContext); Crypt.decryptData(outBytes, 0, 16, ref inBytes, cryptContext); testStr = System.Text.Encoding.Default.GetString(inBytes); }
// here's a simple example of how to gen a cert programmatically using Pluralsight.Crypto // note you'll need to also reference System.Security.dll to get support for X509Certificate2UI. static void GenSelfSignedCert() { using (CryptContext ctx = new CryptContext()) { ctx.Open(); X509Certificate2 cert = ctx.CreateSelfSignedCertificate( new SelfSignedCertProperties { IsPrivateKeyExportable = true, KeyBitLength = 4096, Name = new X500DistinguishedName("cn=localhost"), ValidFrom = DateTime.Today.AddDays(-1), ValidTo = DateTime.Today.AddYears(1), }); X509Certificate2UI.DisplayCertificate(cert); } }
public static X509Certificate2 GenSelfSignedCert(string commonName, DateTime validFrom, DateTime validTo) { using (CryptContext ctx = new CryptContext()) { ctx.Open(); X509Certificate2 cert = ctx.CreateSelfSignedCertificate( new SelfSignedCertProperties { IsPrivateKeyExportable = true, KeyBitLength = 4096, Name = new X500DistinguishedName("CN=" + commonName), ValidFrom = validFrom, ValidTo = validTo, }); return(cert); } }
public static X509Certificate2 GenerateCertificate() { using (CryptContext ctx = new CryptContext()) { ctx.Open(); X509Certificate2 cert = ctx.CreateSelfSignedCertificate( new SelfSignedCertProperties { IsPrivateKeyExportable = true, KeyBitLength = 1024, Name = new X500DistinguishedName("cn=localhost"), ValidFrom = DateTime.Now, ValidTo = DateTime.Now.AddDays(1), }); return(cert); } }
// private methods private void ProcessNeedCollectionInfoState(CryptContext context, string databaseName, CancellationToken cancellationToken) { if (_metadataClient == null) { // should not be reached throw new InvalidOperationException("Metadata client is null."); } var database = _metadataClient.GetDatabase(databaseName); var filterBytes = context.GetOperation().ToArray(); var filterDocument = new RawBsonDocument(filterBytes); var filter = new BsonDocumentFilterDefinition <BsonDocument>(filterDocument); var options = new ListCollectionsOptions { Filter = filter }; var cursor = database.ListCollections(options, cancellationToken); var results = cursor.ToList(cancellationToken); FeedResults(context, results); }
protected override async Task ProcessStateAsync(CryptContext context, string databaseName, CancellationToken cancellationToken) { switch (context.State) { case CryptContext.StateCode.MONGOCRYPT_CTX_NEED_MONGO_COLLINFO: await ProcessNeedCollectionInfoStateAsync(context, databaseName, cancellationToken).ConfigureAwait(false); break; case CryptContext.StateCode.MONGOCRYPT_CTX_NEED_MONGO_MARKINGS: await ProcessNeedMongoMarkingsStateAsync(context, databaseName, cancellationToken).ConfigureAwait(false); break; default: await base.ProcessStateAsync(context, databaseName, cancellationToken).ConfigureAwait(false); break; } }
internal static void GenerateCertificate( IFileSystem fileSystem, string pathToPfx, string pathToCer, string issuer, string password, DateTime validity) { using (CryptContext ctx = new CryptContext()) { ctx.Open(); X509Certificate2 cert = ctx.CreateSelfSignedCertificate( new SelfSignedCertProperties { IsPrivateKeyExportable = true, KeyBitLength = 2048, Name = new X500DistinguishedName($"cn={issuer}"), ValidFrom = DateTime.Today.AddDays(-1), ValidTo = validity }); if (fileSystem.FileExists(pathToPfx)) { fileSystem.DeleteFile(pathToPfx); } fileSystem.WriteAllBytesToFile(pathToPfx, cert.Export(X509ContentType.Pfx, password)); if (fileSystem.FileExists(pathToCer)) { fileSystem.DeleteFile(pathToCer); } fileSystem.WriteAllTextToFile(pathToCer, "-----BEGIN CERTIFICATE-----\r\n" + Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks) + "\r\n-----END CERTIFICATE-----"); } }
private static void CreateCertificate(string cn) { Console.WriteLine("Creating certificate..."); using (CryptContext ctx = new CryptContext()) { ctx.Open(); X509Certificate2 cert = ctx.CreateSelfSignedCertificate( new SelfSignedCertProperties { IsPrivateKeyExportable = true, KeyBitLength = 4096, Name = new X500DistinguishedName($"cn={cn}"), ValidFrom = DateTime.Today.AddDays(-1), ValidTo = DateTime.Today.AddYears(1), } ); byte[] certFileRaw = cert.Export(X509ContentType.Pfx, "banaantje"); string filePath = Directory.GetCurrentDirectory() + "\\certificate.pfx"; File.WriteAllBytes(filePath, certFileRaw); File.WriteAllText(Directory.GetCurrentDirectory() + "\\certificate.cer", "-----BEGIN CERTIFICATE-----\r\n" + Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks) + "\r\n-----END CERTIFICATE-----" ); Console.WriteLine("Done"); Console.WriteLine("Adding to store..."); using (X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadWrite); store.Add(cert); } Console.WriteLine("Done"); } }
public ClientBuffer() { m_rawBuffer = new MsgBuffer(); m_msgBuffer = new MsgBuffer(); //m_sendTmpBA = new ByteBuffer(); m_sendTmpBuffer = new MsgBuffer(); m_socketSendBA = new ByteBuffer(); //m_socketSendBA.m_id = 1000; //m_dynBuff = new DynamicBuffer<byte>(8096); m_unCompressHeaderBA = new ByteBuffer(); m_sendData = new ByteBuffer(); m_tmpData = new ByteBuffer(4); m_tmp1fData = new ByteBuffer(4); m_readMutex = new MMutex(false, "ReadMutex"); m_writeMutex = new MMutex(false, "WriteMutex"); #if MSG_ENCRIPT m_cryptContext = new CryptContext(); #endif }
// rc5 加密后大小不会变化的 static public bool DES_ECB_Symmetry_Encode_OpenSSL(byte[] encryptByte, uint startPos, uint inLen, ref byte[] outBytes, DES_key_schedule rgbKey, CryptContext cryptContext) { try { Dec.DES_ecb_encrypt_one(encryptByte, startPos, inLen, ref outBytes, rgbKey, RC5.RC5_ENCRYPT, cryptContext); return true; } catch { Ctx.m_instance.m_logSys.error("DES_ECB_Symmetry_Encode_OpenSSL error"); return false; } }