Logic for Generating Signature - for SHA-2 Hashing (Java) - sha256

I'm using a specification document for accessing API, and it says that hash is calculated on the signature generated from the following logic:
Signature = (field1 + field2 + field3 + field4 + field5 + field6) + (field7 + field8)
I'm just wondering what does this mean?
So, when I concatenate the fields and hash using sha-256, I'm getting a different hash format than the expected 32 byte; a sample hash has this format:
PajZG3NEUUHgrycwtPKcKkvTdBg/Kkx6OhlULgSV+ko=
as opposed to this example:
c7477242d3901f537387b2b6c61099380634c013a060960a5bf4d87734d54f0e
This is my code:
stringToHash = "field1field2field3field4field5field6field7field8";
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(stringToHash.getBytes(StandardCharsets.UTF_8));
String encoded = Base64.getEncoder().encodeToString(hash);
What could I be missing?

I found out the answer from this link: http://www.mytecbits.com/tools/cryptography/sha2generator
This code does it:
String input = "String to hash";
MessageDigest objSHA = MessageDigest.getInstance("SHA-256");
byte[] bytSHA = objSHA.digest(input.getBytes());
BigInteger intNumber = new BigInteger(1, bytSHA);
String stringHashCode = intNumber.toString(16);
// pad with 0 if the hexa digits are less then 64.
while (stringHashCode.length() < 64) {
stringHashCode = "0" + stringHashCode;
}

Related

.NET Core - StringBuilder - missing character in downloaded file

