Mixing : SHA dan MD5, plus Salt
Sekarang gimana melakukan enkripsi satu arah (oneway encryption) namun mengkolaborasikan 2 methode, yaitu SHA dan MD5 , mungkin cara ini rada gak lazim, soalnya gak boleh melakukan enkripsi berganda, salah-salah malah kembali keliatan aselinya .. ha ha ha.
Sebelumnya code2 di atas berupa Java, namun yang ini dicoba dalam .NET. Silakan menyimak.
———–
prinsipnya kira:
Encrypting
1. Generate a Random “Salt” Value
2. Merge the string (after encode by SHA) to encrypt with the “Salt”
3. MD5 the merged string
4. Save the MD5 Hash in one location and the Salt in another, usually a separate “Table” in your DBMS (Database Management System)
Testing
1. Locate the saved “Salt”
2. Merge the string( after encode by SHA) and the saved “Salt”
3. MD5 the
4. Test the new MD5 hash against the saved, if a match is found allow usage to whatever you were protecting.
————-
Private Shared EncStringBytes() As Byte
Private Shared Encoder As New UTF8Encoding
Private Shared MD5Hasher As New MD5CryptoServiceProvider
Private Shared objSync As New Object
’Encrptes the string in MD5 when passed as a string
Public Function Encrypt(ByVal EncString As String) As String
’Variable Declarations
Dim RanGen As New Random
Dim RanString As String = “”
Dim MD5String As String
Dim RanSaltLoc As String
’Generates a Random number of under 4 digits
While RanString.Length <= 3
RanString = RanString & RanGen.Next(0, 9)
End While
’Converts the String to bytes
Dim chiperCode As String = FormsAuthentication.HashPasswordForStoringInConfigFile(EncString, “SHA1″)
EncStringBytes = Encoder.GetBytes(chiperCode & “AgainNextSalt” & RanString)
’Generates the MD5 Byte Array
EncStringBytes = MD5Hasher.ComputeHash(EncStringBytes)
’Affixing Salt information into the MD5 hash
MD5String = BitConverter.ToString(EncStringBytes)
MD5String = MD5String.Replace(“-”, Nothing)
’Finds a random location in the string to sit the salt
RanSaltLoc = RanGen.Next(4, MD5String.Length)
’Shoves the salt in the location
MD5String = MD5String.Insert(RanSaltLoc, RanString)
’Adds 0 for values under 10 so we always occupy 2 charater spaces
If RanSaltLoc < 10 Then
RanSaltLoc = “0″ & RanSaltLoc
End If
’Shoves the salt location in the string at position 3
MD5String = MD5String.Insert(3, RanSaltLoc)
’Returns the MD5 encrypted string to the calling object
Return MD5String
End Function
Public Shared Function Verify(ByVal S As String, ByVal chiper As String) As Boolean
’Variable Declarations
Dim SaltAddress As Double
Dim SaltID As String
Dim NewHash As String
’Finds the Salt Address and Removes the Salt Address from the string
SaltAddress = chiper.Substring(3, 2)
chiper = chiper.Remove(3, 2)
’Finds the SaltID and removes it from the string
SaltID = chiper.Substring(SaltAddress, 4)
chiper = chiper.Remove(SaltAddress, 4)
Dim chiperCode As String = FormsAuthentication.HashPasswordForStoringInConfigFile(S, “SHA1″)
’Converts the string passed to us to Bytes
EncStringBytes = Encoder.GetBytes(chiperCode & “AgainNextSalt” & SaltID)
’Encryptes the string passed to us with the salt
EncStringBytes = MD5Hasher.ComputeHash(EncStringBytes)
’Converts the Hash to a string
NewHash = BitConverter.ToString(EncStringBytes)
NewHash = NewHash.Replace(“-”, Nothing)
’Tests the new has against the one passed to us
If NewHash = chiper Then
Return True
ElseIf NewHash <> chiper Then
Return False
End If
End Function
Sumber: http://www.codeproject.com/KB/dotnet/istmd5.aspx?display=Print
Implementasi Random Secure (SHA1PRNG)
Untuk meng-create bilangan random menggunakan SHA1PRNG code di Java sangat simple nih, silakan disima/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package engine;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author nora herawati
*/
public class TestRandom {
public static void main(String[] args){
SecureRandom random;
try {
random = SecureRandom.getInstance(“SHA1PRNG”);
byte seed[] = random.generateSeed(20);
random.setSeed(seed);
byte bytes[] = new byte[20];
random.nextBytes(bytes);
for (byte b : bytes) {
System.out.println(b);
}
} catch (NoSuchAlgorithmException ex) {
}
}
}
Implementasi SHA-1
Ketika menulis code Digital Signature untuk model DSA, biyasanya membutuhkan code hash SHA-1. Di bawah ini merupakan implementasi SHA-1 di Java yang saya temukan setelah googling. Silakan disimak.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package engine;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.DigestInputStream;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author nora herawati
*/
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class TestSHA {
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) (’0′ + halfbyte));
else
buf.append((char) (‘a’ + (halfbyte – 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
public static String SHA1(String text)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md;
md = MessageDigest.getInstance(“SHA-1″);
byte[] sha1hash = new byte[40];
md.update(text.getBytes(“iso-8859-1″), 0, text.length());
sha1hash = md.digest();
return convertToHex(sha1hash);
}
public static void main(String[] args) throws IOException
{
BufferedReader userInput = new BufferedReader (new InputStreamReader(System.in));
System.out.println(“Enter string:”);
String rawString = userInput.readLine();
try {
System.out.println(“SHA1 hash of string: ” + SHA1(rawString));
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Aplikasi DSA di Java
Aku nemu code neh di Java, sangat simple, untuk implementasi DSA. Silakan dicoba, asik banget pokoknya.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vipercomm;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
/**
*
* @author Pengguna
*/
public class NewMain {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try
{
// 1. Get the bytes in the Message.
String strMessage = ” Hello World !”;
byte [ ] bMessage = strMessage.getBytes ( ) ;
// 2. Get the PrivateKey and the PublicKey.
KeyPair keyPair = KeyPairGenerator.getInstance ( “DSA” ) .generateKeyPair ( ) ;
PrivateKey privateKey = keyPair.getPrivate ( ) ;
PublicKey publicKey = keyPair.getPublic ( ) ;
// Incorrect Public Key
KeyPair keyPairIncorrect = KeyPairGenerator.getInstance ( “DSA” ) .generateKeyPair ( ) ;
PublicKey publicKeyIncorrect = keyPairIncorrect.getPublic ( ) ;
// 3. Encrypt the Data.
Signature signature = Signature.getInstance ( “DSA” ) ;
signature.initSign ( privateKey ) ;
signature.update ( bMessage ) ;
// 4. Get the Signature, by signing the message.
byte [ ] bSignature = signature.sign ( ) ;
// 5. Decrypt the Signature with the Public Key and get the Message Digest.
Signature signaturePublic = Signature.getInstance ( “DSA” ) ;
// 6. Authentication
signaturePublic.initVerify ( publicKey ) ;
signaturePublic.update ( bMessage ) ;
// 6. Check if the Signatures Match.
boolean b = signaturePublic.verify ( bSignature ) ;
if ( b )
{
System.out.println ( ” The Signature is Good ” + b ) ;
}
else
{
System.out.println ( ” The Signature is Bad ” + b ) ;
}
}
catch ( NoSuchAlgorithmException e )
{
e.printStackTrace ( ) ;
}
catch ( SignatureException e )
{
e.printStackTrace ( ) ;
}
catch ( InvalidKeyException e )
{
e.printStackTrace ( ) ;
}
catch ( Exception e )
{
e.printStackTrace ( ) ;
}
}
}