-1

Currently I am working on SHA-1 Hash Algoritham can any one suggest me how can such algo be developed using the secret key?

Thanks :-)

Similar question : How can I calculate the SHA-256 hash of a string with a secret key in Android?.

Thanks.

Community
  • 1
  • 1
Swift
  • 829
  • 2
  • 12
  • 33
  • 4
    A hash (or message digest) does not have a secret key. Are you looking for a MAC (message authentication code) algorithm? – Henry Feb 24 '14 at 09:01
  • mmmm Algorit-ham *drool* – weston Feb 24 '14 at 09:16
  • Using SHA-1 Algoritham where i should pass the string and secret key so i can encrypt the string and also can decrypt. – Swift Feb 24 '14 at 09:18
  • If you are looking for a cipher algorithm (encrypt and decrypt with a secret key) than SHA-1 is not for you. A hash on puropose is one-way. It is practically impossible to recover the original text from the hash. – Henry Feb 24 '14 at 09:40
  • Henry thanks :-) Are there any way to encrypt string using SHA-1 ? – Swift Feb 24 '14 at 09:41
  • It's like you are asking how to fix a screw with a hammer. It simply isn't the right tool. – Henry Feb 24 '14 at 09:47

1 Answers1

1

Are you talking of a salt or something ? I think you'd like to use an encryption you can resverse such as 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");
  }

A simple way to use it would be

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 !");
Manitoba
  • 8,522
  • 11
  • 60
  • 122