How to Calculate SHA-256 for a String

Computer information security often requires that strings, which are just a series of characters like a word or sentence, be hashed. Hashing is similar to encryption, except that a hash cannot be reversed, whereas encryption can be decrypted. The most common use for hashing a string is for protecting passwords. Normally, a computer system will not store your actual password. Instead, it will store the hash of your password, so that an attacker who gains illegal access to the database will still not acquire user passwords. Strings are hashed by hash algorithms. One popular hash algorithm is the SHA-256.

Instructions

    • 1

      Run the mhash function in PHP, using the MHASH_SHA256 constant, like below:

      mhash (MHASH_SHA256, "your string here");

      Store or print the output by running the file this code is in.

    • 2

      Type the following code into your Java program:

      getSHA256Hash("your string here");

      public byte[] getSHA256Hash(String password) {
      MessageDigest digest=null;
      try {
      digest = MessageDigest.getInstance("SHA-256");
      } catch (NoSuchAlgorithmException e1) {
      e1.printStackTrace();
      }
      digest.reset();
      return digest.digest(password.getBytes());
      }

      Compile and run your class to get the output from this code.

    • 3

      Type the following code into your Python program:

      import hmac
      import hashlib
      dig = hmac.new(b'1234567890', msg='your string here', digestmod = hashlib.sha256) .digest()

      Store or print the output by running the file this code is in.

Tips & Warnings

  • Unless it's for fun or homework, never try to implement your own hashing algorithm. It's a notoriously complex field within computer science, so it's very easy to make mistakes in your algorithm, and the stakes are normally very high. Just use your language's built-in implementation.

Related Searches:

References

Resources

Comments

Related Ads

Featured