public void StoreKey(string bucket, string handle, CryptoKey decryptedCryptoKey) { byte[] encryptedKey = this.asymmetricCrypto.Encrypt(decryptedCryptoKey.Key, true); var encryptedCryptoKey = new CryptoKey(encryptedKey, decryptedCryptoKey.ExpiresUtc); this.dataStore.StoreKey(bucket, handle, encryptedCryptoKey); this.cache.StoreKey(bucket, handle, new CachedCryptoKey(encryptedCryptoKey, decryptedCryptoKey)); }
/// <summary> /// Explicit constructor /// </summary> /// <param name="hashMode">Any one of the Crypto.HashModes constants (simple or salted)</param> /// <param name="salt">Salt to use in hash. If non-null, forces salted hash mode. If null, uses simple hash mode</param> public HashEncoder(string hashMode, byte[] salt) { CryptoKey key = new CryptoKey(); if (salt != null) { key.Properties.Add(new CryptoProperty() { Name = Crypto.PropertyNames.HashSaltedMode, ValueType = Crypto.PropertyValueTypes.String, Value = hashMode } ); key.Segments.Add(Crypto.SegmentNames.HashSalt, salt); } else { key.Properties.Add(new CryptoProperty() { Name = Crypto.PropertyNames.HashSimpleMode, ValueType = Crypto.PropertyValueTypes.String, Value = hashMode } ); } }
public Rijndael(CryptoKey cryptoKey = null) { _rijndaelManaged = new RijndaelManaged(); if (cryptoKey == null) return; _key = cryptoKey.Key; _iv = cryptoKey.IV; }
public TripleDes(CryptoKey cryptoKey = null) { _tripleDes = TripleDES.Create(); if (cryptoKey == null) return; _key = cryptoKey.Key; _iv = cryptoKey.IV; }
public bool IsEqual(string value, CryptoKey key) { using (Rfc2898DeriveBytes derivedBytes = new Rfc2898DeriveBytes(value, key.Salt)) { byte[] newKey = derivedBytes.GetBytes(settings.SaltSize); return newKey.SequenceEqual(key.Key); } }
/// <summary> /// Constructor called by Factory methods. Sets common default values for Symmetric key encryption /// </summary> /// <param name="encryptorMode">One of the Crypto.PropertyTypes.EncodeMode constants or can be any specific user implementation</param> /// <param name="key">Array of bytes appropriate for this mode</param> /// <param name="IV">(also called InitializationVector) Array of bytes appropriate for this mode</param> private SymmetricEncoder(string encryptorMode, byte[] key, byte[] IV) { _key = new CryptoKey(); _key.Properties.Add(new CryptoProperty() { Name = Crypto.PropertyNames.EncodeMode, Value = encryptorMode, ValueType = Crypto.PropertyValueTypes.String }); _key.Segments[Crypto.SegmentNames.SymmetricKey] = key; _key.Segments[Crypto.SegmentNames.SymmetricIv] = IV; }
public static byte[] EncryptData(CryptoKey cryptoKey, CryptoIV cryptoIV, byte[] data) { // Advanced Encryption Standard ICryptoTransform encryptor = new RijndaelManaged().CreateEncryptor(cryptoKey, cryptoIV); using (MemoryStream stream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(data, 0, data.Length); cryptoStream.FlushFinalBlock(); return stream.ToArray(); } } }
public SetupOtpDeviceLink(Controller controller, ApiClient apiClient, ServerAccount serverAccount, CryptoKey cryptoKey) { InitializeComponent(); Controller = controller; _apiClient = apiClient; _serverAccount = serverAccount; _cryptoKey = cryptoKey; _loadingAnimationRunning = true; ImageAnimator.Animate(lblQrCode.Image, AnimateLoader); txtOtpDeviceLinkCode.Visible = Program.AppEnvDebug; }
public CryptoKey GetCryptoKey(string password) { byte[] mySaltHash = new byte[32]; byte[] myPasswordHash = Encoding.UTF8.GetBytes(password); CryptProvider.GetBytes(mySaltHash); CryptManager = new SHA256Managed(); byte[] hashedPassword = CryptManager.ComputeHash(mySaltHash.Concat(myPasswordHash).ToArray(), 0, mySaltHash.Length + myPasswordHash.Length); CryptoKey response = new CryptoKey(); response.Salt = BitConverter.ToString(mySaltHash).Replace("-",""); response.Hash = BitConverter.ToString(hashedPassword).Replace("-",""); return response; }
public static string CompressEncryptString(string textToEncrypt, CryptoKey key) { if (string.IsNullOrEmpty(textToEncrypt)) { return string.Empty; } textToEncrypt = Compress(textToEncrypt); using (AesCryptoServiceProvider des = new AesCryptoServiceProvider { Key = key.Key, IV = key.Iv }) using (ICryptoTransform desencrypt = des.CreateEncryptor()) using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, desencrypt, CryptoStreamMode.Write)) using (StreamWriter streamWriter = new StreamWriter(cryptoStream)) { streamWriter.Write(textToEncrypt); } return Convert.ToBase64String(memoryStream.ToArray()); } }
public static string DecompressDecryptString(string textToDecrypt, CryptoKey key) { if (string.IsNullOrEmpty(textToDecrypt)) { return string.Empty; } string compressedText; byte[] bytes = Convert.FromBase64String(textToDecrypt); using (AesCryptoServiceProvider des = new AesCryptoServiceProvider { Key = key.Key, IV = key.Iv }) using (ICryptoTransform desdecrypt = des.CreateDecryptor()) using (MemoryStream msDecrypt = new MemoryStream(bytes)) using (CryptoStream cryptoStream = new CryptoStream(msDecrypt, desdecrypt, CryptoStreamMode.Read)) using (StreamReader srDecrypt = new StreamReader(cryptoStream)) { compressedText = srDecrypt.ReadToEnd(); } return Decompress(compressedText); }
public Authority(string name) { DSA dsa = new DSA(new DSAParameters(512)); this.key = new CryptoKey(dsa); this.name = name; }
/// <summary> /// Gets the return to signature. /// </summary> /// <param name="returnTo">The return to.</param> /// <param name="cryptoKey">The crypto key.</param> /// <returns> /// The generated signature. /// </returns> /// <remarks> /// Only the parameters in the return_to URI are signed, rather than the base URI /// itself, in order that OPs that might change the return_to's implicit port :80 part /// or other minor changes do not invalidate the signature. /// </remarks> private byte[] GetReturnToSignature(Uri returnTo, CryptoKey cryptoKey = null) { Requires.NotNull(returnTo, "returnTo"); // Assemble the dictionary to sign, taking care to remove the signature itself // in order to accurately reproduce the original signature (which of course didn't include // the signature). // Also we need to sort the dictionary's keys so that we sign in the same order as we did // the last time. var returnToParameters = HttpUtility.ParseQueryString(returnTo.Query); returnToParameters.Remove(ReturnToSignatureParameterName); var sortedReturnToParameters = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (string key in returnToParameters) { sortedReturnToParameters.Add(key, returnToParameters[key]); } Logger.Bindings.DebugFormat("ReturnTo signed data: {0}{1}", Environment.NewLine, sortedReturnToParameters.ToStringDeferred()); // Sign the parameters. byte[] bytesToSign = KeyValueFormEncoding.GetBytes(sortedReturnToParameters); byte[] signature; try { if (cryptoKey == null) { cryptoKey = this.cryptoKeyStore.GetKey(SecretUri.AbsoluteUri, returnToParameters[ReturnToSignatureHandleParameterName]); ErrorUtilities.VerifyProtocol( cryptoKey != null, MessagingStrings.MissingDecryptionKeyForHandle, SecretUri.AbsoluteUri, returnToParameters[ReturnToSignatureHandleParameterName]); } using (var signer = HmacAlgorithms.Create(HmacAlgorithms.HmacSha256, cryptoKey.Key)) { signature = signer.ComputeHash(bytesToSign); } } catch (ProtocolException ex) { throw ErrorUtilities.Wrap(ex, OpenIdStrings.MaximumAuthenticationTimeExpired); } return signature; }
public Authority(X509Certificate cert, CryptoKey key) { this.key = key; this.ca = new X509CertificateAuthority(cert, key, this.serial); this.name = cert.Subject.Common; }
/// <summary> /// Non-op. Placeholder for future expansion /// </summary> /// <param name="isDisposing"></param> public void Dispose(bool isDisposing) { _key = null; if (isDisposing) { } }
/// <summary> /// Create a key suitable for a hashing using a specific algorithm /// </summary> /// <param name="hashMode">One of the Crypto.HashModesSimple constants</param> /// <returns>New hash key</returns> public static CryptoKey CreateKey(string hashMode) { var key = new CryptoKey(); key.Properties.Add(new CryptoProperty() { Name = Crypto.PropertyNames.HashSimpleMode, Value = hashMode, ValueType = Crypto.PropertyValueTypes.String }); return key; }
public static byte[] EncryptData(byte[] data, out CryptoKey cryptoKey, out CryptoIV cryptoIV) { cryptoKey = new CryptoKey(); cryptoIV = new CryptoIV(); return EncryptData(cryptoKey, cryptoIV, data); }
private CryptoKey Decrypt(string bucket, string handle, CryptoKey encryptedCryptoKey) { if (encryptedCryptoKey == null) { return null; } // Avoid the asymmetric decryption if possible by looking up whether we have that in our cache. CachedCryptoKey cached = (CachedCryptoKey)this.cache.GetKey(bucket, handle); if (cached != null && MessagingUtilities.AreEquivalent(cached.EncryptedKey, encryptedCryptoKey.Key)) { return cached; } byte[] decryptedKey = this.asymmetricCrypto.Decrypt(encryptedCryptoKey.Key, true); var decryptedCryptoKey = new CryptoKey(decryptedKey, encryptedCryptoKey.ExpiresUtc); // Store the decrypted version in the cache to save time next time. this.cache.StoreKey(bucket, handle, new CachedCryptoKey(encryptedCryptoKey, decryptedCryptoKey)); return decryptedCryptoKey; }
static void Main(string[] args) { Authorities(); return; SimpleSerialNumber seq = new SimpleSerialNumber(); X509CertificateAuthority ca = X509CertificateAuthority.SelfSigned( seq, new X509Name("CN=."), TimeSpan.FromDays(10) ); Console.WriteLine(ca.Certificate); DSA dsa = new DSA(new DSAParameters(512)); CryptoKey key = new CryptoKey(dsa); X509Request req = new X509Request(0, new X509Name("CN=com."), key); req.Sign(key, MessageDigest.DSS1); X509Certificate cert = ca.ProcessRequest(req, TimeSpan.FromDays(10)); Console.WriteLine(cert); Console.WriteLine("CA Verified: " + cert.Verify(ca.Key)); Console.WriteLine("Self Verified: " + cert.Verify(key)); SimpleSerialNumber serial2 = new SimpleSerialNumber(); X509CertificateAuthority caSelf = new X509CertificateAuthority( cert, key, serial2); X509Request req2 = cert.CreateRequest(key, MessageDigest.DSS1); X509Name subject = req2.Subject; Console.WriteLine("Request1: " + req); Console.WriteLine("Request2: " + req2); X509Certificate cert2 = caSelf.ProcessRequest(req2, TimeSpan.FromDays(10)); Console.WriteLine("Cert2: " + cert2); DH dh = new DH(128, 5); MessageDigestContext mdc = new MessageDigestContext(MessageDigest.DSS1); byte[] msg = dh.PublicKey; byte[] sig = mdc.Sign(msg, key); Console.WriteLine(dh); Console.WriteLine("DH P : " + BitConverter.ToString(dh.P)); Console.WriteLine("DH G : " + BitConverter.ToString(dh.G)); Console.WriteLine("DH Secret Key: " + BitConverter.ToString(dh.PrivateKey)); Console.WriteLine("DH Public Key: " + BitConverter.ToString(msg)); Console.WriteLine("DH Signature : " + BitConverter.ToString(sig)); Console.WriteLine(mdc.Verify(msg, sig, key)); }
public static byte[] GenerateMAC(CryptoKey validationKey, byte[] data) { HMACSHA256 hmac = new HMACSHA256(validationKey.Value); return hmac.ComputeHash(data); }
/// <summary> /// Initializes a new instance of the <see cref="CachedCryptoKey"/> class. /// </summary> /// <param name="encrypted">The encrypted key.</param> /// <param name="decrypted">The decrypted key.</param> internal CachedCryptoKey(CryptoKey encrypted, CryptoKey decrypted) : base(decrypted.Key, decrypted.ExpiresUtc) { Contract.Requires(encrypted != null); Contract.Requires(decrypted != null); Contract.Requires(encrypted.ExpiresUtc == decrypted.ExpiresUtc); this.EncryptedKey = encrypted.Key; }
public bool TestCryptoKey(string password, CryptoKey criptoKey) { // 1. Hash password using CriptoKey Salt's byte[] passwordHash = Encoding.UTF8.GetBytes(password); byte[] saltHash = StringToByteArray(criptoKey.Salt); byte[] hashToTest = CryptManager.ComputeHash(saltHash.Concat(passwordHash).ToArray(), 0, saltHash.Length + passwordHash.Length); string hashStringToTest = BitConverter.ToString(hashToTest).Replace("-",""); return criptoKey.Hash == hashStringToTest; }
private static Authority MakeRoot() { DSA dsa = new DSA(new DSAParameters(512)); CryptoKey key = new CryptoKey(dsa); X509Name subject = new X509Name("CN=."); X509Certificate cert = new X509Certificate( 0, subject, subject, key, TimeSpan.FromDays(365)); cert.Sign(key, MessageDigest.DSS1); return new Authority(cert, key); }
/// <summary> /// Builds a KeyData object from a key. /// </summary> /// <param name="CryptoKey"></param> public KeyData(CryptoKey CryptoKey) { }
/// <summary> /// Create a key for a specific encryption mode using a specific key and initialization vector /// </summary> /// <param name="encryptorMode">One of the EncodeModes constants</param> /// <param name="key">Hyrdated key that is valid for this specific encryption mode</param> /// <param name="IV">Hydrated initialization vector that is valid for this specific encryption mode</param> /// <returns>Hydrated key</returns> public static CryptoKey CreateKey(string encryptorMode, byte[] keyBytes, byte[] IVBytes) { CryptoKey key = new CryptoKey(); key.Properties.Add(new CryptoProperty() { Name = Crypto.PropertyNames.EncodeMode, Value = encryptorMode, ValueType = Crypto.PropertyValueTypes.String }); key.Segments[Crypto.SegmentNames.SymmetricKey] = keyBytes; key.Segments[Crypto.SegmentNames.SymmetricIv] = IVBytes; return key; }
/// <summary> /// Create a key using a specific Crypto.HashModesSalted and specific salt. /// </summary> /// <param name="hashMode">One of the Crypto.HashModesSalted constants</param> /// <param name="salt">Non-null salt value to use in hashing operations</param> /// <returns>Newly created key</returns> public static CryptoKey CreateSaltedKey(string hashMode, byte[] salt) { var key = new CryptoKey(); key.Properties.Add(new CryptoProperty() { Name = Crypto.PropertyNames.HashSaltedMode, Value = hashMode, ValueType = Crypto.PropertyValueTypes.String }); key.Segments.Add(Crypto.SegmentNames.HashSalt, salt); return key; }
/// <summary> /// Default constructor /// </summary> public SymmetricEncoder(CryptoKey key):this(key.Properties[Crypto.PropertyNames.EncodeMode].Value,key.Segments[Crypto.SegmentNames.SymmetricKey], key.Segments[Crypto.SegmentNames.SymmetricIv]) { }
/// <summary> /// Default constructor /// </summary> /// <param name="key">Hydrated key containing any required hashing parameters</param> public HashEncoder(CryptoKey key) { _key = key; }
/// <summary> /// Create an instance of a symmetric encoder /// </summary> /// <param name="key">Hydrated key usually generated by one of the CreateKey methods.</param> /// <returns>A new instance of encoder suitable of symmetric key encryption using the provided key parameters</returns> public static SymmetricEncoder Create(CryptoKey key) { return new SymmetricEncoder(key); }
public TrijnDes(CryptoKey rijndaelKey, CryptoKey tripleDesKey, CryptoKey rijndaelKey2) { _rijndael = new Rijndael(rijndaelKey); _tripleDes = new TripleDes(tripleDesKey); _rijndael2 = new Rijndael(rijndaelKey2); }
/// <summary> /// Stores a cryptographic key. /// </summary> /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param> /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param> /// <param name="key">The key to store.</param> /// <exception cref="CryptoKeyCollisionException">Thrown in the event of a conflict with an existing key in the same bucket and with the same handle.</exception> public void StoreKey(string bucket, string handle, CryptoKey key) { }