I export some data to a csv on an angular/.NET Core app
a ; is missing after the first csv field, while the other ; are there
and the instructions used are the same for the other fields
StringBuilder sb = new StringBuilder();
sb.Append("Id; Civility;Name; Email; Phone;");
sb.Append("\r\n");
for (int i = 0; i < partners.Count; i++)
{
Partner p = partners[i];
sb.Append('"' + p.Id + '"' + ';');
sb.Append('"' +(p.Manager.Civility==0?"Mr":"Mme") +'"'+ ';');
sb.Append('"' + p.Manager.FirstName+" "+ p.Manager.LastName + '"' + ';');
...
here is the part that sends it to the web client for download
DateTime localDate = DateTime.Now;
var date = localDate.ToString("MM_dd_yy_HH_mm_ss");
var filename = "Partners_" + date + ".csv";
Response.Headers.Add("x-file-name", filename);
Response.Headers.Add("Access-Control-Expose-Headers", "x-file-name");
return File(Encoding.UTF8.GetBytes(sb.ToString()), "text/csv", filename);
why is the ; missing in the data ?
apparently the quotes are missing too for the id field
thanks for your time on this
This happens because adding up an int with a char yields an int as result.
var x = 'a' + 5;
//yields 102 as 'a' is implicitly cast from char to int, where 'a' holds the value of 97
You can fix it by either converting the int to a string by using ToString() or you can use strings instead of chars e.g.
sb.Append("\"" + p.Id + "\";"); //the " is escaped using \

How can I get the same MD5 hash from both AS3 and VB.NET? Already have code, it doesn't work

I need to generate a hash of a file in VB.NET on a server and send it to an AS3 client for validation against a file on the client. I chose MD5. I am using the builtin VB.NET MD5 hash and the hurlant MD5 hash on AS3. The results are different.
I am looking for a moderately reliable method of verifying the files are the same. Speed is as important as accuracy. I am open to other hashing algorithms which are at least as reliable/secure as MD5.
If there is a solution using what I have that would be great. If there is another way which works, that's OK too.
My VB Code looks like;
Dim baFileData() As Byte = File.ReadAllBytes(HttpContext.Current.Server.MapPath(strFilePath))
Dim strFileHash As String = GetHash(baFileData)
Function GetHash(theInputBytes() As Byte) As String
Using hasher As MD5 = MD5.Create() ' create hash object
' Convert to byte array and get hash
Dim dbytes As Byte() =
hasher.ComputeHash(theInputBytes)
' sb to create string from bytes
Dim sBuilder As New StringBuilder()
' convert byte data to hex string
For n As Integer = 0 To dbytes.Length - 1
sBuilder.Append(dbytes(n).ToString("X2"))
Next n
Return sBuilder.ToString()
End Using
End Function
My AS3 code looks like this;
private function getFileMD5Hash(flLocalFile:File):String
{
var strmInFile:FileStream = new FileStream();
strmInFile.open(flLocalFile, FileMode.READ);
var strFileData:String = strmInFile.readUTFBytes(strmInFile.bytesAvailable);
strmInFile.close();
var hash:IHash = Crypto.getHash("md5");
var baFileData:ByteArray = Hex.toArray(Hex.fromString(strFileData));
var baHash:ByteArray = hash.hash(baFileData);
var strFileHash:String = Hex.fromArray(baHash);
return strFileHash;
}
#Organis basically gave me the tools in his comments to solve the problem. My only reason for posting this as an answer is to show what the resulting code looks like.
If Organis posts an answer I will give it a vote.
The VB code remained the same.
The AS3 code changed to;
private function getFileMD5Hash(flLocalFile:File):String
{
var strmInFile:FileStream = new FileStream();
strmInFile.open(flLocalFile, FileMode.READ);
var baFileData:ByteArray = new ByteArray;
strmInFile.readBytes(baFileData);
strmInFile.close();
var hash:IHash = Crypto.getHash("md5");
var baHash:ByteArray = hash.hash(baFileData);
var strFileHash:String = Hex.fromArray(baHash).toUpperCase();
return strFileHash;
}

Hive UDF return expected result but also added null and newline in result

I have written Hive UDF in Java for decoding the information, for that we used the below code.
public Text evaluate(Text str) throws Exception {
byte[] keyBytes = (SALT + KEY).getBytes("UTF8");
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
keyBytes = messageDigest.digest(keyBytes);
keyBytes = java.util.Arrays.copyOf(keyBytes, 16);
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
String decryptedString = Base64.encodeBase64String(cipher.doFinal(str.getBytes()));
return new Text(decryptedString);
}
The below query is executed successfully with UDF.
below is the Gender table where I'm executing the UDF
When I execute the query on the gender table with UDF, I'm getting the null and new line in it. Please find the below screenshot with highlighted areas.
I'm expecting the result in one line only. Please help and let me know where I'm wrong.

Kotlin: how to swap character in String

I would like to swap a string from "abcde" to "bcdea". So I wrote my code as below in Kotlin
var prevResult = "abcde"
var tmp = prevResult[0]
for (i in 0..prevResult.length - 2) {
prevResult[i] = prevResult[i+1] // Error on preveResult[i]
}
prevResult[prevResult.length-1] = tmp // Error on preveResult[prevResult.lengt-1]
It errors out as stated above comment line. What did I do wrong? How could I fix this and get what I want?
Strings in Kotlin just like in Java are immutable, so there is no string.set(index, value) (which is what string[index] = value is equivalent to).
To build a string from pieces you could use a StringBuilder, construct a CharSequence and use joinToString, operate on a plain array (char[]) or do result = result + nextCharacter (creates a new String each time -- this is the most expensive way).
Here's how you could do this with StringBuilder:
var prevResult = "abcde"
var tmp = prevResult[0]
var builder = StringBuilder()
for (i in 0..prevResult.length - 2) {
builder.append(prevResult[i+1])
}
builder.append(tmp) // Don't really need tmp, use prevResult[0] instead.
var result = builder.toString()
However, a much simpler way to achieve your goal ("bcdea" from "abcde") is to just "move" one character:
var result = prevResult.substring(1) + prevResult[0]
or using the Sequence methods:
var result = prevResult.drop(1) + prevResult.take(1)
You can use drop(1) and first() (or take(1)) to do it in one line:
val str = "abcde"
val r1 = str.drop(1) + str.first()
val r2 = str.drop(1) + str.take(1)
As to your code, Kotlin String is immutable and you cannot modify its characters. To achieve what you want, you can convert a String to CharArray, modify it and then make a new String of it:
val r1 = str.toCharArray().let {
for (i in 0..it.lastIndex - 1)
it[i] = it[i+1]
it[it.lastIndex] = str[0] // str is unchanged
String(it)
}
(let is used for conciseness to avoid creating more variables)
Also, you can write a more general version of this operation as an extension function for String:
fun String.rotate(n: Int) = drop(n % length) + take(n % length)
Usage:
val str = "abcde"
val r1 = str.rotate(1)
Simpler solution: Just use toMutableList() to create a MutableList of Char and then join it all together with joinToString.
Example:
Given a String input, we want to exchange characters at positions posA and posB:
val chars = input.toMutableList()
val temp = chars[posA]
chars[posA] = chars[posB]
chars[posB] = temp
return chars.joinToString(separator = "")
Since Strings are immutable, you will have to copy the source string into an array, make changes to the array, then create a new string from the modified array. Look into:
getChars() to copy the string chars into an array.
Perform your algorithm on that array, making changes to it as needed.
Convert the modified array back into a String with String(char[]).

[Sql-Server]what data type to use for password salt and hash values and what length?

I am generating salt and hash values from my passwords by using,
string salt = CreateSalt(TxtPassword.Text.Length);
string hash = CreatePasswordHash(TxtPassword.Text, salt);
private static string CreateSalt(int size)
{
//Generate a cryptographic random number.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);
// Return a Base64 string representation of the random number.
return Convert.ToBase64String(buff);
}
private static string CreatePasswordHash(string pwd, string salt)
{
string saltAndPwd = String.Concat(pwd, salt);
string hashedPwd =
FormsAuthentication.HashPasswordForStoringInConfigFile(
saltAndPwd, "sha1");
return hashedPwd;
}
What datatype you would suggest for storing these values in sql server? Any suggestion...
Salt:9GsPWpFD
Hash:E778AF0DC5F2953A00B35B35D80F6262CDBB8567
ASPNET_DB says this - can't go wrong.
Password nvarchar(128) NOT NULL,
PasswordSalt nvarchar(128) NOT NULL,
while 128 may seem like a lot, various types of encryption can result in larger strings than you started out with. There is absolutely no reason not to follow the lead of the very smart people who have spend thousands of man hours developing the asp.net membership system.
We store our passwords as a binary SHA512 hash