logo

Hvordan krypteres adgangskode i Java?

Hver softwareapplikation kræver et brugernavn og en adgangskode for at godkende den gyldige bruger. Et brugernavn kan være noget som et e-mail-id eller blot en kombination af tegn. Men mens man opretter en adgangskode, skal man være meget forsigtig. Fordi alle med gyldige legitimationsoplysninger kan gå ind i systemet og få adgang til oplysningerne.

Behov for at kryptere en adgangskode

Når en bruger indstiller sin adgangskode, gemmer den i databasen som en almindelig tekst. Det er slet ikke sikkert at gemme den almindelige tekst, som den er i databasen. Hackere kan bryde systemet og stjæle adgangskoder fra databasen.

For at sikre sikkerheden af ​​brugerens adgangskode krypteres det ved hjælp af forskellige krypteringsteknikker. Ved hjælp af forskellige krypteringsteknikker gemmes det almindelige tekstkodeord i en krypteret form i databasen. Der er mange metoder, der kan bruges til at kryptere adgangskoden. Men hashing er en af ​​de mest populære krypteringsteknikker.

Java Secure Hashing-teknikker

Den krypterede hash-værdi genereres ved hjælp af visse algoritmer på den almindelige tekst-adgangskode, som er angivet af brugeren. Java-programmering understøtter flere hashing-teknikker for at kryptere en adgangskode.

MD5 Hashing-teknik

MD5 (Message Digest) er en meget populær hashing-algoritme. Det er en kryptografisk hashfunktion, der genererer en 128-bit hashværdi. Denne algoritme er defineret under java.security-pakken i Java-programmering.

