Luffy Singh Luffy Singh - 14 days ago 12
Java Question

"UnsupportedEncodingException: SHA" when using RSA in Client-Server Application

I'm working on an instant messaging app in java. I tried to implement the RSA Algorithm as discussed in Demonstrate the use of RSA Public-key system to exchange messages that achieve confidentiality and integrity/authentication with its solution provided but the received message is not getting decrypted correctly.

enter image description here

Stack Trace: SHA
at java.lang.StringCoding.decode(
at java.lang.String.<init>(
at java.lang.String.<init>(
at mychatappp.networking.MessageListener.decryptMessage(

Server side run method:

ServerSocket server;
int listenPort = 8877;
WritableGUI gui;
LoginScreen sc = new LoginScreen();

public MessageListener(WritableGUI gui, int port){
this.listenPort = port;
this.gui = gui;
try {
server = new ServerSocket(port);
} catch (IOException ex) {
Logger.getLogger(MessageListener.class.getName()).log(Level.SEVERE, null, ex);
public void decryptMessage(InputStream inStream) throws IOException, NoSuchAlgorithmException
try {

//Create the Data input stream from the socket
DataInputStream dis = new DataInputStream(inStream);

//Get the key
ObjectInputStream in = new ObjectInputStream(new FileInputStream("KeyFile.xx"));

PrivateKey privatekey = (PrivateKey) in.readObject();
System.out.println("Key Used: " + in.toString());

//Initiate the cipher
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

int len = dis.readInt();
byte[] encryptedMsg = new byte[len];

System.out.println("Server - Msg Length: " + len);
System.out.println("Server - Encrypted: " + asHex(encryptedMsg));

// -Print out the decrypt String to see if it matches the original message.
byte[] plainText = cipher.doFinal(encryptedMsg);
System.out.println("Decrypted Message: " + new String(plainText, "SHA"));

} catch (Exception e) {

//Function to make the bytes printable (hex format)
public static String asHex(byte buf[]) {
StringBuilder strbuf = new StringBuilder(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10) {
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
return strbuf.toString();

public void run() {
Socket clientSocket;

try {
while((clientSocket = server.accept()) != null){
InputStream is = clientSocket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
if(line != null){

Where I am going wrong?


The problem is in this snippet new String(plainText, "SHA"). SHA is not a character encoding. I don't know how your string is encoded (i.e. how characters are converted to bytes and vice versa) but you probably want "UTF-8" here.