我有以下要求。散列密碼並與MD5比較
1. save a user password converted to hash(digested)
2. when comparing with data base, add random bytes with the password given from user
3. now send the random bytes added password to DAO class
4. separate the random byte from password
5. compare with the stored hashed(digested) password
我嘗試了一些相似的東西,但它給出了數組超出界限的異常。
package poc;
import com.sun.xml.internal.ws.message.ByteArrayAttachment;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
public class HashedPassword {
public static final String CRYPTOGRAPHY_ALGORITHM = "MD5";
public static final String CHAR_SET = "UTF8";
public static void main(String[] arg){
System.out.println(createPassword("[email protected]*$"));
}
public static byte[] createPassword(String password){
byte[] salt = new byte[12];
byte[] digestedPassword =null;
byte[] digestedPasswordPwd =null;
try {
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
MessageDigest mdPassword = MessageDigest.getInstance(CRYPTOGRAPHY_ALGORITHM);
MessageDigest mdPasswordPawd = MessageDigest.getInstance(CRYPTOGRAPHY_ALGORITHM);
mdPassword.update(salt);
mdPassword.update(password.getBytes(CHAR_SET));
mdPasswordPawd.update(password.getBytes(CHAR_SET));
digestedPassword = mdPassword.digest();
digestedPasswordPwd = mdPasswordPawd.digest();
byte[] resultBytes= new byte[1000];
System.arraycopy(digestedPassword, 11, resultBytes,0,digestedPassword.length);
if(Arrays.equals(resultBytes, digestedPasswordPwd)){
System.out.println("match");
}else{
System.out.println("no-match");
}
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("digestedPassword : "+digestedPassword);
System.out.println("digestedPasswordPwd : "+digestedPasswordPwd);
return digestedPassword;
}
}
堆棧跟蹤:
java.lang.ArrayIndexOutOfBoundsException
digestedPassword : [[email protected]
digestedPasswordPwd : [[email protected]
[[email protected]
at java.lang.System.arraycopy(Native Method)
at poc.HashedPassword.createPassword(HashedPassword.java:43)
at poc.HashedPassword.main(HashedPassword.java:23)
所以請幫助我如何去了解它
親切的問候
後堆棧跟蹤請! – ppeterka
感謝您的評論,更新了strack Trace。 –
'digestedPassword = mdPassword.digest();'後面的digestedPassword數組的長度是多少? –