public CryptoToken( string encryptedToken, EncryptionKey encryptionKey, InitializationVector initializationVector = null ) { _encryptionKey = encryptionKey; if ( !string.IsNullOrEmpty( encryptedToken ) ) { var encryptor = new SymmetricCrypto( _encryptionKey ); string plainTokenText = string.Empty; try { if ( initializationVector != null ) { byte[] encryptedValue = Convert.FromBase64String( encryptedToken ); byte[] encryptedValueAndInitializationVector = encryptedValue.Concat( initializationVector.InitializationVectorBytes ).ToArray(); plainTokenText = encryptor.Decrypt( Convert.ToBase64String( encryptedValueAndInitializationVector ) ); } else { plainTokenText = encryptor.Decrypt( encryptedToken ); } } catch ( CryptographicException ) { _isValid = false; // CryptoException generally indicates the enc key/padding was wrong and that probably means someone (evil) tried to make up a crypto token. } catch ( FormatException ) { _isValid = false; // FormatException indicates that the encrypted string value provided by the user was not a Base64-encoded string } catch ( ArgumentNullException ) { _isValid = false; // ArgumentNullException indicates that something went wrong when trying to read the Cryptographic token likely due to the length being incorrect. } if ( _isValid ) { DictionaryContents = JsonConvert.DeserializeObject<Dictionary<string, string>>( plainTokenText ); if ( DictionaryContents.Keys.Contains( "expirationdate" ) ) { ExpirationDate = new DateTime( Int64.Parse( DictionaryContents["expirationdate"].ToString() ) ); DictionaryContents.Remove( "expirationdate" ); } } } }
public virtual string GetEncryptedToken() { var tokenText = new StringBuilder(); if ( DictionaryContents != null && DictionaryContents.Count > 0 ) { if ( !DictionaryContents.Keys.Contains("expirationdate") ) { DictionaryContents.Add("expirationdate", ExpirationDate.Ticks.ToString()); } tokenText = new StringBuilder( JsonConvert.SerializeObject( DictionaryContents ) ); } var encryptor = new SymmetricCrypto( _encryptionKey ); return encryptor.Encrypt( tokenText.ToString() ); }