我有以下要求。
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("r14@17*$"));
}
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 : [B@9980d5
digestedPasswordPwd : [B@1d95492
[B@9980d5
at java.lang.System.arraycopy(Native Method)
at poc.HashedPassword.createPassword(HashedPassword.java:43)
at poc.HashedPassword.main(HashedPassword.java:23)
所以请帮助我如何去做
亲切的问候
最佳答案
这条线有问题:
System.arraycopy(digestedPassword, 11, resultBytes,0,digestedPassword.length);
它尝试从 digestedPassword
中从位置 11 开始复制 digestedPassword.length
字节。因此它尝试复制不存在的 11 个字节。
试试这个:
System.arraycopy(digestedPassword, 11, resultBytes,0,digestedPassword.length-11);
复制自API doc for System.arraycopy :
Otherwise, if any of the following is true, an IndexOutOfBoundsException is thrown and the destination is not modified:
The srcPos argument is negative.
The destPos argument is negative.
The length argument is negative.
srcPos+length is greater than src.length, the length of the source array.
destPos+length is greater than dest.length, the length of the destination array.
关于java - 对密码进行哈希处理并与 MD5 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12909967/