How to hash the string by Sha256 from VB.net and Java

เราสามารถ hash ให้เป็นค่าเดียวกัน (แม้จะต่างภาษา) โดยใช้อัลกอลึทึมเดียวกัน และใช้ “logic” ในการ “encode” แบบเดียวกัน จากตัวอย่างใช้ UTF8Encoding

We can hash the String to be same value by using the same algorithm although using different  language (such as  VB.NET and JAVA). The importance is the encoding algorithm. For the example, we used  UTF8Encoding algorithm.

Vb.net

Public Class sha

Public Function hashed(ByVal plainText As String, ByVal salt As String) As String

'Encode by UTF8
Dim pt As New UTF8Encoding
Dim ptBytes() As Byte = pt.GetBytes(plainText)
Dim s As New UTF8Encoding
Dim sBytes() As Byte = s.GetBytes(salt)
'Mix plaintext + salt
'Reserver array to mix plain and salt
Dim ptSBytes() As Byte = New Byte(ptBytes.Length + sBytes.Length - 1) {}
'Copy plaintext bytes to array.
Dim num As Integer

For num = 0 To ptBytes.Length - 1
ptSBytes(num) = ptBytes(num)
Next num

'Copy salt bytes to array.
For num = 0 To sBytes.Length - 1
ptSBytes(ptBytes.Length + num) = sBytes(num)
Next num

Dim hash As HashAlgorithm
'hashing algorithm class.
'hash = New SHA1Managed()
'hash = New SHA384Managed()
'hash = New SHA512Managed()
hash = New SHA256Managed()
' Compute hash

Dim hashBytes As Byte()
hashBytes = hash.ComputeHash(ptSBytes)
' Convert into a base64-encoded string.

Dim hashValue As String
hashValue = Convert.ToBase64String(hashBytes)
hashed = hashValue
End Function
End Class
sha1
ทดสอบ “sha256” จาก “VB.net”

JAVA

import java.security.MessageDigest;
import org.apache.commons.codec.binary.Base64;

public class sha {
        public static String hashed(String text, String salt){
    	try {
    		//Create Byte valiable
    		byte[] textByte ;
    		text = text + salt;
    		textByte = text.getBytes("UTF-8");

    		//Define hash algorithm
    		MessageDigest sha = MessageDigest.getInstance("SHA-256");

			//Hashed pain-text
			textByte = sha.digest(textByte);

			String output;
			output = Base64.encodeBase64String(textByte);

			return output;
		} catch (Exception e ) {
			e.printStackTrace();
			return null;
		}
    }

    //Test function
    public static void main(String args[])
    {
    	//paintext
        final String painText = "p@ssword_12342qweqwe";

        //salt
		final String salt = "p@ssword";

		//hashed
        final String HashedText = sha.hashed(painText, salt);

        System.out.println("Cipher-text : " + painText);
        System.out.println("Hashed : " +  HashedText);
    }
}
ทดสอบ "sha256" จาก JAVA
ทดสอบ “sha256” จาก JAVA

ใส่ความเห็น