如何在Android中使用密钥计算字符串的SHA -1哈希值?

时间:2014-02-24 08:57:41

标签: java android encryption sha1 secret-key

目前我正在研究SHA-1 Hash Algoritham 任何人都可以建议我如何使用密钥开发这样的算法?

谢谢: - )

类似的问题: How can I calculate the SHA-256 hash of a string with a secret key in Android?

感谢。

1 个答案:

答案 0 :(得分:1)

你在谈论盐还是什么?我想你想使用可以反转的加密技术,比如AES。

  public static byte[] encrypt(String plainText, String encryptionKey) throws Exception   
  {
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
    SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
    cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(new byte[cipher.getBlockSize()]));
    return cipher.doFinal(plainText.getBytes("UTF-8"));
  }

  public static String decrypt(byte[] cipherText, String encryptionKey) throws Exception
  {
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
    SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
    cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(new byte[cipher.getBlockSize()]));
    return new String(cipher.doFinal(cipherText),"UTF-8");
  }

使用它的一种简单方法是

String plaintext = "My plain text.";
String encryptionKey = "Super secret encryption key";
Log.d("AES", "Plain text is : " + plaintext );

byte[] cipher = encrypt(plaintext, encryptionKey);
Log.d("AES", "Encrypted string is : " + new String(cipher));

String decrypted = decrypt(cipher, encryptionKey);
Log.d("AES", "Decrypted string is : " + decrypted);

if (plaintext.equals(decrypted)) Log.d("AES", "Strings match !");