【问题标题】:How can I calculate the SHA -1 hash of a string with a secret key in Android? [closed]如何在 Android 中计算带有密钥的字符串的 SHA -1 哈希? [关闭]
【发布时间】:2014-02-24 20:11:04
【问题描述】:

目前我正在研究 SHA-1 哈希算法 谁能建议我如何使用密钥开发这种算法?

谢谢:-)

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

谢谢。

【问题讨论】:

  • 散列(或消息摘要)没有密钥。您在寻找 MAC(消息验证码)算法吗?
  • mmmm Algorit-ham 流口水
  • 使用 SHA-1 算法,我应该传递字符串和密钥,这样我就可以加密字符串,也可以解密。
  • 如果您正在寻找一种密码算法(使用密钥加密和解密),那么 SHA-1 不适合您。目的哈希是单向的。从哈希中恢复原始文本几乎是不可能的。
  • Henry 谢谢 :-) 有没有办法使用 SHA-1 加密字符串?

标签: java android encryption sha1 secret-key


【解决方案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 !");

【讨论】:

  • 好吧,盐是一个随机字符串,你连接到你想要散列的字符串,以使其更难反转。例如。 sha1("要加密的纯文本" + "jdsdiuihfsduqihfsdiuif15454"). “jdsdiuihfsduqihfsdiuif15454”是你的盐。
  • 谢谢 :-) 让我知道 SHA-1 在哪里?我必须使用 sha-1 加密字符串。
  • 代码已更新。
  • 谢谢 :-) 有帮助并且有效 :-)
猜你喜欢
  • 2012-08-16
  • 2010-11-21
  • 2011-11-02
  • 2011-05-30
  • 1970-01-01
  • 2013-11-20
  • 1970-01-01
  • 2011-10-14
  • 2011-07-30
相关资源
最近更新 更多