swift 3 md5 hash string (or equivalent) with only built in security module - md5

I'm looking for a for a way to generate a md5 hash (or equivalent 32 character) string using only the security module in Xcode 8 with Swift 3. In other words a method that does not require CommonCrypto.
I've only found one post that mentions this approach. This post claims this approach is only for OS X (not iOS).
I know md5 is not super secure but I need compatibility with an older site, so assistance would be greatly appreciated.

What is wrong with CommonCrypto? It is already available on every device, simple, fast and well tested:
extension Data {
var hexString: String {
return map { String(format: "%02hhx", $0) }.joined()
}
var md5: Data {
var digest = [Byte](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
self.withUnsafeBytes({
_ = CC_MD5($0, CC_LONG(self.count), &digest)
})
return Data(bytes: digest)
}
}
As far as i know the only other possibility to calculate md5 is to add the algorithm by yourself like the one used in CryptoSwift.

Related

How to use Collections.binarySearch() in a CodenameOne project

I am used to being able to perform a binary search of a sorted list of, say, Strings or Integers, with code along the lines of:
Vector<String> vstr = new Vector<String>();
// etc...
int index = Collections.binarySearch (vstr, "abcd");
I'm not clear on how codenameone handles standard java methods and classes, but it looks like this could be fixed easily if classes like Integer and String (or the codenameone versions of these) implemented the Comparable interface.
Edit: I now see that code along the lines of the following will do the job.
int index = Collections.binarySearch(vstr, "abcd", new Comparator<String>() {
#Override
public int compare(String object1, String object2) {
return object1.compareTo(object2);
}
});
Adding the Comparable interface (to the various primitive "wrappers") would also would also make it easier to use Collections.sort (another very useful method :-))
You can also sort with a comparator but I agree, this is one of the important enhancements we need to provide in the native VM's on the various platforms personally this is my biggest peeve in our current VM.
Can you file an RFE on that and mention it as a comment in the Number issue?
If we are doing that change might as well do both.

App windows 8 hash md5

I need to calculate the md5 of a file saved locally in an windows8 app created in
javascript / html.
I need the md5 to compare it with an online file and see if the two objects are really the same.
What function should I use?
Here's the code I use to hash a string in MD5 using Windows.Security.Cryptography namespace:
var inputBuffer, outputBuffer, toHash, hashed,
hashProvider = Windows.Security.Cryptography.Core.HashAlgorithmProvider.openAlgorithm(Windows.Security.Cryptography.Core.HashAlgorithmNames.md5); // "open" an md5 hash provider
toHash = 'string'; // string to hash
inputBuffer = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(toHash, Windows.Security.Cryptography.BinaryStringEncoding.utf8); // convert string to binary
outputBuffer = hashProvider.hashData(inputBuffer); // hash the binary
hashed = Windows.Security.Cryptography.CryptographicBuffer.encodeToHexString(outputBuffer); // the hashed string
Now, all you need to do is to read the file in (see http://msdn.microsoft.com/en-us/library/windows/apps/hh464978.aspx). If reading the file into a buffer, then you wouldn't need the convertStringToBinary line.
The WinRT API provides SHA functionality in the Windows.Security.Cryptography.Core namespace, specifically through the static method HashAlgorithmProvider.openAlgorithm(Windows.Security.Cryptography.Certificates.HashAlgorithmNames.sha256).
This provides you with a HashAlgorithmProvider class that has methods like hashData.
Fin in this Link is all that's available in winjs in terms of cryptography.
And Here you can find an example on how to implement an MD5 calculator for a string, from there is a good start to make it work for a file.
Hope this helps.

Printing/exporting a public key on AppEngine PyCrypto

Google AppEngine currently uses an old version of PyCrypto.
After making an RSAkey, I can't find any way to export the publickey.
Alas docs for pycrypto 2.01 currently 404. And the .export methods I see in current code don't work on PyCrypto 2.01:
Making the keypair:
rsa_key = RSA.generate(384, random_generator)
Checking methods available:
In [84]: rsa_key.publickey. <tab>
RSAkey.publickey.__call__ RSAkey.publickey.__func__ RSAkey.publickey.__reduce__ RSAkey.publickey.__str__
RSAkey.publickey.__class__ RSAkey.publickey.__get__ RSAkey.publickey.__reduce_ex__ RSAkey.publickey.__subclasshook__
RSAkey.publickey.__cmp__ RSAkey.publickey.__getattribute__ RSAkey.publickey.__repr__ RSAkey.publickey.im_class
RSAkey.publickey.__delattr__ RSAkey.publickey.__hash__ RSAkey.publickey.__self__ RSAkey.publickey.im_func
RSAkey.publickey.__doc__ RSAkey.publickey.__init__ RSAkey.publickey.__setattr__ RSAkey.publickey.im_self
RSAkey.publickey.__format__ RSAkey.publickey.__new__ RSAkey.publickey.__sizeof__
Printing doesn't work.
It should be possible to use the pickle module, provided interoperability is not that important to you.
import pickle
keyout = pickle.dumps(rsa_key)
# Save keyout into a file or a db
[ ... ]
# Retrieve keyin from the same file or db
rsa_key = pickle.loads(keyin)
Just take a look at the code to see:
def generate(bits, randfunc, progress_func=None):
"""generate(bits:int, randfunc:callable, progress_func:callable)
Generate an RSA key of length 'bits', using 'randfunc' to get
random data and 'progress_func', if present, to display
the progress of the key generation.
"""
obj=RSAobj()
# Generate random number from 0 to 7
difference=ord(randfunc(1)) & 7
# Generate the prime factors of n
if progress_func: progress_func('p\n')
obj.p=pubkey.getPrime(bits/2, randfunc)
if progress_func: progress_func('q\n')
obj.q=pubkey.getPrime((bits/2)+difference, randfunc)
obj.n=obj.p*obj.q
# Generate encryption exponent
if progress_func: progress_func('e\n')
obj.e=pubkey.getPrime(17, randfunc)
if progress_func: progress_func('d\n')
obj.d=pubkey.inverse(obj.e, (obj.p-1)*(obj.q-1))
return obj
This site has a good explanation of what each variable means.

Do you expect query string parameter names to be case sensitive?

Silverlight is case sensitive for query string parameters so the following code would return false with "callid=5"
string callId;
if (System.Windows.Browser.HtmlPage.Document.QueryString.TryGetValue("callId", out callId))
{
....
}
Microsoft defends the decision by citing the www.w3.org spec, but I think it leads to a less friendly experience for people trying to link to you, or give a URL over the phone.
Looks like Stackoverflow is case insensitive:
https://stackoverflow.com/search?q=silverlight+bug
https://stackoverflow.com/search?Q=silverlight+bug
I think you should focus on your naming conventions rather than the implementations of standards, making sure to avoid similar field names and mixed case. For example, you can use a convention of words that over the phone can be read out stating "all lowercase" or "all uppercase".
I did this. Don't know if it helps.
var keyName = "";
if (!string.IsNullOrEmpty(keyName = someDictionary.SomeKeys.FirstOrDefault(k => k.ToLowerInvariant() == "size")))
{
var someValue = someDictionary[keyName];
}
Yes, I'm used to it being case sensitive, and therefore have been programming to it for a long time. I know of some people that have implemented methods to do intermediate parsing to convert them all to lowercase, or other things server side, and it really depends on what you are working with specifically.
As for usability, yes it is harder to read. BUT, at the same time a URL over the phone that has a querystring is not easy to give out anyway.
This workaround will not use the power of dictionaries because it will iterate through all keys, but it is likely to be a sufficient work-around for most scenarios.
var keyName = HtmlPage.Document.QueryString.Keys.SingleOrDefault(key => key.Equals("callid", StringComparison.OrdinalIgnoreCase));
string callid;
HtmlPage.Document.QueryString.TryGetValue(keyName, out callid)
You could also transform the whole QueryString dictionary to a new dictionary with a case insensitive comparer if you are having many dictionary lookups.
var insensitiveQueryString = HtmlPage.Document.QueryString.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase);

