如何用sha1和Base64编码传递?

时间:2015-09-15 12:39:18

标签: android base64 encode sha1

我需要提供sha1和Base64的哈希密码,如下所示:

base64(sha1(password))

这是我试过的:

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 password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    md.update(password.getBytes("iso-8859-1"), 0, password.length());
    byte[] sha1hash = md.digest();
    return convertToHex(sha1hash);
}

而不是:

String encodedPass = Base64.encodeToString(password.getBytes(), Base64.DEFAULT);

但是这不能正常工作...... 也许有一些错误或更简单的方法吗?

1 个答案:

答案 0 :(得分:0)

接下来的问题是: convertToHex(sha1hash) - 返回字符串,但为了正确使用Base64我需要把byte []放在这里:

Base64.encodeToString(byte[], Base64.DEFAULT);

所以解决方案非常简单:

public static String encodePassword(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        String result;
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(password.getBytes("iso-8859-1"), 0, password.length());
        byte[] sha1hash = md.digest();
        result = Base64.encodeToString(sha1hash, Base64.DEFAULT);
        result = result.substring(0, result.length()-1);
        return result;
    }