/// <summary> /// copy of legacy PortalSecurity.EncryptString method /// </summary> /// <param name="message">string to be encrypted</param> /// <param name="passphrase">key for encryption</param> /// <returns></returns> public override string EncryptString(string message, string passphrase) { byte[] results; var utf8 = new UTF8Encoding(); using (var hashProvider = CryptographyUtils.CreateSHA512()) { byte[] tdesKey = hashProvider.ComputeHash(utf8.GetBytes(passphrase)); byte[] trimmedBytes = new byte[24]; Buffer.BlockCopy(tdesKey, 0, trimmedBytes, 0, 24); var tdesAlgorithm = new TripleDESCryptoServiceProvider { Key = trimmedBytes, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; byte[] dataToEncrypt = utf8.GetBytes(message); try { ICryptoTransform encryptor = tdesAlgorithm.CreateEncryptor(); results = encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length); } finally { // Clear the TripleDes and Hashprovider services of any sensitive information tdesAlgorithm.Clear(); hashProvider.Clear(); } } //Return the encrypted string as a base64 encoded string return(Convert.ToBase64String(results)); }
/// <summary> /// This method publishes certificate revocation lists (CRLs) for a certification authority (CA). /// <para> /// The PublishCRL method publishes a CRL based on the CA's current certificate, as well as CRLs /// based on any CA certificates that have been renewed and are not yet expired. /// </para> /// </summary> /// <param name="deltaOnly"> /// A delta CRL is published, or the most recent delta CRL is republished if <strong>updateFilesOnly</strong> /// parameter is set. Note that if the CA has not enabled delta CRL publishing, use of this flag will result /// in an error.</param> /// <param name="updateFilesOnly"> /// The most recent base or delta CRL, is republished. The CA will not republish a CRL to a CRL distribution point /// if the CRL at the distribution point is already the most recent CRL. /// </param> /// <exception cref="UninitializedObjectException">The object is not properly initialized.</exception> /// <exception cref="ServerUnavailableException">CA server is not accessible via RPC/DCOM.</exception> public void PublishCRL(Boolean deltaOnly = false, Boolean updateFilesOnly = false) { if (String.IsNullOrEmpty(Name)) { throw new UninitializedObjectException(); } if (!Ping()) { ServerUnavailableException e = new ServerUnavailableException(DisplayName); e.Data.Add("Source", OfflineSource.DCOM); throw e; } CertAdmin = new CCertAdmin(); try { if (deltaOnly) { CertAdmin.PublishCRLs(ConfigString, new DateTime(0), 0x2); } else if (updateFilesOnly) { CertAdmin.PublishCRLs(ConfigString, new DateTime(0), 0x11); } else { CertAdmin.PublishCRLs(ConfigString, new DateTime(0), 0x1); } } catch (Exception e) { throw Error.ComExceptionHandler(e); } finally { CryptographyUtils.ReleaseCom(CertAdmin); } }
public static void SplitMetadata(IFileMetadata fileMetadata, ref Track track, ref TrackStatistic trackStatistic, ref Album album, ref Artist artist, ref Genre genre) { string path = fileMetadata.Path; // Track information track.Path = path; track.SafePath = path.ToSafePath(); track.FileName = FileUtils.NameWithoutExtension(path); track.Duration = Convert.ToInt64(fileMetadata.Duration.TotalMilliseconds); track.MimeType = fileMetadata.MimeType; track.BitRate = fileMetadata.BitRate; track.SampleRate = fileMetadata.SampleRate; track.TrackTitle = MetadataUtils.SanitizeTag(fileMetadata.Title.Value); track.TrackNumber = MetadataUtils.SafeConvertToLong(fileMetadata.TrackNumber.Value); track.TrackCount = MetadataUtils.SafeConvertToLong(fileMetadata.TrackCount.Value); track.DiscNumber = MetadataUtils.SafeConvertToLong(fileMetadata.DiscNumber.Value); track.DiscCount = MetadataUtils.SafeConvertToLong(fileMetadata.DiscCount.Value); track.Year = MetadataUtils.SafeConvertToLong(fileMetadata.Year.Value); track.HasLyrics = string.IsNullOrWhiteSpace(fileMetadata.Lyrics.Value) ? 0 : 1; track.NeedsIndexing = 0; // TrackStatistic information trackStatistic.Path = path; trackStatistic.SafePath = path.ToSafePath(); trackStatistic.Rating = fileMetadata.Rating.Value; // Before proceeding, get the available artists string albumArtist = GetFirstAlbumArtist(fileMetadata); string trackArtist = GetFirstArtist(fileMetadata); // will be used for the album if no album artist is found // Album information album.AlbumTitle = string.IsNullOrWhiteSpace(fileMetadata.Album.Value) ? Defaults.UnknownAlbumText : MetadataUtils.SanitizeTag(fileMetadata.Album.Value); album.AlbumArtist = (albumArtist == Defaults.UnknownArtistText ? trackArtist : albumArtist); album.DateAdded = DateTime.Now.Ticks; album.DateCreated = FileUtils.DateCreatedTicks(path); UpdateAlbumYear(album, MetadataUtils.SafeConvertToLong(fileMetadata.Year.Value)); // Artist information artist.ArtistName = trackArtist; // Genre information genre.GenreName = GetFirstGenre(fileMetadata); // Metadata hash System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(album.AlbumTitle); sb.Append(artist.ArtistName); sb.Append(genre.GenreName); sb.Append(track.TrackTitle); sb.Append(track.TrackNumber); sb.Append(track.Year); track.MetaDataHash = CryptographyUtils.MD5Hash(sb.ToString()); // File information track.FileSize = FileUtils.SizeInBytes(path); track.DateFileModified = FileUtils.DateModifiedTicks(path); track.DateLastSynced = DateTime.Now.Ticks; }
/// <summary> /// Retrieves the most recent 'CA Exchange' certificate. If the certificate does not exist, the method /// will instruct CA server to generate or enroll a new one. /// </summary> /// <exception cref="UninitializedObjectException">The object is not properly initialized.</exception> /// <exception cref="ServerUnavailableException">CA server is not accessible via RPC/DCOM.</exception> /// <exception cref="UnauthorizedAccessException">The caller do not have at least <strong>Read</strong> permissions.</exception> /// <exception cref="PlatformNotSupportedException">Current CA is not <strong>Enterprise CA</strong>. Only Enterprise CAs supports this feature.</exception> /// <returns>CA Exchange certificate.</returns> public X509Certificate2 GetCAExchangeCertificate() { if (String.IsNullOrEmpty(Name)) { throw new UninitializedObjectException(); } if (!IsEnterprise) { throw new PlatformNotSupportedException(Error.E_NONENTERPRISE); } if (!Ping()) { ServerUnavailableException e = new ServerUnavailableException(DisplayName); e.Data.Add("Source", OfflineSource.DCOM); throw e; } CertAdmin = new CCertAdmin(); try { Int32 index = (Int32)CertAdmin.GetCAProperty(ConfigString, CertAdmConst.CR_PROP_CAXCHGCERTCOUNT, 0, 1, 0) - 1; if (index >= 0) { String Base64 = (String)CertAdmin.GetCAProperty(ConfigString, CertAdmConst.CR_PROP_CAXCHGCERT, index, 3, 1); return(new X509Certificate2(Convert.FromBase64String(Base64))); } throw new Exception(String.Format(Error.E_XCHGUNAVAILABLE, DisplayName)); } catch (Exception e) { throw Error.ComExceptionHandler(e); } finally { CryptographyUtils.ReleaseCom(CertAdmin); } }
void InitializeCom(IX509CertificateTemplate template) { if (CryptographyUtils.TestOleCompat()) { if (((Int32)template.Property[EnrollmentTemplateProperty.TemplatePropPrivateKeyFlags] & (Int32)PrivateKeyFlags.RequireKeyArchival) > 0) { KeyArchival = true; try { IObjectId soid = (IObjectId)template.Property[EnrollmentTemplateProperty.TemplatePropSymmetricAlgorithm]; EncryptionAlgorithm = new Oid(soid.Value); } catch { } try { KeyLength = (Int32)template.Property[EnrollmentTemplateProperty.TemplatePropSymmetricKeyLength]; } catch { } } } else { if (((UInt32)template.Property[EnrollmentTemplateProperty.TemplatePropPrivateKeyFlags] & (Int32)PrivateKeyFlags.RequireKeyArchival) > 0) { KeyArchival = true; try { IObjectId soid = (IObjectId)template.Property[EnrollmentTemplateProperty.TemplatePropSymmetricAlgorithm]; EncryptionAlgorithm = new Oid(soid.Value); } catch { } try { KeyLength = Convert.ToInt32(template.Property[EnrollmentTemplateProperty.TemplatePropSymmetricKeyLength]); } catch { } } } }
void InitializeCom(IX509CertificateTemplate template) { if (CryptographyUtils.TestOleCompat()) { GeneralFlags = (Int32)template.Property[EnrollmentTemplateProperty.TemplatePropGeneralFlags]; EnrollmentOptions = (Int32)template.Property[EnrollmentTemplateProperty.TemplatePropEnrollmentFlags]; subjectFlags = (Int32)template.Property[EnrollmentTemplateProperty.TemplatePropSubjectNameFlags]; ValidityPeriod = get_validity(null, (Int64)template.Property[EnrollmentTemplateProperty.TemplatePropValidityPeriod]); RenewalPeriod = get_validity(null, (Int64)template.Property[EnrollmentTemplateProperty.TemplatePropRenewalPeriod]); } else { GeneralFlags = Convert.ToInt32((UInt32)template.Property[EnrollmentTemplateProperty.TemplatePropGeneralFlags]); EnrollmentOptions = Convert.ToInt32((UInt32)template.Property[EnrollmentTemplateProperty.TemplatePropEnrollmentFlags]); subjectFlags = unchecked ((Int32)(UInt32)template.Property[EnrollmentTemplateProperty.TemplatePropSubjectNameFlags]); ValidityPeriod = get_validity(null, Convert.ToInt64((UInt64)template.Property[EnrollmentTemplateProperty.TemplatePropValidityPeriod])); RenewalPeriod = get_validity(null, Convert.ToInt64((UInt64)template.Property[EnrollmentTemplateProperty.TemplatePropRenewalPeriod])); } try { SupersededTemplates = (String[])template.Property[EnrollmentTemplateProperty.TemplatePropSupersede]; } catch { } List <X509Extension> exts2 = (from IX509Extension ext in (IX509Extensions)template.Property[EnrollmentTemplateProperty.TemplatePropExtensions] select new X509Extension(ext.ObjectId.Value, Convert.FromBase64String(ext.RawData[Interop.CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_BASE64]), ext.Critical)).Select(CryptographyUtils.ConvertExtension).ToList(); foreach (X509Extension ext in exts2) { _exts.Add(ext); } }
/// <inheritdoc /> public void SetCertificateExtension(Int32 requestID, X509Extension extension) { if (extension == null) { throw new ArgumentNullException(nameof(extension)); } var certAdmin = new CCertAdminClass(); // BSTR is length-prefixed type, so allocate extra 4 bytes to store BSTR length IntPtr pbBstr = Marshal.AllocHGlobal(extension.RawData.Length + 4); // write length in front of actual BSTR value Marshal.WriteInt32(pbBstr, 0, extension.RawData.Length); // copy raw bytes right after length prefix Marshal.Copy(extension.RawData, 0, pbBstr + 4, extension.RawData.Length); // create an instance of VARIANT and configure it var variant = new OleAut.VARIANT { vt = OleAut.VT_BSTR, // the pointer to BSTR doesn't include prefix length, so skip 4 bytes pvRecord = pbBstr + 4 }; Int32 flags = extension.Critical ? 1 : 0; IntPtr pvarValue = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(OleAut.VARIANT))); Marshal.StructureToPtr(variant, pvarValue, false); try { certAdmin.SetCertificateExtension(_configString, requestID, extension.Oid.Value, CertAdmConstants.ProptypeBinary, flags, pvarValue); } finally { Marshal.FreeHGlobal(pbBstr); Marshal.FreeHGlobal(pvarValue); CryptographyUtils.ReleaseCom(certAdmin); } }
public bool InitializeClient(GitClient gitClient) { lock (_lock) { try { if (File.Exists(Common.UserSettingFilePath)) { using (var stream = new MemoryStream()) { CryptographyUtils.DecryptFiletoStream(Common.UserSettingFilePath, stream, Common.GetMachineGuid()); stream.Position = 0; userSetting = UserSetting.Parser.ParseFrom(stream); InitializeClient(userSetting.JiraServerAddress, userSetting.JiraUserName, userSetting.JiraPassword); if (!string.IsNullOrEmpty(userSetting.ProxyServer)) { JiraRequestProxy myProxy = new JiraRequestProxy(userSetting.ProxyUserName, userSetting.ProxyPassword, userSetting.ProxyServer); client.Proxy = myProxy; } } } } catch (Exception ex) { Console.WriteLine("Exception occurred in JiraController constructor : " + ex.ToString()); } } return(false); }
public Administrator(string lastName, string firstName, string login, string password, DateTime currentDate) { LastName = lastName; FirstName = firstName; Login = login; PasswordHash = CryptographyUtils.ComputeHash(password); CreationDate = currentDate; }
private string GetHash(string data) { using (var sha256 = CryptographyUtils.CreateSHA256()) { var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(data)); return(Convert.ToBase64String(hash)); } }
public static CspCNGCollection EnumCNGProviders() { if (!CryptographyUtils.TestCNGCompat()) { throw new PlatformNotSupportedException(); } return(m_enumcngprovs()); }
void releaseUnmanagedResources() { if (dbRow != null) { CryptographyUtils.ReleaseCom(dbRow); } CryptographyUtils.ReleaseCom(_caView); }
public virtual void ChangePassword(string currentPassword, string newPassword) { var currentPasswordHash = CryptographyUtils.ComputeHash(currentPassword); ValidationUtils.Assert(PasswordHash == currentPasswordHash, "Указан неверный пароль."); PasswordHash = CryptographyUtils.ComputeHash(newPassword); }
private static void FullNameMaskDemo() { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); //解决中文乱码 var encoding = Encoding.GetEncoding("GBK"); var name = "张三丰"; var mask = CryptographyUtils.FullNameMask(name); Console.WriteLine(mask); }
/// <summary> /// Registers or updates a current object in local registry. /// </summary> /// <exception cref="UninitializedObjectException"> /// The current object is not properly initialized through any of public constructor. /// </exception> /// <exception cref="NotSupportedException"> /// <strong>Authentication</strong> property is set to <strong>None</strong>. /// </exception> public void Register() { if (URL == null) { throw new UninitializedObjectException(); } CX509EnrollmentHelper urlClass = new CX509EnrollmentHelper(); urlClass.Initialize(UserContext ? X509CertificateEnrollmentContext.ContextUser : X509CertificateEnrollmentContext.ContextMachine); try { switch (Authentication) { case PolicyAuthenticationEnum.Anonymous: case PolicyAuthenticationEnum.Kerberos: urlClass.AddPolicyServer( URL.AbsoluteUri, PolicyId, 0, (X509EnrollmentAuthFlags)(Int32)Authentication, null, null ); break; case PolicyAuthenticationEnum.UserNameAndPassword: urlClass.AddPolicyServer( URL.AbsoluteUri, PolicyId, 0, (X509EnrollmentAuthFlags)(Int32)Authentication, uName, Marshal.PtrToStringAuto(Marshal.SecureStringToBSTR(uPassword)) ); break; case PolicyAuthenticationEnum.ClientCertificate: urlClass.AddPolicyServer( URL.AbsoluteUri, PolicyId, 0, (X509EnrollmentAuthFlags)(Int32)Authentication, uName, null ); break; default: throw new NotSupportedException(); } registered = true; } catch (Exception e) { throw Error.ComExceptionHandler(e); } finally { CryptographyUtils.ReleaseCom(urlClass); } }
public static void SplitMetadata(string path, ref Track track, ref Album album, ref Artist artist, ref Genre genre) { if (!string.IsNullOrEmpty(path)) { var fmd = new FileMetadata(path); var fi = new FileInformation(path); // Track information track.Path = path; track.FileName = fi.NameWithoutExtension; track.Duration = Convert.ToInt64(fmd.Duration.TotalMilliseconds); track.MimeType = fmd.MimeType; track.BitRate = fmd.BitRate; track.SampleRate = fmd.SampleRate; track.TrackTitle = MetadataUtils.SanitizeTag(fmd.Title.Value); track.TrackNumber = MetadataUtils.SafeConvertToLong(fmd.TrackNumber.Value); track.TrackCount = MetadataUtils.SafeConvertToLong(fmd.TrackCount.Value); track.DiscNumber = MetadataUtils.SafeConvertToLong(fmd.DiscNumber.Value); track.DiscCount = MetadataUtils.SafeConvertToLong(fmd.DiscCount.Value); track.Year = MetadataUtils.SafeConvertToLong(fmd.Year.Value); track.Rating = fmd.Rating.Value; // Before proceeding, get the available artists string albumArtist = GetFirstAlbumArtist(fmd); string trackArtist = GetFirstArtist(fmd); // will be used for the album if no album artist is found // Album information album.AlbumTitle = string.IsNullOrWhiteSpace(fmd.Album.Value) ? Defaults.UnknownAlbumString : MetadataUtils.SanitizeTag(fmd.Album.Value); album.AlbumArtist = (albumArtist == Defaults.UnknownAlbumArtistString ? trackArtist : albumArtist); album.DateAdded = FileOperations.GetDateCreated(path); IndexerUtils.UpdateAlbumYear(album, MetadataUtils.SafeConvertToLong(fmd.Year.Value)); // Artist information artist.ArtistName = trackArtist; // Genre information genre.GenreName = GetFirstGenre(fmd); // Metadata hash System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(album.AlbumTitle); sb.Append(artist.ArtistName); sb.Append(genre.GenreName); sb.Append(track.TrackTitle); sb.Append(track.TrackNumber); sb.Append(track.Year); track.MetaDataHash = CryptographyUtils.MD5Hash(sb.ToString()); // File information track.FileSize = fi.SizeInBytes; track.DateFileModified = fi.DateModifiedTicks; track.DateLastSynced = DateTime.Now.Ticks; } }
/// <inheritdoc /> public Int32 DeleteLastUpdatedRequests(DateTime notAfter) { ICertAdmin2 certAdmin = new CCertAdminClass(); try { return(certAdmin.DeleteRow(_configString, (Int32)BulkRowRemovalOption.LastChanged, notAfter, (Int32)AdcsDbCRTable.Request, 0)); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
/// <inheritdoc /> public Int32 DeleteExpiredCRLs(DateTime notAfter) { ICertAdmin2 certAdmin = new CCertAdminClass(); try { return(certAdmin.DeleteRow(_configString, (Int32)BulkRowRemovalOption.Expired, notAfter, (Int32)AdcsDbCRTable.CRL, 0)); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
void publishCRL(AdcsCrlPublishType crlFlags, DateTime?nexUpdate = null) { ICertAdmin2 certAdmin = new CCertAdminClass(); try { certAdmin.PublishCRLs(_configString, nexUpdate ?? DateTime.UtcNow, (Int32)crlFlags); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
/// <inheritdoc /> public void RevokeRequest(String serialNumber, DateTime?revocationDate = null, AdcsCrlReason reason = AdcsCrlReason.Unspecified) { ICertAdmin2 certAdmin = new CCertAdminClass(); try { certAdmin.RevokeCertificate(_configString, serialNumber, (Int32)reason, revocationDate ?? DateTime.UtcNow); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
/// <inheritdoc /> public void DenyRequest(Int32 requestID) { ICertAdmin2 certAdmin = new CCertAdminClass(); try { certAdmin.DenyRequest(_configString, requestID); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
/// <inheritdoc /> public AdcsPropCertState ApproveRequest(Int32 requestID) { ICertAdmin2 certAdmin = new CCertAdminClass(); try { return((AdcsPropCertState)certAdmin.ResubmitRequest(_configString, requestID)); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
/// <inheritdoc /> public Int32 DeleteDatabaseRow(Int32 requestID, AdcsDbCRTable table = AdcsDbCRTable.Request) { ICertAdmin2 certAdmin = new CCertAdminClass(); try { return(certAdmin.DeleteRow(_configString, 0, new DateTime(), (Int32)table, requestID)); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
protected override void UpdateDomain(AppUserDto data, string userId) { UserName = data.UserName; FullName = data.FullName; Email = data.Email; IsActive = data.IsActive; CreatedDate = DateTime.Now; PasswordHash = CryptographyUtils.HashPassword(data.Password); SecurityStamp = ""; }
private async Task CreateSignatureAsync(SortedDictionary <string, string> data) { // Combine as string var source = smsKey + "&" + data.JoinAsString() + smsKey; // Calculate signature var signatureBytes = await CryptographyUtils.MD5Async(source); data["signature"] = Convert.ToHexString(signatureBytes).ToLower(); }
public ActionResult GenerateKey() { string guid = Guid.NewGuid().ToString(); string appId = CryptographyUtils.SHA1(guid); string appSecret = CryptographyUtils.DesEncrypt(appId); //string appSecret = SHA256ManagedUtils.GetHashedPassword(guid, appId); return(Content(string.Format("AppID:{0}<br>AppSecret:{1}", appId, appSecret))); }
private static void MD5EncryptDemo() { var original = "This is MD5 Encrypt Demo."; var result = CryptographyUtils.MD5Encrypt(original); Console.WriteLine(result); if (result.Equals("7c243f5af73c7ff5ec7fec10f45172e9", StringComparison.CurrentCultureIgnoreCase)) { Console.WriteLine("true"); } }
public ActionResult Create(客戶資料 客戶資料) { if (ModelState.IsValid) { 客戶資料.密碼 = CryptographyUtils.SHA256Cryp(客戶資料.密碼); _客戶資料Service.Create(客戶資料); return(RedirectToAction("Index")); } return(View(客戶資料)); }
void get_extensions() { if (CTLInfo.cExtension > 0) { Wincrypt.CERT_EXTENSIONS extstruct = new Wincrypt.CERT_EXTENSIONS { rgExtension = CTLInfo.rgExtension, cExtension = CTLInfo.cExtension }; _listExtensions.AddRange(CryptographyUtils.DecodeX509ExtensionCollection2(extstruct)); } }
private static void GetFileMD5HashDemo() { var path = System.IO.Directory.GetCurrentDirectory() + @"\Demo.png"; var md5 = CryptographyUtils.GetFileMD5Hash(path); Console.WriteLine(md5); if (md5.Equals("c7862d93618a4abe90c708a4b0d01ef3", StringComparison.CurrentCultureIgnoreCase)) { Console.WriteLine("true"); } }