Search code examples
javasha

SHA Encoding Error "UnsupportedEncodingException: UTF­8"


Below is my JAVA code, I am trying to encode string into SHA1 encoding but i am getting below Error.

java.io.UnsupportedEncodingException: UTF­8

at java.lang.StringCoding.encode(StringCoding.java:341) at java.lang.String.getBytes(String.java:918) at sample.SHAEncoding.getSHA(SHAEncoding.java:20) at sample.SHAEncoding.main(SHAEncoding.java:34)

import java.security.MessageDigest;

public class SHAEncoding {
    private static char[] hexits = "0123456789ABCDEF".toCharArray();

    public static String getSHA(String data) throws Exception {
    MessageDigest md = null;
    byte[] ba = null;
    md = MessageDigest.getInstance("SHA");
    md.update(data.getBytes("UTF­8"));
    ba = md.digest();

    StringBuffer sb = new StringBuffer(ba.length * 2);
    for (int i = 0; i < ba.length; i++) {
        sb.append(hexits[(((int) ba[i] & 0xFF) / 16) & 0x0F]);
        sb.append(hexits[((int) ba[i] & 0xFF) % 16]);
    }
    return sb.toString();
}

public static void main(String args[]){
    String SessionID = "2K6VB0UAZV33C5KTKXDV";
    try{
        String PIN = getSHA(SessionID + getSHA("xyz"+"1234").toLowerCase()).toUpperCase();
        System.out.println("PIN ===>>> "+PIN);
       }catch(Exception e){
        e.printStackTrace();
       }
 }
}

Solution

  • issue resolved by replacing "UTF8" by "UTF-8". Thankyou all for your reply.