SHA1 hashing not working as expected in Java












0















I am trying to write a small Java code to see how to properly use SHA1.



Following is the code snippet I came up with:



package dummyJavaExp;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Exp1 {

public static void main(String args) throws NoSuchAlgorithmException {
// TODO Auto-generated method stub
String str = "Hello there";
String hashstr = new String(MessageDigest.getInstance("SHA1").digest(str.getBytes()));
System.out.println("Encrypted value of " + str + " is: " + hashstr);
}

}


But the above code gives some weird characters as shown in the following output message when I run the above code:



Encrypted value of Hello there is: rlvU>?Þ¢‘4ónjòêìÎ


I thought the encrypted message will be some alphanumeric string.



Am I missing something in my code?










share|improve this question




















  • 3





    encrypted message is array of bytes, maybe you want base64

    – Iłya Bursov
    Jan 1 at 7:27











  • ok, so how do I get alphanumeric string. I want to use the generated hashes as keys in a hashmap. I can't use bytes as keys.

    – user3243499
    Jan 1 at 7:29











  • It depends on your purpouses. If you need to encrypt a value, you must use MessageDigest; once you get the encrypted byte array you can think to create a base64 string. If you just need a base64 string, well you can directly create it from the original string

    – Angelo Immediata
    Jan 1 at 7:31






  • 2





    1. Don't use String.getBytes(), which uses your platform default encoding. Use String.getBytes(StandardCharsets.UTF_8), which uses UTF_8 and is thus guaranteed to work the same way everywhere and support any character. 2. Encode the result using Base64 or Hex encoding.

    – JB Nizet
    Jan 1 at 7:32











  • Some puristic remark: the result is a hash value, not an encrypted value. The latter somehow suggests that you could decrypt it.

    – Henry
    Jan 1 at 7:36
















0















I am trying to write a small Java code to see how to properly use SHA1.



Following is the code snippet I came up with:



package dummyJavaExp;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Exp1 {

public static void main(String args) throws NoSuchAlgorithmException {
// TODO Auto-generated method stub
String str = "Hello there";
String hashstr = new String(MessageDigest.getInstance("SHA1").digest(str.getBytes()));
System.out.println("Encrypted value of " + str + " is: " + hashstr);
}

}


But the above code gives some weird characters as shown in the following output message when I run the above code:



Encrypted value of Hello there is: rlvU>?Þ¢‘4ónjòêìÎ


I thought the encrypted message will be some alphanumeric string.



Am I missing something in my code?










share|improve this question




















  • 3





    encrypted message is array of bytes, maybe you want base64

    – Iłya Bursov
    Jan 1 at 7:27











  • ok, so how do I get alphanumeric string. I want to use the generated hashes as keys in a hashmap. I can't use bytes as keys.

    – user3243499
    Jan 1 at 7:29











  • It depends on your purpouses. If you need to encrypt a value, you must use MessageDigest; once you get the encrypted byte array you can think to create a base64 string. If you just need a base64 string, well you can directly create it from the original string

    – Angelo Immediata
    Jan 1 at 7:31






  • 2





    1. Don't use String.getBytes(), which uses your platform default encoding. Use String.getBytes(StandardCharsets.UTF_8), which uses UTF_8 and is thus guaranteed to work the same way everywhere and support any character. 2. Encode the result using Base64 or Hex encoding.

    – JB Nizet
    Jan 1 at 7:32











  • Some puristic remark: the result is a hash value, not an encrypted value. The latter somehow suggests that you could decrypt it.

    – Henry
    Jan 1 at 7:36














0












0








0








I am trying to write a small Java code to see how to properly use SHA1.



Following is the code snippet I came up with:



package dummyJavaExp;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Exp1 {

public static void main(String args) throws NoSuchAlgorithmException {
// TODO Auto-generated method stub
String str = "Hello there";
String hashstr = new String(MessageDigest.getInstance("SHA1").digest(str.getBytes()));
System.out.println("Encrypted value of " + str + " is: " + hashstr);
}

}


