• 0

why is my java not working?


Question

hi! I have been coding for a few hours most has gone well untill now and i have hit a wall...

im making an ecrypted chat program and the first person encrypts a string with another string.... the encrypted string is then sent... the encrypted string is then encrypted with a string and sent back the plan is to then decrypt this string and send it back once more but my code has stopped working here.... I have commented where it works and where it doesn't


try {
System.out.println("test..1...2..." + stk); //this happens the varible stk is there and working
DesEncrypter encrypters = new DesEncrypter(stk); //I assume these dont work
String decrypteds = encrypters.decrypt(inputLine); // ^^^^^^^^^^^^^^^^^^^^^^
System.out.println("is working? ---> " + decrypteds); //this does not happen <----------
out.println(decrypteds);
System.out.println("is working? ---> " + decrypteds);
System.out.println("thisith your encryption removed ---> " + decrypteds);
sen = 0;
stk = null;
} catch (Exception e) {

}
[/CODE]

Link to comment
https://www.neowin.net/forum/topic/1115139-why-is-my-java-not-working/
Share on other sites

15 answers to this question

Recommended Posts

  • 0

Remove your empty try-catch and you might see what the exception is. This is full of useful information like the nature of the error and where it happened. Here, I don't see where "inputLine" comes from so it might be null, causing an error. Otherwise I don't know what this "DesEncrypter" class is, is it standard in the Java library?

In general you should be running your programs with a debugger attached and have the debugger break immediately on every exception. And stop hiding errors with try-catch statements. You want to find your errors, not pretend like everything works.

  • 0
  On 27/10/2012 at 02:02, Dr_Asik said:

Remove your empty try-catch and you might see what the exception is. This is full of useful information like the nature of the error and where it happened. Here, I don't see where "inputLine" comes from so it might be null, causing an error.

In general you should be running your programs with a debugger attached and have the debugger break immediately on every exception. And stop hiding errors with try-catch statements. You want to find your errors, not pretend like everything works.

