One line code examples in various languages for MD5 - 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")

Related

Returning the filename of the current sketch

I am trying to write a GUI that will display the name of the sketch it was generated from using a simple text() command. However, I am running into trouble getting any of the general JS solutions to work for me. Many solutions I have found use the filename reserved word but that does not seem to be reserved in Processing 3.5.4. I have also tried parsing the strings using a similar method to what can be found here. I am very new to processing and this is only my 2nd attempt at using Processing.
Any advice would be greatly appreciated
You can get the path (as a string) to the sketch with sketchPath().
From there you could either parse the string (pull off everything after the last slash) to get the sketch name, or you can use sketchFile() to get a reference to the file itself and get the name from there:
String path = sketchPath();
File file = sketchFile(path);
String sketchName = file.getName();
println(sketchName);
You could combine this all into one line like so:
String sketchName = sketchFile(sketchPath()).getName();

How to convert ASCII integers to string in Streambase?

I am using streambase, and have created a map to convert incoming integers (0-255) into character codes. Right now, I'm using manual if/else statements. For example:
if (message_code == '106') then
message_code = 'J'
else if (message_code == '110') then
message_code= 'N'
However, I'd like to just use this more generally. Searching Streambase Studio help didn't really provide anything as far as I could tell. I know this can be done in Java, but would probably require calling a java external function. I'm not so competent at this, so am a bit lost.
Is there a better way to do this in StreamBase?
Initial investigations confirm that the StreamBase Expression Language or built-in Functions don't have an obvious way to convert ints representing ASCII character values into a one-character string corresponding to the ASCII value. If there's some non-obvious trick I discover later, I'll come back and edit this answer.
I definitely wouldn't use a 255-clause if/then/else expression!
I would probably use a Java function and here is an example I've lightly tested:
package example;
public class ASCIIIntToString {
public static String ASCIIToString(Integer a) {
if (a == null || a < 0 || a > 255) {
return null;
} else {
return Character.toString((char) (int) a);
}
}
}
And the custom-function declaration to drop into your sbd.sbconf would look like this:
<custom-functions>
<custom-function alias="ASCIIToString"
args="auto"
class="example.ASCIIIntToString"
language="java"
name="ASCIIToString"
type="simple"/>
</custom-functions>
But if you would rather not drop into Java and stay in EventFlow then two methods come to mind:
Load a CSV file with int -> string mappings in them into a Query Table and dto a lookup with Query Read operator, perhaps using the Initial Contents tab to reference the CSV file since ASCII isn't going to change anytime soon.
Create a list constant called, say, ASCII, that has all the strings you want to convert to and index the list by the int. For example, in a Map operator do Add c ASCII[i], and add some bounds checking logic (perhaps in a user function).
Disclosure/Disclaimer: I am an employee of TIBCO Software, Inc. Opinions expressed here are my own and not TIBCO's.

swift sort characters in a string

How to sort characters in a string e.g. "5121" -> "1125" ?
I can do this with code below but it seems too slow:
var nonSortedString = "5121"
var sortedString = String(Array(nonSortedString.characters).sort())
The CharacterView handles properly compound characters and provides proper ordering ("eěf" vs. "efě"). If you are ok with the way C++ handles unicode characters, try using one of the other views, like nonSortedString.utf16.sort(). It should give speed similar to C++.

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.

How is md5Hash calculated for com.google.appengine.api.blobstore.BlobInfo

We're trying to avoid saving duplicate files. However, our md5 result is always different from BlobInfo.
How we calculate it:
MessageDigest messageDigest = java.security.MessageDigest.getInstance("MD5");
digest = messageDigest.digest(bytes);
String digestString = DigestUtils.md5Hex(digest);
It doesn't match:with (new BlobInfoFactory().loadBlobInfo(blobKey)).getMd5Hash();
Example mismatches:
google vs my own calculation:
8cdeb6db94bc4fd156e2975fd8ebbcf2 vs 9003b37afbf3637de96c35774069453f
65a25dafcba58d16d58a9c7585cc3932 vs 52383159f7d27417d50121aaee2728b5
5cccc2d690fdc0c254234d5526876b34 vs 8196da9b6733daa60e08d927693df483
It is on production server. ( we didn't test dev environment )
Sebastian Kreft is right in the above discussion in comments.
The code I copied is wrong. it should just be:
String digestString = DigestUtils.md5Hex(bytes);
Sebastian Kreft used the trick to verify empty file's md5 which should always be d41d8cd98f00b204e9800998ecf8427e!

Resources