But the above code gives some weird characters as shown in the following output message when I run the above code:



Encrypted value of Hello there is: rlvU>?Þ¢‘4ónjòêìÎ


I thought the encrypted message will be some alphanumeric string.



Am I missing something in my code?










share|improve this question
















I am trying to write a small Java code to see how to properly use SHA1.



Following is the code snippet I came up with:



package dummyJavaExp;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Exp1 {

public static void main(String args) throws NoSuchAlgorithmException {
// TODO Auto-generated method stub
String str = "Hello there";
String hashstr = new String(MessageDigest.getInstance("SHA1").digest(str.getBytes()));
System.out.println("Encrypted value of " + str + " is: " + hashstr);
}

}


But the above code gives some weird characters as shown in the following output message when I run the above code:



Encrypted value of Hello there is: rlvU>?Þ¢‘4ónjòêìÎ


I thought the encrypted message will be some alphanumeric string.



Am I missing something in my code?







java






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 25 at 23:39









halfer

14.6k758112




14.6k758112










asked Jan 1 at 7:25









user3243499user3243499

81211226




81211226








  • 3





    encrypted message is array of bytes, maybe you want base64

    – Iłya Bursov
    Jan 1 at 7:27











  • ok, so how do I get alphanumeric string. I want to use the generated hashes as keys in a hashmap. I can't use bytes as keys.

    – user3243499
    Jan 1 at 7:29











  • It depends on your purpouses. If you need to encrypt a value, you must use MessageDigest; once you get the encrypted byte array you can think to create a base64 string. If you just need a base64 string, well you can directly create it from the original string

    – Angelo Immediata
    Jan 1 at 7:31






  • 2





    1. Don't use String.getBytes(), which uses your platform default encoding. Use String.getBytes(StandardCharsets.UTF_8), which uses UTF_8 and is thus guaranteed to work the same way everywhere and support any character. 2. Encode the result using Base64 or Hex encoding.

    – JB Nizet
    Jan 1 at 7:32











  • Some puristic remark: the result is a hash value, not an encrypted value. The latter somehow suggests that you could decrypt it.

    – Henry
    Jan 1 at 7:36














  • 3





    encrypted message is array of bytes, maybe you want base64

    – Iłya Bursov
    Jan 1 at 7:27











  • ok, so how do I get alphanumeric string. I want to use the generated hashes as keys in a hashmap. I can't use bytes as keys.

    – user3243499
    Jan 1 at 7:29











  • It depends on your purpouses. If you need to encrypt a value, you must use MessageDigest; once you get the encrypted byte array you can think to create a base64 string. If you just need a base64 string, well you can directly create it from the original string

    – Angelo Immediata
    Jan 1 at 7:31






  • 2





    1. Don't use String.getBytes(), which uses your platform default encoding. Use String.getBytes(StandardCharsets.UTF_8), which uses UTF_8 and is thus guaranteed to work the same way everywhere and support any character. 2. Encode the result using Base64 or Hex encoding.

    – JB Nizet
    Jan 1 at 7:32











  • Some puristic remark: the result is a hash value, not an encrypted value. The latter somehow suggests that you could decrypt it.

    – Henry
    Jan 1 at 7:36








3




3





encrypted message is array of bytes, maybe you want base64

– Iłya Bursov
Jan 1 at 7:27





encrypted message is array of bytes, maybe you want base64

– Iłya Bursov
Jan 1 at 7:27













ok, so how do I get alphanumeric string. I want to use the generated hashes as keys in a hashmap. I can't use bytes as keys.

– user3243499
Jan 1 at 7:29





ok, so how do I get alphanumeric string. I want to use the generated hashes as keys in a hashmap. I can't use bytes as keys.

– user3243499
Jan 1 at 7:29













It depends on your purpouses. If you need to encrypt a value, you must use MessageDigest; once you get the encrypted byte array you can think to create a base64 string. If you just need a base64 string, well you can directly create it from the original string

