|
Posted
almost 14 years
ago
by
JaCraig
Hey, a couple of things:
1) I use the MIT license in the code because I want people to modify it. I want people to be able to pull parts out, make modifications, slap it into their code base, etc. I mean don't copy it verbatim and call it your own
... [More]
, but I'm all for people using it however they want (and if people happen to pimp out my library, putting a link to the repository, then so much the better). Heck, I even accept pull requests/patches (you know, the few that I've received).
2) I don't do much Silverlight work. Actually, I don't do it at all. I do some WPF from time to time, but no SL. So you may run into parts of the library that will not work. I don't know what parts those might be though.
3) PasswordDeriveBytes, when I initially wrote the code that become what's actually in the library wasn't deprecated at the time. And, even though I'm pretty open to introducing breaking changes if it results in better code, I try not to do anything that will abandon legacy data. And if you run the app below:
static void Main(string[] args)
{
using (Rfc2898DeriveBytes Bytes1 = new Rfc2898DeriveBytes("Password", new byte[] { 1, 2, 3, 4, 5,6,7,8 }, 2))
{
using (PasswordDeriveBytes Bytes2 = new PasswordDeriveBytes("Password", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, "SHA1", 2))
{
foreach (byte x in Bytes1.GetBytes(32))
{
Console.Write((char)x);
}
Console.WriteLine();
foreach (byte x in Bytes2.GetBytes(32))
{
Console.Write((char)x);
}
Console.WriteLine();
Console.ReadLine();
}
}
}
You'll notice that the keys generated are vastly different. Different keys means different encrypted data that gets spit out, which means that anything that was encrypted using the old code wouldn't work with the new code. Then I get irate emails. I try to avoid that. But I do have an idea that might be able to accommodate "upgrading" someone's code as the Rfc2898DeriveBytes uses PBKDF2, which is a bit more secure...
4) As far as I know, none of the SymmetricAlgorithm items in .Net will produce encrypted data that is shorter than original string. That being said, it's probably a good idea, just in case. However, to make my life easier, I'm just going to write a couple of Stream extensions to handle this for me (ReadAll and ReadAllBinary). So the code is going to be a little different from the above, but should still solve the problem when I check it in. [Less]
|
|
Posted
almost 14 years
ago
by
Lyle
Here is an example what your function would look like updated.
public static byte[] Decrypt(this byte[] Data, string Key, SymmetricAlgorithm AlgorithmUsing = null, string Salt = "Kosher",
string
... [More]
HashAlgorithm = "SHA1", int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY", int KeySize = 256)
{
if (Data.IsNull())
return null;
AlgorithmUsing = AlgorithmUsing.NullCheck(new RijndaelManaged());
Key.ThrowIfNullOrEmpty("Key");
Salt.ThrowIfNullOrEmpty("Salt");
HashAlgorithm.ThrowIfNullOrEmpty("HashAlgorithm");
InitialVector.ThrowIfNullOrEmpty("InitialVector");
using (PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Key, Salt.ToByteArray(), HashAlgorithm, PasswordIterations))
{
using (SymmetricAlgorithm SymmetricKey = AlgorithmUsing)
{
SymmetricKey.Mode = CipherMode.CBC;
byte[] PlainTextBytes = null;
byte[] Buffer = new byte[4096];
int ByteCount = 0;
using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(DerivedPassword.GetBytes(KeySize / 8), InitialVector.ToByteArray()))
{
using (MemoryStream MemStream = new MemoryStream(Data))
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
{
using (MemoryStream Decrypted = new MemoryStream())
{
while ((ByteCount = CryptoStream.Read(Buffer, 0, Buffer.Length)) > 0)
{
Decrypted.Write(Buffer, 0, ByteCount);
}
CryptoStream.Close();
PlainTextBytes = Decrypted.ToArray();
Decrypted.Close();
}
}
MemStream.Close();
}
}
SymmetricKey.Clear();
return PlainTextBytes;
}
}
}
[Less]
|
|
Posted
almost 14 years
ago
by
Lyle
Hi, First off thanks for this awesome library. I'm learning a ton of stuff from it.
I was working with your Decrypt function in Utilities.Encryption.ExtensionMethods.SymmetricExtensions
I could be wrong here but I believe that your function
... [More]
will not always work.
1.) When you initialize the PlainTextBytes Byte[] you are initializing the size of the array to the length of the encrypted data. so what if the unencrypted data is larger than the encrypted data?
Could this solution work better? I changed my function to use Rfc289DeriveBytes instead of PasswordDeriveBytes that your using because I'm using Silverlight which does not have it. And It's depricated in the MSDN Docs. I hope you don't mind I'm chaning your
code around. I still have the disclaimer In place and am learning so much from your code. Thanks again. Anyways below you could convert your code to use the buffer, length, and decrypted memory stream variables when reading in (decrypting) data from
the cryptostream
I don't know if this is the right place to post this. I couldn't find a contact page on your site. Again this is just a suggestion and thank you so much for this awesome library!
Byte[]
bytes =
null;
Byte[] buffer =
new Byte[4096];
Int32 length = 0;
Rfc2898DeriveBytes derivedBytes =
new Rfc2898DeriveBytes(key, salt.ToByteArray(), iterations);
using (symmetricAlgorithm = symmetricAlgorithm.NullCheck(new AesManaged()))
{
symmetricAlgorithm.KeySize = keySize;
symmetricAlgorithm.BlockSize = blockSize;
symmetricAlgorithm.Key = derivedBytes.GetBytes(symmetricAlgorithm.KeySize / 8);
symmetricAlgorithm.IV = derivedBytes.GetBytes(symmetricAlgorithm.BlockSize / 8);
using (ICryptoTransform cryptoTransform = symmetricAlgorithm.CreateDecryptor())
{
using (MemoryStream memoryStream =
new MemoryStream(data))
{
using (CryptoStream cryptoStream =
new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read))
{
using (MemoryStream decrypted =
new MemoryStream())
{
while ((length = cryptoStream.Read(buffer, 0, buffer.Length)) > 0)
{
decrypted.Write(buffer, 0, length);
}
cryptoStream.Close();
bytes = decrypted.ToArray();
}
}
}
}
}
return bytes;
[Less]
|
|
Posted
almost 14 years
ago
by
James Craig
Updating nuspec files to show the latest version. Also changed the csproj files to generate the xml documentation (for those that want it).
|
|
Posted
almost 14 years
ago
by
JaCraig
List of FeaturesProject DescriptionCraig's Utility Library (or CUL, as in cull because I'm not that creative), was initially designed through a number of projects that I've worked on. Over time I assembled a number of classes to handle various tasks
... [More]
and continue to add a number of items in my spare time. The library is written in C# and uses .Net 4.0 but many of the classes are usable in lower versions. More code can be found on my website: http://www.gutgames.com.For a list of features, take a look at the List of Features page. In this latest update, I got bored and started looking at Ruby and Python for ideas (I've used Python for scripting in the past and Ruby in a couple of just hacked together fun projects). Basically I took a bunch of their built in functions and classes and built a number of C# equivalents. I plan on doing this with other languages in the future, so if you have any suggestions of languages or standard libraries to look at, let me know.Source Code RepositoryThe repository here is Mercurial. Also note that there are repository mirrors available on Bitbucket and Github: Bitbucket and GitHub repositories. I'll be updating all three with changes as I make them. [Less]
|
|
Posted
almost 14 years
ago
by
JaCraig
Craig's Utility Library is one of the largest collections of extension methods and various helper classes out there. It has gotten to the point where if you can think it, it's probably already in there (and if not, put a message on the Issue Tracker
... [More]
and I'll add it when I get bored, which is often). So how much is in there, well let's start with the extension methods:Utilities.DataTypes.ExtensionMethods
Array extensions
Clear
Combine
DateTime extensions
DaysInMonth
DaysLeftInMonth
DaysLeftInYear
FirstDayOfMonth
FirstDayOfWeek
FromUnixTime (actually extension for int and long values)
IsInFuture
IsInPast
IsWeekDay
IsWeekEnd
LastDayOfMonth
LastDayOfWeek
ToUnix
FirstDayOfQuarter
FirstDayOfYear
LastDayOfQuarter
LastDayOfYear
ConvertToTimeZone (assumes that times are in UTC time)
LocalTimeZone
AddWeeks
Age
BeginningOfDay
EndOfDay
IsToday
SetTime
UTCOffset
Generic object extensions
If
NotIf
Return
Chain
Do
Execute
ThrowIfTrue
ThrowIfFalse
ICollection extensions
AddAndReturn
AddRange
AddIf
AddIfUnique
Remove
RemoveRange
IComparable extensions
Between
IDictionary extensions
Sort
SortByValue
IEnumerable extensions
Exists
For
ForEach
ForParallel
ForEachParallel
IsNullOrEmpty
RemoveDefaults
ToArray
ToString
TrueForAll
TryAll
TryAllParallel
FalseForAll
FalseForAny
TrueForAll
TrueForAny
ThrowIfFalseForAll
ThrowIfFalseForAny
ThrowIfTrueForAll
ThrowIfTrueForAny
ElementsBetween
First
Last
ToDataTable
ToCSV
ToDelimitedFile
MatchCollection extensions
Where
string extensions
Encode
FromBase64
Left
Right
ToBase64
ToByteArray
ToFirstCharacterUpperCase
ToSentenceCapitalize
ToTitleCase
NumberTimesOccurs
Reverse
FilterOutText
KeepFilterText
AlphaNumericOnly
AlphaCharactersOnly
NumericOnly
IsUnicode
FormatString
RegexFormat
ExpandTabs
StripLeft
StripRight
Pluralize
Singularize
Center
MaskLeft
MaskRight
UrlDecode
UrlEncode
Various type conversion/type checking extensions
FormatToString
IsNotDefault
IsDefault
IsNotNull
IsNull
IsNotNullOrDBNull
IsNullOrDBNull
NullCheck
ThrowIfDefault
ThrowIfNullOrEmpty
ThrowIfNullOrDBNull
ToSQLDbType
ToDbType
ToType
TryTo
Various value type extensions
ToBool (int)
ToInt (bool)
ToBase64String (byte array)
ToEncodedString (byte array)
IsUnicode (byte array)
TimeSpan Extensions
Years
Months
DaysRemainder
DataTable Extensions
ToList
ToCSV
ToDelimitedFile
Utilities.Math.ExtensionMethods
Math extensions
Between
Clamp
Factorial
Max
Median
Min
Mode
Pow
Round
StandardDeviation
Sqrt
Variance
Permute
Utilities.SQL.ExtensionMethods
DbCommand extensions
AddParameter
BeginTransaction
ClearParameters
Close
Commit
ExecuteDataSet
ExecuteScalar
GetOutputParameter
Open
Rollback
DbDataReader extensions
GetParameter
Utilities.Compression.ExtensionMethods
Compress (both byte arrays and strings)
Decompress (both byte arrays and strings)
Utilities.Encryption.ExtensionMethods
Hash (Now handles all hash algorithms in one function for both byte arrays and strings)
Encrypt (Handles any symmetric encryption algorithm inside .Net)
Decrypt (Handles any symmetric encryption algorithm inside .Net)
Utilities.IO.ExtensionMethods
DirectoryInfo extensions
CopyTo
DeleteAll
DeleteFiles
DeleteFilesNewerThan
DeleteFilesOlderThan
Size
SetAttribute
DriveInfo
DeleteDirectoriesNewerThan
DeleteDirectoriesOlderThan
FileInfo extensions
Append
CompareTo
Read
ReadBinary
Save
SaveAsync
SetAttributes
DriveInfo
Execute
String extensions
RemoveIllegalDirectoryNameCharacters
RemoveIllegalFileNameCharacters
Serialization extensions
ToBinary
ToJSON
ToSOAP
ToXML
ToObject
JSONToObject
SOAPToObject
XMLToObject
Uri extensions
Read
ReadBinary
Execute
Utilities.Web.ExtensionMethods
Web related extensions
AbsoluteRoot
AddScriptFile
ContainsHTML
HTTPCompress
IsEncodingAccepted
RelativeRoot
RemoveURLIllegalCharacters
SetEncoding
StripHTML
IPAddress extensions
GetHostName
Minification
Combine (can be used for HTML,JavaScript, or CSS)
Minify (can be used for HTML, JavaScript, or CSS)
HttpRequest extensions
IsMobile
Utilities.Image.ExtensionMethods
All Bitmap functions were moved
Added ToBase64 extension method
Added DrawRoundedRectangle extension
Screen extensions
TakeScreenShot
Utilities.Error.ExtensionMethods
Various error related extensions
DumpApplicationState
DumpCache
DumpCookies
DumpRequestVariable
DumpResponseVariable
DumpServerVars
DumpSession
Utilities.Reflection.ExtensionMethods
Various reflection related extensions
CallMethod
CreateInstance
DumpProperties
GetAttribute
GetAttributes
GetName
GetObjects
GetProperty
GetPropertyGetter
GetPropertyName
GetPropertyType
GetPropertySetter
GetTypes
IsIEnumerable
IsOfType
Load
LoadAssemblies
MarkedWith
MakeShallowCopy
SetProperty
ToLongVersionString
ToShortVersionString
Utilities.Environment.ExtensionMethods
Process related extensions
KillProcessAsync
GetInformation
On top of that there are a number of helper classes for a number of various tasks including (note that there are actually more, this is what I can remember off the top of my head):
Email
Pop3 client (SSL capable)
MIME parser
SMTP email sending (SSL capable)
Exchange inbox email retrieval
Image manipulation (one of the larger collections of functions dealing in image manipulation out there)
Most image functions are multithreaded and thus act extremely quickly.
Cropping, resizing, rotating, flipping
To black and white or sepia tone
Threshold and edge detection (including Sobel and Laplace)
Text drawing, watermarks, object drawing helpers
Taking a screenshot which spans monitors
RGB Histograms
Various convolution filters such as sharpen, sobel emboss, etc. along with the ability to create your own easily.
Various other filters such as "jitter", pixelate, sin wave, median filter, and dilation, red/green/blue filters,
Multiple blurring techniques including box blur, Gaussian blur, Kuwahara, and Symmetric Nearest Neighbor blur
Bump map and Normal map helpers
ASCII art generator
Adjust brightness, gamma, and contrast
Active Directory querying
Includes functions for active users, all users, all groups, active members in groups, etc.
Exchange querying
Free/Busy data
Get next/previous available time for appointments
Get contacts
Get appointments/events
Get emails
Get the GAL
SQL query helper (which includes bulk copying functionality)
MicroORM
ORM (which includes lazy loading, etc.)
SQL Server structural analysis helpers
File formats/Microformats
XMDP
RSS (with iTunes/Zune information embedded for podcasts)
vCard/hCard
vCalendar/hCalendar
iCalendar (with email sending capabilities, cancellation, and automatically putting it in Exchange)
APML
OPML
XFN
CSV (really any delimited file) with functions to convert it to a list of objects or a DataTable
RSD
BlogML
INI
Cisco phone app helpers
WMI query helpers
Code to render a web page to BMP file
Icon extraction from a file
WebBrowser control cache clearing class
Helper classes for simplifying System.Reflection.Emit namespace
Randomization
Including string randomization based on allowable characters, date randomization, Color, Enum, TimeSpan, and Lorem Ipsum generation.
Includes thread safe randomization function.
Environment information
Process management
Error/Information gathering
Math related classes
Matrix
Vector3
Set
Factorial
Permutation
Data types
Vector
Bag
List
ListMapping
Priority Queue
BTree
DateSpan
Base classes for various patterns including
Singleton
Factory
OAuth helper class
Code for setting up an OpenID relay
REST helper class
Classes to help with various media services/websites including
Twitter
Hulu
Netflix
Craigslist
eBay
Naive Bayes classifier
Validation classes
Caching helper classes
Logging helper classes
Configuration helper classes
AOP helper classes
On top of that I add new code, bug fixes, etc. quite frequently through the code repository. [Less]
|
|
Posted
almost 14 years
ago
by
This update adds about 60 new extension methods, a couple of new classes, and a number of fixes including:
Additions
Added DateSpan class Added GenericDelimited class Random additions
Added static thread friendly version of Random.Next
... [More]
called ThreadSafeNext.
AOP Manager additions
Added Destroy function to AOPManager (clears out all data so system can be recreated. Really only useful for testing...)
ORM additions
Added PagedCommand and PageCount functions to ObjectBaseClass (same as MicroORM).
In ORM added PagedCommand and PageCount functions (same as MicroORM). Added Paged/PageCount functions to ObjectBaseClass. Added PageCount function to ORM Session (forgot about it earlier until, of course, I needed it).
Added Setup function to ORM code to allow defining/setting up mappings (and derived types) at start instead of creating them on the fly.
Added Destroy function to ORM (clears out all data so system can be recreated. Really only useful for testing...)
MicroORM additions
Added ClearAllMappings function to MicroORM (clears out all mappings from the system, so it can be recreated. Really only useful for testing...)
Delimited file additions
Added Parse function, ToDataTable, and ToFile functions to base class
SQLHelper additions
Added ExecuteBulkCopy
Object Extensions
ThrowIfTrue ThrowIfFalse TryTo (converts the type, but still returns it as an object. Good for converting string to int, int to float, etc. but still need it as an object for whatever reason)
IEnumerable Extensions
FalseForAll FalseForAny TrueForAll TrueForAny ThrowIfFalseForAll ThrowIfFalseForAny ThrowIfTrueForAll ThrowIfTrueForAny ElementsBetween First Last ToDataTable ToCSV ToDelimitedFile
string Extensions
ExpandTabs StripLeft StripRight Pluralize Singularize Center MaskLeft MaskRight UrlDecode UrlEncode
FileInfo Extensions
DriveInfo Execute
DirectoryInfo Extensions
DriveInfo DeleteDirectoriesNewerThan DeleteDirectoriesOlderThan
DateTime Extensions
FirstDayOfQuarter FirstDayOfYear LastDayOfQuarter LastDayOfYear ConvertToTimeZone (assumes that times are in UTC time) LocalTimeZone AddWeeks Age BeginningOfDay EndOfDay IsToday SetTime UTCOffset
Uri Extensions
Execute (opens a URL in the default browser)
DataTable Extensions
ToList ToCSV ToDelimitedFile
TimeSpan Extensions
Years Months DaysRemainder
Fixes/Updates
Modified TrueForAll to accept more than one Predicate. Changed ThrowIfDefault, ThrowIfNull, ThrowIfNullOrDBNull, and ThrowIfNullOrEmpty to return the original value instead of being void.
Fixed Remove and RemoveRange so that they would work with fixed length collections, arrays, etc. (Note that the collection is no longer directly changed, the returned value is now the collection minus the removed items)
Changed SQLHelper methods that were returning void. They now return the SQLHelper object (basically allowing for a more fluent interface).
Added PageCount and PagedCommand functions for MicroORM. These functions take an SQL command to determine the data to return (you can't have an order by clause, but this allows a lot more freedom when coming up with what to return).
Changed StopWatch class to actually use System.Diagnostics.Stopwatch class for greater precision when timing. (May remove this class in the future)
Switched Save function on ObjectBaseClass to take an IEnumerable instead of a list of objects.
Fixed issues in ORM when an item contains a ManyToMany or ManyToOne mapping that is the same type (for instance class A contains a list of type A).
Fixed issue in ORM where if string mapping is declared MAX by entering -1 (no longer limits the text in that field to 100 characters).
Fixed bug in ORM code so that Readable and Writable fields on the database are respected.
Plus a lot more.
[Less]
|
|
Posted
almost 14 years
ago
by
JaCraig
This update adds about 60 new extension methods, a couple of new classes, and a number of fixes including:Additions
Added DateSpan class
Added GenericDelimited class
Random additions
Added static thread friendly version of Random.Next called
... [More]
ThreadSafeNext.
AOP Manager additions
Added Destroy function to AOPManager (clears out all data so system can be recreated. Really only useful for testing...)
ORM additions
Added PagedCommand and PageCount functions to ObjectBaseClass (same as MicroORM).
In ORM added PagedCommand and PageCount functions (same as MicroORM).
Added Paged/PageCount functions to ObjectBaseClass.
Added PageCount function to ORM Session (forgot about it earlier until, of course, I needed it).
Added Setup function to ORM code to allow defining/setting up mappings (and derived types) at start instead of creating them on the fly.
Added Destroy function to ORM (clears out all data so system can be recreated. Really only useful for testing...)
MicroORM additions
Added ClearAllMappings function to MicroORM (clears out all mappings from the system, so it can be recreated. Really only useful for testing...)
Delimited file additions
Added Parse function, ToDataTable, and ToFile functions to base class
SQLHelper additions
Added ExecuteBulkCopy
Object Extensions
ThrowIfTrue
ThrowIfFalse
TryTo (converts the type, but still returns it as an object. Good for converting string to int, int to float, etc. but still need it as an object for whatever reason)
IEnumerable Extensions
FalseForAll
FalseForAny
TrueForAll
TrueForAny
ThrowIfFalseForAll
ThrowIfFalseForAny
ThrowIfTrueForAll
ThrowIfTrueForAny
ElementsBetween
First
Last
ToDataTable
ToCSV
ToDelimitedFile
string Extensions
ExpandTabs
StripLeft
StripRight
Pluralize
Singularize
Center
MaskLeft
MaskRight
UrlDecode
UrlEncode
FileInfo Extensions
DriveInfo
Execute
DirectoryInfo Extensions
DriveInfo
DeleteDirectoriesNewerThan
DeleteDirectoriesOlderThan
DateTime Extensions
FirstDayOfQuarter
FirstDayOfYear
LastDayOfQuarter
LastDayOfYear
ConvertToTimeZone (assumes that times are in UTC time)
LocalTimeZone
AddWeeks
Age
BeginningOfDay
EndOfDay
IsToday
SetTime
UTCOffset
Uri Extensions
Execute (opens a URL in the default browser)
DataTable Extensions
ToList
ToCSV
ToDelimitedFile
TimeSpan Extensions
Years
Months
DaysRemainder
Fixes/Updates
Modified TrueForAll to accept more than one Predicate.
Changed ThrowIfDefault, ThrowIfNull, ThrowIfNullOrDBNull, and ThrowIfNullOrEmpty to return the original value instead of being void.
Fixed Remove and RemoveRange so that they would work with fixed length collections, arrays, etc. (Note that the collection is no longer directly changed, the returned value is now the collection minus the removed items)
Changed SQLHelper methods that were returning void. They now return the SQLHelper object (basically allowing for a more fluent interface).
Added PageCount and PagedCommand functions for MicroORM. These functions take an SQL command to determine the data to return (you can't have an order by clause, but this allows a lot more freedom when coming up with what to return).
Changed StopWatch class to actually use System.Diagnostics.Stopwatch class for greater precision when timing. (May remove this class in the future)
Switched Save function on ObjectBaseClass to take an IEnumerable instead of a list of objects.
Fixed issues in ORM when an item contains a ManyToMany or ManyToOne mapping that is the same type (for instance class A contains a list of type A).
Fixed issue in ORM where if string mapping is declared MAX by entering -1 (no longer limits the text in that field to 100 characters).
Fixed bug in ORM code so that Readable and Writable fields on the database are respected.
Plus a lot more. [Less]
|
|
Posted
almost 14 years
ago
by
James Craig
1) Added ThrowIfTrue and ThrowIfFalse extensions to all objects
2) Added FalseForAll, FalseForAny, TrueForAll, TrueForAny, ThrowIfFalseForAll, ThrowIfFalseForAny, ThrowIfTrueForAll, and ThrowIfTrueForAny extensions to IEnumerable.
3) Modified
... [More]
TrueForAll to accept more than one Predicate.
4) Added ExpandTabs, StripLeft, and StripRight extensions to string.
5) Changed ThrowIfDefault, ThrowIfNull, ThrowIfNullOrDBNull, and ThrowIfNullOrEmpty to return the original value instead of being void.
6) Added DriveInfo extension to DirectoryInfo and FileInfo. [Less]
|
|
Posted
almost 14 years
ago
by
James Craig
1) Added FirstDayOfQuarter, FirstDayOfYear, LastDayOfQuarter, LastDayOfYear extensions to DateTime.
2) Added Pluralize and Singularize extensions to String.
|