PassEncTech1.java

 import java.security.NoSuchAlgorithmException; import java.security.MessageDigest; public class PassEncTech1 { /* Driver Code */ public static void main(String[] args) { /* Plain-text password initialization. */ String password = &apos;myPassword&apos;; String encryptedpassword = null; try { /* MessageDigest instance for MD5. */ MessageDigest m = MessageDigest.getInstance(&apos;MD5&apos;); /* Add plain-text password bytes to digest using MD5 update() method. */ m.update(password.getBytes()); /* Convert the hash value into bytes */ byte[] bytes = m.digest(); /* The bytes array has bytes in decimal form. Converting it into hexadecimal format. */ StringBuilder s = new StringBuilder(); for(int i=0; i <bytes.length ;i++) { s.append(integer.tostring((bytes[i] & 0xff) + 0x100, 16).substring(1)); } * complete hashed password in hexadecimal format encryptedpassword="s.toString();" catch (nosuchalgorithmexception e) e.printstacktrace(); display the unencrypted and encrypted passwords. system.out.println('plain-text password: ' password); system.out.println('encrypted using md5: encryptedpassword); < pre> <p> <strong>Output:</strong> </p> <pre> Plain-text password: myPassword Encrypted password using MD5: deb1536f480475f7d593219aa1afd74c </pre> <p>The above code shows the implementation of <strong> <em>MessageDigest</em> </strong> class in <strong> <em>java.security</em> </strong> package. The MD5 returns a byte array that needs to be converted into a readable hexadecimal format.</p> <p>The MD5 hashing technique is easy and fast to implement but it is also prone to brute force attacks or dictionary attacks.</p> <h3>SHA256</h3> <p>SHA is the Secure Hash Algorithm. It uses a cryptographic function that takes up the 32-bit plain-text password and converts it into a fixed size 256-bit hash value. This hashing technique is implemented using the MessageDiagest class of java.security package.</p> <p>It is a one-way encryption technique. Once the passphrase is encrypted it cannot be decrypted back.</p> <p> <strong>PassEncTech2.java</strong> </p> <pre> import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class PassEncTech2 { public static byte[] getSHA(String input) throws NoSuchAlgorithmException { /* MessageDigest instance for hashing using SHA256 */ MessageDigest md = MessageDigest.getInstance(&apos;SHA-256&apos;); /* digest() method called to calculate message digest of an input and return array of byte */ return md.digest(input.getBytes(StandardCharsets.UTF_8)); } public static String toHexString(byte[] hash) { /* Convert byte array of hash into digest */ BigInteger number = new BigInteger(1, hash); /* Convert the digest into hex value */ StringBuilder hexString = new StringBuilder(number.toString(16)); /* Pad with leading zeros */ while (hexString.length() <32) { hexstring.insert(0, '0'); } return hexstring.tostring(); * driver code public static void main(string args[]) try string string1="myPassword" ; system.out.println('
' + ' : tohexstring(getsha(string1))); string2="hashtrial" tohexstring(getsha(string2))); catch (nosuchalgorithmexception e) system.out.println('exception thrown for incorrect algorithm: e); < pre> <p> <strong>Output:</strong> </p> <pre> myPassword : 76549b827ec46e705fd03831813fa52172338f0dfcbd711ed44b81a96dac51c6 hashtrial : d3e3224a59d69e9a000f1ce6782cb6a8be1eb3155610ff41bffbcbc95adc5d7 </pre> <p>The above code uses the instance of <strong> <em>MessageDigest</em> </strong> class to generate a hash for <strong> <em>SHA256</em> </strong> . The SHA256 returns a byte array that needs to be converted into a readable hexadecimal format. And lastly, the encrypted hash value is displayed.</p> <h3>SHA512 MD5 Hashing Technique</h3> <p>SHA512 uses a cryptographic function that takes up the 64-bit plain-text password and converts it into a fixed size 512-bit hash value. This hashing technique is also implemented using the MessageDiagest class of java.security package.</p> <p> <strong>PassEncTech2.java</strong> </p> <pre> import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class PassEncTech2 { public static byte[] getSHA(String input) throws NoSuchAlgorithmException { /* MessageDigest instance for hashing using SHA512*/ MessageDigest md = MessageDigest.getInstance(&apos;SHA-512&apos;); /* digest() method called to calculate message digest of an input and return array of byte */ return md.digest(input.getBytes(StandardCharsets.UTF_8)); } public static String toHexString(byte[] hash) { /* Convert byte array of hash into digest */ BigInteger number = new BigInteger(1, hash); /* Convert the digest into hex value */ StringBuilder hexString = new StringBuilder(number.toString(16)); /* Pad with leading zeros */ while (hexString.length() <32) { hexstring.insert(0, '0'); } return hexstring.tostring(); * driver code public static void main(string args[]) try string string1="myPassword" ; system.out.println('
' + ' : tohexstring(getsha(string1))); string2="hashtrial" tohexstring(getsha(string2))); catch (nosuchalgorithmexception e) system.out.println('exception thrown for incorrect algorithm: e); < pre> <p> <strong>Output:</strong> </p> <pre> myPassword : 450ad03db9395dfccb5e03066fd7f16cfba2b61e23d516373714471459052ec90a9a4bf3a151e600ea8aaed36e3b8c21a3d38ab1705839749d130da4380f1448 hashtrial : 9520ea1a8d60d23334e6d59acebd587de6fec1e53db5836f467096c540ae60f7c85e9fbc90856dee9d6563609b8786b03b47892af0bad44bdcab2206f22df5cb </pre> <p>The above code uses the instance of <strong> <em>MessageDigest</em> </strong> class to generate a hash for <strong> <em>SHA512</em> </strong> . The SHA512 returns a byte array that needs to be converted into a readable hexadecimal format. And lastly, the encrypted hash value is displayed.</p> <h3>Password-Based Encryption using Salt and Base64:</h3> <p>The password-based encryption technique uses plain text passwords and salt values to generate a hash value. And the hash value is then encoded as a Base64 string. Salt value contains random data generated using an instance of Random class from java.util package.</p> <p>The following program demonstrates password encryption using salt and base64.</p> <p> <strong>PassEncTech4.java</strong> </p> <pre> import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; import java.util.Base64; import java.util.Random; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; public class PassEncTech4 { /* Driver Code */ public static void main(String[] args) { /* Plain text Password. */ String password = &apos;myNewPass123&apos;; /* generates the Salt value. It can be stored in a database. */ String saltvalue = PassBasedEnc.getSaltvalue(30); /* generates an encrypted password. It can be stored in a database.*/ String encryptedpassword = PassBasedEnc.generateSecurePassword(password, saltvalue); /* Print out plain text password, encrypted password and salt value. */ System.out.println(&apos;Plain text password = &apos; + password); System.out.println(&apos;Secure password = &apos; + encryptedpassword); System.out.println(&apos;Salt value = &apos; + saltvalue); /* verify the original password and encrypted password */ Boolean status = PassBasedEnc.verifyUserPassword(password,encryptedpassword,saltvalue); if(status==true) System.out.println(&apos;Password Matched!!&apos;); else System.out.println(&apos;Password Mismatched&apos;); } } class PassBasedEnc { /* Declaration of variables */ private static final Random random = new SecureRandom(); private static final String characters = &apos;0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&apos;; private static final int iterations = 10000; private static final int keylength = 256; /* Method to generate the salt value. */ public static String getSaltvalue(int length) { StringBuilder finalval = new StringBuilder(length); for (int i = 0; i <length; i++) { finalval.append(characters.charat(random.nextint(characters.length()))); } return new string(finalval); * method to generate the hash value public static byte[] hash(char[] password, salt) pbekeyspec spec="new" pbekeyspec(password, salt, iterations, keylength); arrays.fill(password, character.min_value); try secretkeyfactory skf="SecretKeyFactory.getInstance(&apos;PBKDF2WithHmacSHA1&apos;);" skf.generatesecret(spec).getencoded(); catch (nosuchalgorithmexception | invalidkeyspecexception e) throw assertionerror('error while hashing a password: ' + e.getmessage(), e); finally spec.clearpassword(); encrypt password using original and salt value. string generatesecurepassword(string finalval="null;" securepassword="hash(password.toCharArray()," salt.getbytes()); finalval; verify if both matches or not boolean verifyuserpassword(string providedpassword, securedpassword, secure with same newsecurepassword="generateSecurePassword(providedPassword," salt); check two passwords are equal < pre> <p> <strong>Output:</strong> </p> <pre> Plain text password = myNewPass123 Secure password = sA0jNGQTrAfMUiqrB++bMKTU55ThdFCl16ZZTIXwD2M= Salt value = n7d9MPQFXxDqzT6onmong3hQt8Nyko Password Matched!! </pre> <p>In the above code, two classes are defined.</p> <ol class="points"> <li>The class <strong> <em>PassEncTech4</em> </strong> contains the driver code for the program. It generates a salt value and encrypted password using the given plain-text password. And verifies them using the value returned by the <strong> <em>verifyUserPassword() </em> </strong> </li> <li>In the class <strong> <em>PassBasedEnc, </em> </strong> 4 methods are defined. The first method is <strong> <em>getSaltvalue()</em> </strong> which generates the value using <strong> <em>Random</em> </strong> class from <strong> <em>util</em> </strong> package. Then <strong> <em>hash()</em> </strong> is defined that has a return type of byte array. The <strong> <em>generateSecurePassword() </em> </strong> uses plain-text password and salt value with the <strong> <em>hash()</em> </strong> method. And lastly, the two passwords are matched using the <strong> <em>verifyUserPassword()</em> </strong> method.</li> </ol> <h2>Techniques for Cracking the Hash</h2> <p>A hash value is prone to different kinds of attacks by attackers. Some of them are mentioned below,</p> <ol class="points"> <tr><td>Brute force attack:</td> In the brute force attack, the attacker submits multiple combinations of passphrases or passwords in the hope that one of the combinations will match and he can enter into the system. <br> To avoid this kind of attack the passphrase should use a combination of alphabets, numbers and symbols. Another way is to set a fixed number of invalid attempts and after that ask for human verification like a captcha. </tr><tr><td>Dictionary attack:</td> Dictionary attack is an enhanced version of brute force attack. In this technique, the encrypted cipher is tried to be decrypted using multiple possibilities, like the words in a dictionary. </tr><tr><td>Rainbow tables:</td> The technique is about a rainbow table that is precomputed table for reversing the cryptographic hash functions. The rainbow tables are used to discover the plain text passwords up to a certain length and a limited number of characters. So it uses a side-loop table in order to reduce the storage usage and increase the speed of attack. </tr></ol> <hr></length;></pre></32)></pre></32)></pre></bytes.length>

Ovenstående kode viser implementeringen af MessageDigest klasse i java.sikkerhed pakke. MD5 returnerer et byte-array, der skal konverteres til et læsbart hexadecimalt format.

MD5-hash-teknikken er nem og hurtig at implementere, men den er også tilbøjelig til brute force-angreb eller ordbogsangreb.

SHA256

SHA er Secure Hash Algorithm. Den bruger en kryptografisk funktion, der optager 32-bit almindelig tekstadgangskode og konverterer den til en fast størrelse 256-bit hashværdi. Denne hashing-teknik er implementeret ved hjælp af MessageDiagest-klassen af ​​java.security-pakken.

Det er en envejs krypteringsteknik. Når først adgangssætningen er krypteret, kan den ikke dekrypteres tilbage.

PassEncTech2.java

 import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class PassEncTech2 { public static byte[] getSHA(String input) throws NoSuchAlgorithmException { /* MessageDigest instance for hashing using SHA256 */ MessageDigest md = MessageDigest.getInstance(&apos;SHA-256&apos;); /* digest() method called to calculate message digest of an input and return array of byte */ return md.digest(input.getBytes(StandardCharsets.UTF_8)); } public static String toHexString(byte[] hash) { /* Convert byte array of hash into digest */ BigInteger number = new BigInteger(1, hash); /* Convert the digest into hex value */ StringBuilder hexString = new StringBuilder(number.toString(16)); /* Pad with leading zeros */ while (hexString.length() <32) { hexstring.insert(0, \'0\'); } return hexstring.tostring(); * driver code public static void main(string args[]) try string string1="myPassword" ; system.out.println(\'
\' + \' : tohexstring(getsha(string1))); string2="hashtrial" tohexstring(getsha(string2))); catch (nosuchalgorithmexception e) system.out.println(\'exception thrown for incorrect algorithm: e); < pre> <p> <strong>Output:</strong> </p> <pre> myPassword : 76549b827ec46e705fd03831813fa52172338f0dfcbd711ed44b81a96dac51c6 hashtrial : d3e3224a59d69e9a000f1ce6782cb6a8be1eb3155610ff41bffbcbc95adc5d7 </pre> <p>The above code uses the instance of <strong> <em>MessageDigest</em> </strong> class to generate a hash for <strong> <em>SHA256</em> </strong> . The SHA256 returns a byte array that needs to be converted into a readable hexadecimal format. And lastly, the encrypted hash value is displayed.</p> <h3>SHA512 MD5 Hashing Technique</h3> <p>SHA512 uses a cryptographic function that takes up the 64-bit plain-text password and converts it into a fixed size 512-bit hash value. This hashing technique is also implemented using the MessageDiagest class of java.security package.</p> <p> <strong>PassEncTech2.java</strong> </p> <pre> import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class PassEncTech2 { public static byte[] getSHA(String input) throws NoSuchAlgorithmException { /* MessageDigest instance for hashing using SHA512*/ MessageDigest md = MessageDigest.getInstance(&apos;SHA-512&apos;); /* digest() method called to calculate message digest of an input and return array of byte */ return md.digest(input.getBytes(StandardCharsets.UTF_8)); } public static String toHexString(byte[] hash) { /* Convert byte array of hash into digest */ BigInteger number = new BigInteger(1, hash); /* Convert the digest into hex value */ StringBuilder hexString = new StringBuilder(number.toString(16)); /* Pad with leading zeros */ while (hexString.length() <32) { hexstring.insert(0, \'0\'); } return hexstring.tostring(); * driver code public static void main(string args[]) try string string1="myPassword" ; system.out.println(\'
\' + \' : tohexstring(getsha(string1))); string2="hashtrial" tohexstring(getsha(string2))); catch (nosuchalgorithmexception e) system.out.println(\'exception thrown for incorrect algorithm: e); < pre> <p> <strong>Output:</strong> </p> <pre> myPassword : 450ad03db9395dfccb5e03066fd7f16cfba2b61e23d516373714471459052ec90a9a4bf3a151e600ea8aaed36e3b8c21a3d38ab1705839749d130da4380f1448 hashtrial : 9520ea1a8d60d23334e6d59acebd587de6fec1e53db5836f467096c540ae60f7c85e9fbc90856dee9d6563609b8786b03b47892af0bad44bdcab2206f22df5cb </pre> <p>The above code uses the instance of <strong> <em>MessageDigest</em> </strong> class to generate a hash for <strong> <em>SHA512</em> </strong> . The SHA512 returns a byte array that needs to be converted into a readable hexadecimal format. And lastly, the encrypted hash value is displayed.</p> <h3>Password-Based Encryption using Salt and Base64:</h3> <p>The password-based encryption technique uses plain text passwords and salt values to generate a hash value. And the hash value is then encoded as a Base64 string. Salt value contains random data generated using an instance of Random class from java.util package.</p> <p>The following program demonstrates password encryption using salt and base64.</p> <p> <strong>PassEncTech4.java</strong> </p> <pre> import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; import java.util.Base64; import java.util.Random; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; public class PassEncTech4 { /* Driver Code */ public static void main(String[] args) { /* Plain text Password. */ String password = &apos;myNewPass123&apos;; /* generates the Salt value. It can be stored in a database. */ String saltvalue = PassBasedEnc.getSaltvalue(30); /* generates an encrypted password. It can be stored in a database.*/ String encryptedpassword = PassBasedEnc.generateSecurePassword(password, saltvalue); /* Print out plain text password, encrypted password and salt value. */ System.out.println(&apos;Plain text password = &apos; + password); System.out.println(&apos;Secure password = &apos; + encryptedpassword); System.out.println(&apos;Salt value = &apos; + saltvalue); /* verify the original password and encrypted password */ Boolean status = PassBasedEnc.verifyUserPassword(password,encryptedpassword,saltvalue); if(status==true) System.out.println(&apos;Password Matched!!&apos;); else System.out.println(&apos;Password Mismatched&apos;); } } class PassBasedEnc { /* Declaration of variables */ private static final Random random = new SecureRandom(); private static final String characters = &apos;0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&apos;; private static final int iterations = 10000; private static final int keylength = 256; /* Method to generate the salt value. */ public static String getSaltvalue(int length) { StringBuilder finalval = new StringBuilder(length); for (int i = 0; i <length; i++) { finalval.append(characters.charat(random.nextint(characters.length()))); } return new string(finalval); * method to generate the hash value public static byte[] hash(char[] password, salt) pbekeyspec spec="new" pbekeyspec(password, salt, iterations, keylength); arrays.fill(password, character.min_value); try secretkeyfactory skf="SecretKeyFactory.getInstance(&apos;PBKDF2WithHmacSHA1&apos;);" skf.generatesecret(spec).getencoded(); catch (nosuchalgorithmexception | invalidkeyspecexception e) throw assertionerror(\'error while hashing a password: \' + e.getmessage(), e); finally spec.clearpassword(); encrypt password using original and salt value. string generatesecurepassword(string finalval="null;" securepassword="hash(password.toCharArray()," salt.getbytes()); finalval; verify if both matches or not boolean verifyuserpassword(string providedpassword, securedpassword, secure with same newsecurepassword="generateSecurePassword(providedPassword," salt); check two passwords are equal < pre> <p> <strong>Output:</strong> </p> <pre> Plain text password = myNewPass123 Secure password = sA0jNGQTrAfMUiqrB++bMKTU55ThdFCl16ZZTIXwD2M= Salt value = n7d9MPQFXxDqzT6onmong3hQt8Nyko Password Matched!! </pre> <p>In the above code, two classes are defined.</p> <ol class="points"> <li>The class <strong> <em>PassEncTech4</em> </strong> contains the driver code for the program. It generates a salt value and encrypted password using the given plain-text password. And verifies them using the value returned by the <strong> <em>verifyUserPassword() </em> </strong> </li> <li>In the class <strong> <em>PassBasedEnc, </em> </strong> 4 methods are defined. The first method is <strong> <em>getSaltvalue()</em> </strong> which generates the value using <strong> <em>Random</em> </strong> class from <strong> <em>util</em> </strong> package. Then <strong> <em>hash()</em> </strong> is defined that has a return type of byte array. The <strong> <em>generateSecurePassword() </em> </strong> uses plain-text password and salt value with the <strong> <em>hash()</em> </strong> method. And lastly, the two passwords are matched using the <strong> <em>verifyUserPassword()</em> </strong> method.</li> </ol> <h2>Techniques for Cracking the Hash</h2> <p>A hash value is prone to different kinds of attacks by attackers. Some of them are mentioned below,</p> <ol class="points"> <tr><td>Brute force attack:</td> In the brute force attack, the attacker submits multiple combinations of passphrases or passwords in the hope that one of the combinations will match and he can enter into the system. <br> To avoid this kind of attack the passphrase should use a combination of alphabets, numbers and symbols. Another way is to set a fixed number of invalid attempts and after that ask for human verification like a captcha. </tr><tr><td>Dictionary attack:</td> Dictionary attack is an enhanced version of brute force attack. In this technique, the encrypted cipher is tried to be decrypted using multiple possibilities, like the words in a dictionary. </tr><tr><td>Rainbow tables:</td> The technique is about a rainbow table that is precomputed table for reversing the cryptographic hash functions. The rainbow tables are used to discover the plain text passwords up to a certain length and a limited number of characters. So it uses a side-loop table in order to reduce the storage usage and increase the speed of attack. </tr></ol> <hr></length;></pre></32)></pre></32)>

Ovenstående kode bruger instansen af MessageDigest klasse til at generere en hash for SHA256 . SHA256 returnerer et byte-array, der skal konverteres til et læsbart hexadecimalt format. Og til sidst vises den krypterede hashværdi.

SHA512 MD5 Hashing-teknik

SHA512 bruger en kryptografisk funktion, der optager 64-bit almindelig tekstadgangskode og konverterer den til en fast størrelse 512-bit hashværdi. Denne hashing-teknik er også implementeret ved hjælp af MessageDiagest-klassen af ​​java.security-pakken.

PassEncTech2.java

 import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class PassEncTech2 { public static byte[] getSHA(String input) throws NoSuchAlgorithmException { /* MessageDigest instance for hashing using SHA512*/ MessageDigest md = MessageDigest.getInstance(&apos;SHA-512&apos;); /* digest() method called to calculate message digest of an input and return array of byte */ return md.digest(input.getBytes(StandardCharsets.UTF_8)); } public static String toHexString(byte[] hash) { /* Convert byte array of hash into digest */ BigInteger number = new BigInteger(1, hash); /* Convert the digest into hex value */ StringBuilder hexString = new StringBuilder(number.toString(16)); /* Pad with leading zeros */ while (hexString.length() <32) { hexstring.insert(0, \'0\'); } return hexstring.tostring(); * driver code public static void main(string args[]) try string string1="myPassword" ; system.out.println(\'
\' + \' : tohexstring(getsha(string1))); string2="hashtrial" tohexstring(getsha(string2))); catch (nosuchalgorithmexception e) system.out.println(\'exception thrown for incorrect algorithm: e); < pre> <p> <strong>Output:</strong> </p> <pre> myPassword : 450ad03db9395dfccb5e03066fd7f16cfba2b61e23d516373714471459052ec90a9a4bf3a151e600ea8aaed36e3b8c21a3d38ab1705839749d130da4380f1448 hashtrial : 9520ea1a8d60d23334e6d59acebd587de6fec1e53db5836f467096c540ae60f7c85e9fbc90856dee9d6563609b8786b03b47892af0bad44bdcab2206f22df5cb </pre> <p>The above code uses the instance of <strong> <em>MessageDigest</em> </strong> class to generate a hash for <strong> <em>SHA512</em> </strong> . The SHA512 returns a byte array that needs to be converted into a readable hexadecimal format. And lastly, the encrypted hash value is displayed.</p> <h3>Password-Based Encryption using Salt and Base64:</h3> <p>The password-based encryption technique uses plain text passwords and salt values to generate a hash value. And the hash value is then encoded as a Base64 string. Salt value contains random data generated using an instance of Random class from java.util package.</p> <p>The following program demonstrates password encryption using salt and base64.</p> <p> <strong>PassEncTech4.java</strong> </p> <pre> import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; import java.util.Base64; import java.util.Random; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; public class PassEncTech4 { /* Driver Code */ public static void main(String[] args) { /* Plain text Password. */ String password = &apos;myNewPass123&apos;; /* generates the Salt value. It can be stored in a database. */ String saltvalue = PassBasedEnc.getSaltvalue(30); /* generates an encrypted password. It can be stored in a database.*/ String encryptedpassword = PassBasedEnc.generateSecurePassword(password, saltvalue); /* Print out plain text password, encrypted password and salt value. */ System.out.println(&apos;Plain text password = &apos; + password); System.out.println(&apos;Secure password = &apos; + encryptedpassword); System.out.println(&apos;Salt value = &apos; + saltvalue); /* verify the original password and encrypted password */ Boolean status = PassBasedEnc.verifyUserPassword(password,encryptedpassword,saltvalue); if(status==true) System.out.println(&apos;Password Matched!!&apos;); else System.out.println(&apos;Password Mismatched&apos;); } } class PassBasedEnc { /* Declaration of variables */ private static final Random random = new SecureRandom(); private static final String characters = &apos;0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&apos;; private static final int iterations = 10000; private static final int keylength = 256; /* Method to generate the salt value. */ public static String getSaltvalue(int length) { StringBuilder finalval = new StringBuilder(length); for (int i = 0; i <length; i++) { finalval.append(characters.charat(random.nextint(characters.length()))); } return new string(finalval); * method to generate the hash value public static byte[] hash(char[] password, salt) pbekeyspec spec="new" pbekeyspec(password, salt, iterations, keylength); arrays.fill(password, character.min_value); try secretkeyfactory skf="SecretKeyFactory.getInstance(&apos;PBKDF2WithHmacSHA1&apos;);" skf.generatesecret(spec).getencoded(); catch (nosuchalgorithmexception | invalidkeyspecexception e) throw assertionerror(\'error while hashing a password: \' + e.getmessage(), e); finally spec.clearpassword(); encrypt password using original and salt value. string generatesecurepassword(string finalval="null;" securepassword="hash(password.toCharArray()," salt.getbytes()); finalval; verify if both matches or not boolean verifyuserpassword(string providedpassword, securedpassword, secure with same newsecurepassword="generateSecurePassword(providedPassword," salt); check two passwords are equal < pre> <p> <strong>Output:</strong> </p> <pre> Plain text password = myNewPass123 Secure password = sA0jNGQTrAfMUiqrB++bMKTU55ThdFCl16ZZTIXwD2M= Salt value = n7d9MPQFXxDqzT6onmong3hQt8Nyko Password Matched!! </pre> <p>In the above code, two classes are defined.</p> <ol class="points"> <li>The class <strong> <em>PassEncTech4</em> </strong> contains the driver code for the program. It generates a salt value and encrypted password using the given plain-text password. And verifies them using the value returned by the <strong> <em>verifyUserPassword() </em> </strong> </li> <li>In the class <strong> <em>PassBasedEnc, </em> </strong> 4 methods are defined. The first method is <strong> <em>getSaltvalue()</em> </strong> which generates the value using <strong> <em>Random</em> </strong> class from <strong> <em>util</em> </strong> package. Then <strong> <em>hash()</em> </strong> is defined that has a return type of byte array. The <strong> <em>generateSecurePassword() </em> </strong> uses plain-text password and salt value with the <strong> <em>hash()</em> </strong> method. And lastly, the two passwords are matched using the <strong> <em>verifyUserPassword()</em> </strong> method.</li> </ol> <h2>Techniques for Cracking the Hash</h2> <p>A hash value is prone to different kinds of attacks by attackers. Some of them are mentioned below,</p> <ol class="points"> <tr><td>Brute force attack:</td> In the brute force attack, the attacker submits multiple combinations of passphrases or passwords in the hope that one of the combinations will match and he can enter into the system. <br> To avoid this kind of attack the passphrase should use a combination of alphabets, numbers and symbols. Another way is to set a fixed number of invalid attempts and after that ask for human verification like a captcha. </tr><tr><td>Dictionary attack:</td> Dictionary attack is an enhanced version of brute force attack. In this technique, the encrypted cipher is tried to be decrypted using multiple possibilities, like the words in a dictionary. </tr><tr><td>Rainbow tables:</td> The technique is about a rainbow table that is precomputed table for reversing the cryptographic hash functions. The rainbow tables are used to discover the plain text passwords up to a certain length and a limited number of characters. So it uses a side-loop table in order to reduce the storage usage and increase the speed of attack. </tr></ol> <hr></length;></pre></32)>

Ovenstående kode bruger instansen af MessageDigest klasse til at generere en hash for SHA512 . SHA512 returnerer et byte-array, der skal konverteres til et læsbart hexadecimalt format. Og til sidst vises den krypterede hashværdi.

Adgangskodebaseret kryptering ved hjælp af Salt og Base64:

Den adgangskodebaserede krypteringsteknik bruger almindelig tekstadgangskoder og saltværdier til at generere en hashværdi. Og hash-værdien kodes derefter som en Base64-streng. Saltværdien indeholder tilfældige data, der er genereret ved hjælp af en forekomst af klassen Random fra pakken java.util.

Følgende program demonstrerer adgangskodekryptering ved hjælp af salt og base64.

PassEncTech4.java

 import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; import java.util.Base64; import java.util.Random; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; public class PassEncTech4 { /* Driver Code */ public static void main(String[] args) { /* Plain text Password. */ String password = &apos;myNewPass123&apos;; /* generates the Salt value. It can be stored in a database. */ String saltvalue = PassBasedEnc.getSaltvalue(30); /* generates an encrypted password. It can be stored in a database.*/ String encryptedpassword = PassBasedEnc.generateSecurePassword(password, saltvalue); /* Print out plain text password, encrypted password and salt value. */ System.out.println(&apos;Plain text password = &apos; + password); System.out.println(&apos;Secure password = &apos; + encryptedpassword); System.out.println(&apos;Salt value = &apos; + saltvalue); /* verify the original password and encrypted password */ Boolean status = PassBasedEnc.verifyUserPassword(password,encryptedpassword,saltvalue); if(status==true) System.out.println(&apos;Password Matched!!&apos;); else System.out.println(&apos;Password Mismatched&apos;); } } class PassBasedEnc { /* Declaration of variables */ private static final Random random = new SecureRandom(); private static final String characters = &apos;0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&apos;; private static final int iterations = 10000; private static final int keylength = 256; /* Method to generate the salt value. */ public static String getSaltvalue(int length) { StringBuilder finalval = new StringBuilder(length); for (int i = 0; i <length; i++) { finalval.append(characters.charat(random.nextint(characters.length()))); } return new string(finalval); * method to generate the hash value public static byte[] hash(char[] password, salt) pbekeyspec spec="new" pbekeyspec(password, salt, iterations, keylength); arrays.fill(password, character.min_value); try secretkeyfactory skf="SecretKeyFactory.getInstance(&apos;PBKDF2WithHmacSHA1&apos;);" skf.generatesecret(spec).getencoded(); catch (nosuchalgorithmexception | invalidkeyspecexception e) throw assertionerror(\\'error while hashing a password: \\' + e.getmessage(), e); finally spec.clearpassword(); encrypt password using original and salt value. string generatesecurepassword(string finalval="null;" securepassword="hash(password.toCharArray()," salt.getbytes()); finalval; verify if both matches or not boolean verifyuserpassword(string providedpassword, securedpassword, secure with same newsecurepassword="generateSecurePassword(providedPassword," salt); check two passwords are equal < pre> <p> <strong>Output:</strong> </p> <pre> Plain text password = myNewPass123 Secure password = sA0jNGQTrAfMUiqrB++bMKTU55ThdFCl16ZZTIXwD2M= Salt value = n7d9MPQFXxDqzT6onmong3hQt8Nyko Password Matched!! </pre> <p>In the above code, two classes are defined.</p> <ol class="points"> <li>The class <strong> <em>PassEncTech4</em> </strong> contains the driver code for the program. It generates a salt value and encrypted password using the given plain-text password. And verifies them using the value returned by the <strong> <em>verifyUserPassword() </em> </strong> </li> <li>In the class <strong> <em>PassBasedEnc, </em> </strong> 4 methods are defined. The first method is <strong> <em>getSaltvalue()</em> </strong> which generates the value using <strong> <em>Random</em> </strong> class from <strong> <em>util</em> </strong> package. Then <strong> <em>hash()</em> </strong> is defined that has a return type of byte array. The <strong> <em>generateSecurePassword() </em> </strong> uses plain-text password and salt value with the <strong> <em>hash()</em> </strong> method. And lastly, the two passwords are matched using the <strong> <em>verifyUserPassword()</em> </strong> method.</li> </ol> <h2>Techniques for Cracking the Hash</h2> <p>A hash value is prone to different kinds of attacks by attackers. Some of them are mentioned below,</p> <ol class="points"> <tr><td>Brute force attack:</td> In the brute force attack, the attacker submits multiple combinations of passphrases or passwords in the hope that one of the combinations will match and he can enter into the system. <br> To avoid this kind of attack the passphrase should use a combination of alphabets, numbers and symbols. Another way is to set a fixed number of invalid attempts and after that ask for human verification like a captcha. </tr><tr><td>Dictionary attack:</td> Dictionary attack is an enhanced version of brute force attack. In this technique, the encrypted cipher is tried to be decrypted using multiple possibilities, like the words in a dictionary. </tr><tr><td>Rainbow tables:</td> The technique is about a rainbow table that is precomputed table for reversing the cryptographic hash functions. The rainbow tables are used to discover the plain text passwords up to a certain length and a limited number of characters. So it uses a side-loop table in order to reduce the storage usage and increase the speed of attack. </tr></ol> <hr></length;>

I ovenstående kode er to klasser defineret.

  1. Klassen PassEncTech4 indeholder driverkoden til programmet. Den genererer en saltværdi og krypteret adgangskode ved hjælp af den givne adgangskode i almindelig tekst. Og verificerer dem ved hjælp af værdien returneret af verifyUserPassword()
  2. I klassen PassBasedEnc, Der er defineret 4 metoder. Den første metode er getSaltvalue() som genererer værdien vha tilfældig klasse fra util pakke. Derefter hash() er defineret, der har en returtype af byte-array. Det generSecurePassword() bruger almindelig tekst adgangskode og salt værdi med hash() metode. Og endelig matches de to adgangskoder ved hjælp af verifyUserPassword() metode.

Teknikker til at knække hashen

En hashværdi er tilbøjelig til forskellige former for angreb fra angribere. Nogle af dem er nævnt nedenfor,

    Brute force angreb:I brute force-angrebet indsender angriberen flere kombinationer af adgangssætninger eller adgangskoder i håb om, at en af ​​kombinationerne vil matche, og han kan komme ind i systemet.
    For at undgå denne form for angreb bør adgangssætningen bruge en kombination af alfabeter, tal og symboler. En anden måde er at indstille et fast antal ugyldige forsøg og derefter bede om menneskelig verifikation som en captcha.Ordbogsangreb:Ordbogsangreb er en forbedret version af brute force-angreb. I denne teknik forsøges den krypterede chiffer at blive dekrypteret ved hjælp af flere muligheder, som ordene i en ordbog.Regnbue borde:Teknikken handler om en regnbuetabel, der er forudberegnet tabel til at vende de kryptografiske hash-funktioner. Regnbuetabellerne bruges til at finde almindelig tekstadgangskoder op til en vis længde og et begrænset antal tegn. Så det bruger et sideløkkebord for at reducere lagerforbruget og øge angrebshastigheden.