One line code examples in various languages for MD5

I'm looking for one line code examples in various languages for getting a valid MD5 result (as a string, not a bytehash or what have you). For instance:
PHP:
$token = md5($var1 . $var2);
I found VB especially troublesome to do in one line.
C#:
string hash = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(input, "md5");
VB is virtually the same.
Here it is not using the System.Web namespace:
string hash = Convert.ToBase64String(new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(System.Text.Encoding.UTF8.GetBytes(input)));
Or in readable form:
string hash =
Convert.ToBase64String
(new System.Security.Cryptography.MD5CryptoServiceProvider()
.ComputeHash
(System.Text.Encoding.UTF8.GetBytes
(input)
)
);
There is a kind of universality in how this is to be accomplished. Typically, one defines a routine called md5_in_one_line (or Md5InOneLine) once, and uses it all over the place, just as one would use a library routine.
So for example, once one defines Md5InOneLine in C#, it's an easy one-liner to get the right results.
Python
token = __import__('md5').new(var1 + var2).hexdigest()
or, if md5 is alrady imported:
token = md5.new(var1 + var2).hexdigest()
Thanks to Greg Hewgill
Aren't you really just asking "what languages have std. library support for MD5?" As Justice said, in any language that supports it, it'll just be a function call storing the result in a string variable. Even without built-in support, you could write that function in any language!
Just in case you need VBScript:
download the MD5 class from webdevbros and then with one line:
hash = (new MD5).hash("some value")
Does it really matter if you can do MD5 in one line. If it's that much trouble that you can't do it in VB in 1 line, then write your own function. Then, when you need to do MD5 in VB in one line, just call that function.
If doing it all in 1 line of code is all that important, here is 1 line of VB. that doesn't use the System.Web Namespace.
Dim MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider() : Dim HashBytes() As Byte : Dim MD5Str As String = "" : HashBytes = MD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes("MyString")) : For i As Integer = 0 To HashBytes.Length - 1 : MD5Str &= HashBytes(i).ToString("x").PadLeft(2, "0") : Next
This will hash "MyString" and store the MD5 sum in MD5Str.
Coldfusion has a bunch of hashing algorithms, MD5 is the default.
cfset var md5hashresult = hash("string to hash")

Resources