it wont let me use "DesEncrypter encrypters =newDesEncrypter(stk)" without throwing and catching :( i dont like them either it could be the inputLine but its not null I have checked (system.out)

i have also worked out it is 100% this line.... "String decrypteds = encrypters.decrypt(inputLine);" hmmm what can it be :/ i use this in other places so i dont know

also no its not a standard class but its all there and was working encrypting and decrypting up to this point

  • 0
  On 27/10/2012 at 02:10, SPEhosting said:

it wont let me use "DesEncrypter encrypters =newDesEncrypter(stk)" without throwing and catching :(

Well there's your error then. You're passing in something invalid in that constructor. Maybe it's null, maybe it's not initialized, maybe DesEncrypter doesn't like getting instantiated with new and has a factory method you should use instead, I don't know, but there's the error. If you were to let it propagate and read what it says, it would tell you the nature of the error, and possibly even suggest how to fix it.

You're not fixing anything by using a try-catch. All you do is allow execution to continue in the body of the catch (which is empty in your case) after the exception is thrown. Basically, here's what happens when you currently execute your code:

   try {
System.out.println("test..1...2..." + stk);
DesEncrypter encrypters = new DesEncrypter(stk); // exception thrown; execution breaks here and resumes at the catch
}
catch (Exception e) { // exception caught
// nothing to do here! exception ignored, we don't know what it said, so we have no way of diagnosing the issue
}
[/CODE]

You could see this yourself, line by line, by running your program in a [b]debugger[/b], like you certainly have if you're using any common Java IDE (Eclipse, Netbeans, IntelliJ etc)

If you really insist on catching your exceptions and not using the most useful tools to find bugs (i.e. a debugger), you should at the very least not entirely ignore them and display their message on the console, i.e.

[CODE]
try {
// code that doesn't work and throws exceptions goes here
}
catch (Exception e) {
system.out.println(e.getMessage()); // let's see what the problem was!
}
[/CODE]

  • 0
  On 27/10/2012 at 02:43, Dr_Asik said:

If you really insist on catching your exceptions and not using the most useful tools to find bugs (i.e. a debugger), you should at the very least not entirely ignore them and display their message on the console, i.e.


try {
// code that doesn't work and throws exceptions goes here
}
catch (Exception e) {
system.out.println(e.getMessage()); // let's see what the problem was!
}
[/CODE]

it didnt throw back any message :(

  • 0
  On 27/10/2012 at 13:46, SPEhosting said:

AHHH I GOT IT !!! given final block not properly padded!!!! .... what does that mean :/

i got something do you know what i means?

if possible can you paste complete method if not too lengthy!

Yes. With stack trace, i can tell you the info. it's the final thing that one can check for any failures in prgm

  • 0
  On 27/10/2012 at 13:48, nitins60 said:

if possible can you paste complete method if not too lengthy!

Yes. With stack trace, i can tell you the info. it's the final thing that one can check for any failures in prgm

http://www.java2s.com/Code/Java/Security/EncryptingwithDESUsingaPassPhrase.htm

this is the method for encrypting ... should tell you what you need to know :p

  • 0
  On 27/10/2012 at 14:01, vcfan said:

check if encrypted message has escape characters like \r or \n, which could mess up the decryption routine and make it not work properly or at all

ermmm it has an =

when its encrypted there should be nothing but dashes in the final string .... maybe thats the problem ?

  • 0
  On 27/10/2012 at 14:09, SPEhosting said:

ermmm it has an =

when its encrypted there should be nothing but dashes in the final string .... maybe thats the problem ?

i meant the message before it is encrypted,

try creating a new project to test out the encryption and decryption only. try encrypting a string without escape characters. do it manually,feed it straight a-z characters, let it encrypt, then decrypt. then test it again with escape characters, and see if your decrypted outputs work correctly both ways. this will help you isolate the problem, if your problem has to do with your crypto routines and libraries.

  • 0

here is all my code lol ::::

SwingChatServer.java


import java.awt.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.spec.*;
import java.util.UUID;
import chat.*;
public class SwingChatServer extends SwingChatGUI
{
PrintWriter out;
BufferedReader in;
BufferedReader stdin;
String inputLine, outputLine, collect;
public ButtonHandler bHandler = new ButtonHandler();
public ButtonHandler bH = new ButtonHandler();
public String rgk;
public String stk;
public String lls;
public int sen;
public SwingChatServer (String title)
{
super (title);
bHandler = new ButtonHandler ();
sendButton.addActionListener (bHandler);
synco.addActionListener (bH);
keymaker();
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent event)
{

if(event.getSource()==sendButton)
{
outputLine = txArea.getText ();
System.out.println ("Server > " + outputLine);
try {

DesEncrypter encrypter = new DesEncrypter(rgk);
String encrypted = encrypter.encrypt(outputLine);
System.out.println("" + encrypted);
out.println (encrypted);

} catch (Exception e) {
//out.println (outputLine);
}
}
if(event.getSource()==synco)
{
System.out.println("YOURNER WISHES TO MAKE THIS A PRIVATE MATTER, CLICK SYNC TO ENCRYPT ALL MESSAGES");
stk = rgk;
System.out.println("thishe key which will encrypt the new key ---> " + stk);
keymaker();
System.out.println("thishe key which will be encrypted ---> " + rgk);
try {
DesEncrypter encrypter = new DesEncrypter(stk);
String encrypted = encrypter.encrypt(rgk);
System.out.println("thisow the key looks encrypted ---> " + encrypted);
out.println (encrypted);
out.println("test");
sen = 1;
} catch (Exception e) {
System.out.println("error
}

}

}
}

public void run () throws IOException
{
ServerSocket serverSocket = null;

try
{
serverSocket = new ServerSocket (4444);
}
catch (IOException e)
{
System.err.println ("Could not listen on port: 4444.");
System.exit (1);
}
Socket clientSocket = null;
try
{
clientSocket = serverSocket.accept ();
}
catch (IOException e)
{
System.err.println ("Accept failed.");
System.exit(1);
}
out = new PrintWriter (clientSocket.getOutputStream (), true);
in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
//stdin = new BufferedReader (new InputStreamReader (System.in));
out.println ("Welcome to the Chat Server\n");
while ((inputLine = in.readLine ()) != null)
{

lls = inputLine;
if (sen == 1)
{
System.out.println("thisld be the encrypted, encryption ---> " + lls);

try {
System.out.println("test..1+ inputLine + " and now for stk " + stk);
DesEncrypter encrypters = new DesEncrypter(stk);
System.out.println("peeka);
String decrypteds = encrypters.decrypt(inputLine);
System.out.println(decrypteds);
//sen = 0;
//stk = null;
} catch (Exception e) {
System.out.println(e.getMessage());
}
} else {

System.out.println ("Server < " + inputLine);
try {
DesEncrypter encrypter = new DesEncrypter(rgk);

String decrypted = encrypter.decrypt(inputLine);
System.out.println("" + decrypted);
rxArea.setText (decrypted);
} catch (Exception e) {
}
collect = (collect +" \n"+ inputLine);
rxArea.setText (collect);

}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
public static void main(String[] args) //throws IOException
{

SwingChatServer f = new SwingChatServer ("Chat Server Program");

f.pack ();
f.setVisible(true);
try
{
f.run ();
}
catch (IOException e)
{
System.err.println("Couldn'tfor the connection.");
System.exit(1);
}
}
public void keymaker()
{

String uuid = UUID.randomUUID().toString();
rgk = uuid;
}
}
[/CODE]

SwingChatClient.java

[CODE]
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.spec.*;
import java.util.UUID;
import chat.*;
public class SwingChatClient extends SwingChatGUI
{
static Socket socket = null;
static PrintWriter out = null;
static BufferedReader in = null;
public ButtonHandler bHandler, bH;
public String rgk;
public String stk;
public String lls;
public int sen;

public SwingChatClient (String title)
{
super (title);
bHandler = new ButtonHandler();
bH = new ButtonHandler();
sendButton.addActionListener( bHandler );
synco.addActionListener( bH );
keymaker();
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if (event.getSource()==sendButton)
{
String outputLine;
outputLine = txArea.getText ();
System.out.println ("Client > " + outputLine);
out.println (outputLine);
}
if (event.getSource()==synco)
{
System.out.println("YOURNER WISHES TO MAKE THIS A PRIVATE MATTER, CLICK SYNC TO ENCRYPT ALL MESSAGES");
stk = rgk;
System.out.println("thishe key which will encrypt the new key " + stk);


try {
DesEncrypter encrypter = new DesEncrypter(stk);
String encrypted = encrypter.encrypt(lls);
System.out.println("" + encrypted);
out.println (encrypted);
sen = 1;
} catch (Exception e) {
System.out.println("error
}
}
}
}
public void run () throws IOException
{
try
{
socket = new Socket ("localhost", 4444);
out = new PrintWriter (socket.getOutputStream (), true);
in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
}
catch (UnknownHostException e)
{
System.err.println ("Don't know about host: .");
System.exit(1);
}
catch (IOException e)
{
System.err.println ("Couldn't get I/O for the connection to: .");
System.exit (1);
}
String fromServer;
while ((fromServer = in.readLine ()) != null)
{
System.out.println ("this should be encrypted " + fromServer);
lls = fromServer;

if (sen == 1)
{

try {
DesEncrypter encrypter = new DesEncrypter(stk);
String decrypted = encrypter.decrypt(fromServer);
rgk = decrypted;
sen = 0;
stk = null;
System.out.println("hello;
} catch (Exception e) {
}

} else {
try {
DesEncrypter encrypter = new DesEncrypter(rgk);

String decrypted = encrypter.decrypt(fromServer);
System.out.println("hmm+ decrypted);
rxArea.setText (decrypted);
} catch (Exception e) {
}
if (fromServer.equals ("Bye.")) break;
}
}
out.close();
in.close();
socket.close();
}
public static void main(String[] args)
{
SwingChatClient f = new SwingChatClient ("Chat Client Program");

f.pack ();
f.setVisible(true);
try
{
f.run ();
}
catch (IOException e)
{
System.err.println("Couldn'tfor the connection to:");
System.exit(1);
}
}
public void keymaker()
{

String uuid = UUID.randomUUID().toString();
rgk = uuid;
}
}
[/CODE]

SwingChatGUI.java

[CODE]
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class SwingChatGUI extends JFrame
{
public JButton sendButton, synco;
public JTextArea txArea, rxArea;

public Container container;

public JPanel n1, s1;


public SwingChatGUI (String title)
{
super (title);

container = getContentPane();
container.setLayout( new FlowLayout() );

txArea = new JTextArea (6, 40);

rxArea = new JTextArea (6, 40);

sendButton = new JButton ("Send");
synco = new JButton ("sync");

container.add (rxArea);
container.add (txArea);
container.add (sendButton);
container.add (synco);
}

public static void main (String[] args)
{
Frame f = new SwingChatGUI ("Chat Program");
f.pack ();
f.setVisible(true);
}
}
[/CODE]

the chat package......is next....

DesEncrypter.java

[CODE]
package chat;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class DesEncrypter {
Cipher ecipher;
Cipher dcipher;
byte[] salt = { (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32, (byte) 0x56, (byte) 0x35,
(byte) 0xE3, (byte) 0x03 };
public DesEncrypter(String passPhrase) throws Exception {
int iterationCount = 2;
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
}
public String encrypt(String str) throws Exception {
return new BASE64Encoder().encode(ecipher.doFinal(str.getBytes()));
}
public String decrypt(String str) throws Exception {
return new String(dcipher.doFinal(new BASE64Decoder().decodeBuffer(str)));
}
}
[/CODE]

This topic is now closed to further replies.
  • Posts

    • Also good for Debugging or troubleshooting your game.. i dont get it why nvidia app or amd does not show this data.. if steam can do it..
    • Microsoft reportedly planning to lay off thousands of employees, mostly in sales by Usama Jawad Back in May 2025, Microsoft decided to lay off 3% of its workforce, which amounted to roughly 6,000 employees. It claimed that this decision allowed it to implement better organizational changes in a "dynamic marketplace". Now, a new report claims that the Redmond tech firm is planning to lay off thousands more next month. Citing unnamed sources, Bloomberg reports that as the company continues investing heavily in its AI ventures, it is about to announce layoffs of thousands of workers as early as next month. This reduction in workforce will primarily affect sales teams, but they won't be the only ones affected. That said, the sources did mention that the timing for this announcement may change. This move, if true, won't be entirely surprising. In April 2025, Microsoft announced that it will be relying more on third-party firms to sell its software to small- and medium-sized customers. It's currently unclear how many employees will be impacted by this change, but even if the layoff percentage is in the single digits, it would still be significant as it would be impacting the professional careers of thousands. The May 2025 layoffs primarily impacted engineering and product teams. The other major round of layoffs prior to this was the decision to eliminate 10,000 jobs back in January 2023. Those represented 5% of the total workforce at that time, with numerous teams, including the one leading Mixed Reality (MR) efforts, being heavily impacted. It is interesting to note that if the timing of the announcement for layoffs is accurate, it would be soon after Microsoft closes its fiscal year at the end of June 2025. Although we'll get financial reports for the latest quarter soon after too, one has to wonder what the human cost of profit is, as Microsoft continues to report billions of dollars in revenue every quarter. Source: Bloomberg (paywall)
    • Ah .. lockout for suspicious activity. I bet they uploaded the SanDisk utility detected as malware
    • Microsoft 365 will soon disable outdated authentication protocols for file access by Usama Jawad On a fairly regular basis, Microsoft disables outdated protocols that are used to access its services. In the past few years, the company has deprecated Basic Auth in Exchange Online and cut access to Outlook for third-party apps relying on this protocol. Now, it has decided to get rid of old authentication protocols for file access across Microsoft 365 services. As reported by Bleeping Computer, Microsoft has posted a message on its Microsoft 365 Admin Center. Starting from mid-July 2025, the company will begin disabling legacy authentication protocols used to access files across Microsoft 365 and Office apps, SharePoint, and OneDrive. Essentially, applications or services which use the Relying Party Suite (RPS) or FrontPage Remote Procedure Call (FPRPC) will to perform browser-based authentication to perform open operations on Office files will no longer be able to do so. As expected, this is primarily being done to improve the cybersecurity posture of various services. Microsoft states that RPS can be brute-forced and phished with relative ease as it is fairly outdated. Similarly, FPRPC is typically used for remote web page authoring and it is susceptible to exploitation through various vulnerabilities too. As such, both of these protocols will be disabled by default starting from mid-July 2025, with the rollout of this change targeting completion by August 2025. The Redmond tech giant will update the protocol baseline by default without mandating any licensing changes for customers. In addition, once these modifications are rolled out, Microsoft 365 will require admin consent to get third-party access to files and sites. IT admins can view the guidance available here to configure admin consent workflows. Microsoft says that these changes align with the principles of its Secure Future Initiative (SFI). Earlier today, it announced the rollout of improved security defaults for Windows 365 citing the same reasons too.
  • Recent Achievements

    • First Post
      Fuzz_c earned a badge
      First Post
    • First Post
      TIGOSS earned a badge
      First Post
    • Week One Done
      slackerzz earned a badge
      Week One Done
    • Week One Done
      vivetool earned a badge
      Week One Done
    • Reacting Well
      pnajbar earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      704
    2. 2
      ATLien_0
      283
    3. 3
      Michael Scrip
      216
    4. 4
      +FloatingFatMan
      195
    5. 5
      Steven P.
      131
  • Tell a friend

    Love Neowin? Tell a friend!