3

我正在尝试使用以下代码在 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());

但是当我两次运行这段代码时,它给了我不同的哈希码来“土豆”。据我所知,每次我运行程序时他们都应该给我相同的答案,有人知道这可能是什么问题吗?

4

1 回答 1

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/

于 2014-01-27T08:42:13.107 回答