logo

Java에서 비밀번호를 암호화하는 방법은 무엇입니까?

모든 소프트웨어 애플리케이션에는 유효한 사용자를 인증하기 위해 사용자 이름과 비밀번호가 필요합니다. 사용자 이름은 이메일 ID나 문자 조합 등 무엇이든 될 수 있습니다. 하지만 비밀번호를 생성할 때는 매우 조심해야 합니다. 유효한 자격 증명을 가진 사람은 누구나 시스템에 들어가 정보에 접근할 수 있기 때문입니다.

비밀번호 암호화의 필요성

사용자가 자신의 비밀번호를 설정하면 데이터베이스에 일반 텍스트로 저장됩니다. 일반 텍스트를 있는 그대로 데이터베이스에 저장하는 것은 전혀 안전하지 않습니다. 해커는 시스템을 손상시키고 데이터베이스에서 비밀번호를 훔칠 수 있습니다.

안드로이드 유튜브 광고 차단

사용자 비밀번호의 보안을 보장하기 위해 다양한 암호화 기술을 사용하여 암호화됩니다. 다양한 암호화 기술을 사용하여 일반 텍스트 비밀번호는 암호화된 형태로 데이터베이스에 저장됩니다. 비밀번호를 암호화하는 데 사용할 수 있는 방법은 다양합니다. 그러나 해싱은 가장 널리 사용되는 암호화 기술 중 하나입니다.

Java 보안 해싱 기술

암호화된 해시 값은 사용자가 제공한 일반 텍스트 비밀번호에 대해 특정 알고리즘을 사용하여 생성됩니다. Java 프로그래밍은 비밀번호를 암호화하기 위해 여러 가지 해싱 기술을 지원합니다.

MD5 해싱 기술

MD5(Message Digest)는 매우 널리 사용되는 해싱 알고리즘입니다. 128비트 해시 값을 생성하는 암호화 해시 함수입니다. 이 알고리즘은 Java 프로그래밍의 java.security 패키지에 정의되어 있습니다.

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>

위의 코드는 구현을 보여줍니다. 메시지다이제스트 수업 자바.보안 패키지. MD5는 읽을 수 있는 16진수 형식으로 변환해야 하는 바이트 배열을 반환합니다.

빈에서 bcd로

MD5 해싱 기술은 구현이 쉽고 빠르지만 무차별 대입 공격이나 사전 공격에 취약합니다.

SHA256

SHA는 보안 해시 알고리즘입니다. 32비트 일반 텍스트 비밀번호를 사용하여 고정된 크기의 256비트 해시 값으로 변환하는 암호화 기능을 사용합니다. 이 해싱 기술은 java.security 패키지의 MessageDiagest 클래스를 사용하여 구현됩니다.

단방향 암호화 기술입니다. 암호 문구가 암호화되면 다시 해독할 수 없습니다.

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)>

위의 코드는 다음의 인스턴스를 사용합니다. 메시지다이제스트 해시를 생성하는 클래스 SHA256 . SHA256은 읽을 수 있는 16진수 형식으로 변환해야 하는 바이트 배열을 반환합니다. 그리고 마지막으로 암호화된 해시 값이 표시됩니다.

SHA512 MD5 해싱 기술

SHA512는 64비트 일반 텍스트 비밀번호를 사용하여 고정된 크기의 512비트 해시 값으로 변환하는 암호화 기능을 사용합니다. 이 해싱 기술은 java.security 패키지의 MessageDiagest 클래스를 사용하여 구현됩니다.

자바에서 문자를 문자열로 캐스트

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)>

위의 코드는 다음의 인스턴스를 사용합니다. 메시지다이제스트 해시를 생성하는 클래스 SHA512 . SHA512는 읽을 수 있는 16진수 형식으로 변환해야 하는 바이트 배열을 반환합니다. 그리고 마지막으로 암호화된 해시 값이 표시됩니다.

Salt 및 Base64를 사용한 비밀번호 기반 암호화:

비밀번호 기반 암호화 기술은 일반 텍스트 비밀번호와 솔트 값을 사용하여 해시 값을 생성합니다. 그런 다음 해시 값은 Base64 문자열로 인코딩됩니다. 솔트 값에는 java.util 패키지의 Random 클래스 인스턴스를 사용하여 생성된 무작위 데이터가 포함되어 있습니다.

다음 프로그램은 salt 및 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;>

위의 코드에는 두 개의 클래스가 정의되어 있습니다.

  1. 클래스 PassEncTech4 프로그램의 드라이버 코드가 포함되어 있습니다. 주어진 일반 텍스트 비밀번호를 사용하여 솔트 값과 암호화된 비밀번호를 생성합니다. 그리고 반환된 값을 사용하여 이를 확인합니다. 사용자비밀번호() 확인
  2. 수업 중 패스 기반 Enc, 4가지 메소드가 정의되어 있습니다. 첫 번째 방법은 getSalt값() 다음을 사용하여 값을 생성합니다. 무작위의 수업 유틸리티 패키지. 그 다음에 해시시() 반환 유형이 바이트 배열인 것으로 정의됩니다. 그만큼 보안비밀번호() 생성 일반 텍스트 비밀번호와 솔트 값을 사용합니다. 해시시() 방법. 마지막으로 두 비밀번호는 다음을 사용하여 일치됩니다. 사용자비밀번호() 확인 방법.

해시 크래킹 기술

해시 값은 공격자가 다양한 종류의 공격을 받기 쉽습니다. 그 중 일부는 아래에 언급되어 있습니다.

    무차별 공격:무차별 대입 공격에서 공격자는 조합 중 하나가 일치하여 시스템에 들어갈 수 있기를 바라면서 여러 암호 문구 또는 비밀번호 조합을 제출합니다.
    이러한 종류의 공격을 방지하려면 암호에 알파벳, 숫자 및 기호를 조합하여 사용해야 합니다. 또 다른 방법은 잘못된 시도 횟수를 고정한 다음 보안 문자와 같은 사람의 확인을 요청하는 것입니다.사전 공격:사전 공격은 무차별 대입 공격(Brute Force Attack)의 향상된 버전입니다. 이 기술에서는 사전에 나오는 단어와 같은 다양한 가능성을 사용하여 암호화된 암호를 해독하려고 합니다.레인보우 테이블:이 기술은 암호화 해시 함수를 역전시키기 위해 미리 계산된 테이블인 레인보우 테이블에 관한 것입니다. 레인보우 테이블은 특정 길이와 제한된 문자 수까지의 일반 텍스트 비밀번호를 찾는 데 사용됩니다. 그래서 스토리지 사용량을 줄이고 공격 속도를 높이기 위해 사이드 루프 테이블을 사용합니다.