– Angelo Immediata
Jan 1 at 7:31





It depends on your purpouses. If you need to encrypt a value, you must use MessageDigest; once you get the encrypted byte array you can think to create a base64 string. If you just need a base64 string, well you can directly create it from the original string

– Angelo Immediata
Jan 1 at 7:31




2




2





1. Don't use String.getBytes(), which uses your platform default encoding. Use String.getBytes(StandardCharsets.UTF_8), which uses UTF_8 and is thus guaranteed to work the same way everywhere and support any character. 2. Encode the result using Base64 or Hex encoding.

– JB Nizet
Jan 1 at 7:32





1. Don't use String.getBytes(), which uses your platform default encoding. Use String.getBytes(StandardCharsets.UTF_8), which uses UTF_8 and is thus guaranteed to work the same way everywhere and support any character. 2. Encode the result using Base64 or Hex encoding.

– JB Nizet
Jan 1 at 7:32













Some puristic remark: the result is a hash value, not an encrypted value. The latter somehow suggests that you could decrypt it.

– Henry
Jan 1 at 7:36





Some puristic remark: the result is a hash value, not an encrypted value. The latter somehow suggests that you could decrypt it.

– Henry
Jan 1 at 7:36












1 Answer
1






active

oldest

votes


















2














When you use String sample = new String(byte bytes) it will create a string with platform's default charset, your digest bytes may not have alphanumeric representation in that charset.



Try to use Base64 or HexString to display digest message.



For example in JAVA8:



You can encode your digest bytes to string with:



String hashstr = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA1").digest(str.getBytes("UTF-8")));


You can decode your Base64 with:



byte  digest = Base64.getDecoder().decode(hashstr); 





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53993754%2fsha1-hashing-not-working-as-expected-in-java%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    When you use String sample = new String(byte bytes) it will create a string with platform's default charset, your digest bytes may not have alphanumeric representation in that charset.



    Try to use Base64 or HexString to display digest message.



    For example in JAVA8:



    You can encode your digest bytes to string with:



    String hashstr = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA1").digest(str.getBytes("UTF-8")));


    You can decode your Base64 with:



    byte  digest = Base64.getDecoder().decode(hashstr); 





    share|improve this answer






























      2














      When you use String sample = new String(byte bytes) it will create a string with platform's default charset, your digest bytes may not have alphanumeric representation in that charset.



      Try to use Base64 or HexString to display digest message.



      For example in JAVA8:



      You can encode your digest bytes to string with:



      String hashstr = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA1").digest(str.getBytes("UTF-8")));


      You can decode your Base64 with:



      byte  digest = Base64.getDecoder().decode(hashstr); 





      share|improve this answer




























        2












        2








        2







        When you use String sample = new String(byte bytes) it will create a string with platform's default charset, your digest bytes may not have alphanumeric representation in that charset.



        Try to use Base64 or HexString to display digest message.



        For example in JAVA8:



        You can encode your digest bytes to string with:



        String hashstr = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA1").digest(str.getBytes("UTF-8")));


        You can decode your Base64 with:



        byte  digest = Base64.getDecoder().decode(hashstr); 





        share|improve this answer















        When you use String sample = new String(byte bytes) it will create a string with platform's default charset, your digest bytes may not have alphanumeric representation in that charset.



        Try to use Base64 or HexString to display digest message.



        For example in JAVA8:



        You can encode your digest bytes to string with:



        String hashstr = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA1").digest(str.getBytes("UTF-8")));


        You can decode your Base64 with:



        byte  digest = Base64.getDecoder().decode(hashstr); 






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 1 at 7:45

























        answered Jan 1 at 7:37









        Ehsan MashhadiEhsan Mashhadi

        751618




        751618
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53993754%2fsha1-hashing-not-working-as-expected-in-java%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Mossoró

            Error while reading .h5 file using the rhdf5 package in R

            Pushsharp Apns notification error: 'InvalidToken'