我正在尝试使用以下代码在Android上实现SHA-1
String name = "potato";
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(name.getBytes("iso-8859-1"), 0 , name.getBytes( "iso-8859-1").length );
Bytes[] sha1hash = md.digest();
textview.setText(sha1hash.toString());
但是当我运行这个代码两次时,它给了我不同的哈希码到“马铃薯”。据我所知,每次我运行程序时他们应该给我相同的答案,任何人都知道它可能是什么问题?
答案 0 :(得分:0)
您可以使用此代码获取SHA-1值。
public class sha1Calculate {
public static void main(String[] args)throws Exception
{
File file = new File("D:\\Android Links.txt");
String outputTxt= "";
String hashcode = null;
try {
FileInputStream input = new FileInputStream(file);
ByteArrayOutputStream output = new ByteArrayOutputStream ();
byte [] buffer = new byte [65536];
int l;
while ((l = input.read (buffer)) > 0)
output.write (buffer, 0, l);
input.close ();
output.close ();
byte [] data = output.toByteArray ();
MessageDigest digest = MessageDigest.getInstance( "SHA-1" );
byte[] bytes = data;
digest.update(bytes, 0, bytes.length);
bytes = digest.digest();
StringBuilder sb = new StringBuilder();
for( byte b : bytes )
{
sb.append( String.format("%02X", b) );
}
System.out.println("Digest(in hex format):: " + sb.toString());
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
尝试使用此链接获取任何帮助。
http://www.mkyong.com/java/how-to-generate-a-file-checksum-value-in-java/