• 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

    • Download The Inclusion Equation: Leveraging Data & AI (worth $21) for free by Steven Parker Claim your complimentary eBook worth $21 for free, before the offer ends on June 24. The Inclusion Equation is a comprehensive, one-of-a-kind guide to merging DEI and employee wellbeing concepts with data analytics and AI. In this book, renowned thought leader and professional keynote speaker Dr. Serena Huang explains exactly how to quantify the effectiveness of new talent strategies by connecting them to a firm ROI estimate, enabling readers to approach and win the favor of higher-ups in any organization with the same effectiveness that marketing and financial departments do. This book is written in a style that is appealing and accessible to all readers regardless of technical background, but with enough depth to provide real insight and strategies. Dr. Serena H. Huang distills her 10 years of Fortune 500 people analytics leadership experience into tools and framework you can leverage to measure and improve DEI and wellbeing in your workplace. Some of the topics explored in this book include: Attract and retain top talent, including Gen Z and Millennials, with tailored DEI and wellbeing strategies Quantifying not only a talent strategy's perceived initial effect on an organization, but also its improvement and expansion over time Turning DEI and wellbeing from illusive corporate concepts to quantifiable metrics Harness the power of AI to create synchronized DEI and wellbeing strategies that maximize ROI Getting serious attention from your CEO and CFO by quantifying HR initiatives Using data storytelling to demonstrate the business impact of DEI and wellbeing Preparing for the future by understanding the role of AI in creating an inclusive and healthy workplace The Inclusion Equation is a complete guide for DEI and wellbeing, covering getting started in measurement to using storytelling to influence leadership. This is the contemporary playbook for any organization intending to substantially improve their diversity, equity, inclusion, and employee wellbeing by leveraging data & AI. This book is also perfect for any data analytics professionals who want to understand how to apply analytics to issues that keep their CEOs up at night. Whether you are a data expert or data novice, as long as you are serious about improving DEI and wellbeing, this book is for you. This free to download offer expires June 24. How to get it Please ensure you read the terms and conditions to claim this offer. Complete and verifiable information is required in order to receive this free offer. If you have previously made use of these free offers, you will not need to re-register. While supplies last! Download The Inclusion Equation: Leveraging Data & AI (worth $21) for free Offered by Wiley, view other free resources The below offers are also available for free in exchange for your (work) email: AI and Innovation ($21 Value) FREE – Expires 6/11 Unruly: Fighting Back when Politics, AI, and Law Upend [...] ($18 Value) FREE - Expires 6/17 SQL Essentials For Dummies ($10 Value) FREE – Expires 6/17 Continuous Testing, Quality, Security, and Feedback ($27.99 Value) FREE – Expires 6/18 VideoProc Converter AI v7.5 for FREE (worth $78.90) – Expires 6/18 Macxvideo AI ($39.95 Value) Free for a Limited Time – Expires 6/22 Excel Quick and Easy ($12 Value) FREE – Expires 6/24 The Inclusion Equation: Leveraging Data & AI ($21 Value) FREE – Expires 6/24 Microsoft 365 Copilot At Work ($60 Value) FREE – Expires 6/25 Natural Language Processing with Python ($39.99 Value) FREE – Expires 6/25 How to Engage Buyers and Drive Growth in the Age of AI ($22.95 Value) FREE – Expires 7/1 Using Artificial Intelligence to Save the World ($30.00 Value) FREE – Expires 7/1 Essential: How Distributed Teams, Generative AI, [...] ($18.00 Value) FREE – Expires 7/2 The Chief AI Officer's Handbook: Master AI leadership with strategies to innovate, overcome challenges, and drive business growth ($9.99 Value) FREE for a Limited Time – Expires 7/2 The Ultimate Linux Newbie Guide – Featured Free content Python Notes for Professionals – Featured Free content Learn Linux in 5 Days – Featured Free content Quick Reference Guide for Cybersecurity – Featured Free content We post these because we earn commission on each lead so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin The above deal not doing it for you, but still want to help? Check out the links below. Check out our partner software in the Neowin Store Buy a T-shirt at Neowin's Threadsquad Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: An account at Neowin Deals is required to participate in any deals powered by our affiliate, StackCommerce. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through the branded deals site.
    • It's basically been a rite of passage to blow up your first WSUS server by trying to sync the drivers database. Anyone who has done this has certainly seen the tens of thousands of driver packages and asked "what is all of this literal garbage?". Seems Microsoft is asking the same question. I do hope they won't take it too far and start removing drivers needed to run legacy systems, but there's definitely a happy medium to be found between "only the latest versions for actively supported hardware" and "every version of every driver ever for all time".
    • Stable..... No, he isn't..
    • Of course the sales are bad. Who even asked for a thinner phone with way less battery? Lightness? It's still a giant brick, it's just a thinner giant brick. It makes no sense at all. Making folding phones thinner, now that does make sense. Because when folded, the thinner it is unfolded, the more usable and pocketable it is when folded. You already expect worse battery at expense of actually being more pocketable. Galaxy Flip, when folded is half the size of S Ultra models and about as thick. That does make a big difference when fitting it in a pocket. But the phone that's as big as Ultra, making it thinner, you don't really solve anything, it's still a giant slab that barely fits into a pocket. All the "Mini" phones made way more sense than this thin crap. Especially now that it's literally impossible to find a phone smaller than 6.5". My dad only needs phone for calls and SMS and he doesn't want to go with smartphone because they are all so massive. Especially cheaper ones. Like, he'd be fine with Galaxy A06 for all he cares in terms of hardware, but it only comes in giant 6.7" format. It's useless. Or is he suppose to find a 800€ old gen iPhone Mini or Zenfone? He doesn't even need those stupid specs and such stupid price. And then you see old people fumbling around with giant smartphones and they don't even need 3/4 of features on them.
  • Recent Achievements

    • First Post
      emptyother earned a badge
      First Post
    • Week One Done
      Crunchy6 earned a badge
      Week One Done
    • One Month Later
      KynanSEIT earned a badge
      One Month Later
    • One Month Later
      gowtham07 earned a badge
      One Month Later
    • Collaborator
      lethalman went up a rank
      Collaborator
  • Popular Contributors

    1. 1
      +primortal
      664
    2. 2
      ATLien_0
      270
    3. 3
      Michael Scrip
      218
    4. 4
      Steven P.
      161
    5. 5
      +FloatingFatMan
      157
  • Tell a friend

    Love Neowin? Tell a friend!