• 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

    • Hopefully this will turn out to be the same/better than the old LOTR BFME series. Been nothing decent on the RTS scene for a long time now. Anything that does come out tends to be pretty mediocre. A new C&C Generals series would sell well
    • It make sense only if they want to hide the minority of changes of each new version
    • Trade up with Sterling Stock Picker now price dropped by 85% by Steven Parker Today's highlighted deal comes via our Apps + Software section of the Neowin Deals store, where you can save 85% off on a lifetime subscription to Sterling Stock Picker. Sterling Stock Picker (SSP) is an award-winning platform designed to make stock investing accessible to everyone, regardless of expertise. The software offers multiple methods to identify winning stocks that align with your personal values, investment preferences, and risk tolerance. By handling all the complex calculations, it allows you to focus on making informed investment decisions. The patent-pending North Star technology provides clear guidance on whether to buy, sell, hold, or avoid a particular stock. Ask Finley, your personal AI financial coach Finley is your personal AI financial coach providing real-time data access, strategic investment advice, risk assessment, and educational support to help you make informed decisions. Whether you're a seasoned investor or just starting, Finley is equipped to help you achieve your financial goals. Feel free to ask any questions about your portfolio or the stock market. PERSONALIZED FINANCIAL GUIDANCE Custom Recommendations: Get stock picks tailored to your risk tolerance, portfolio performance, and investment goals. Dynamic Insights: Access detailed financial, technical, earnings, growth, and risk analysis for smarter investing. ENHANCED PORTFOLIO MANAGEMENT Done-For-You Portfolio Builder: Easily construct a diversified portfolio based on your risk tolerance and investment goals. Analysis and Suggestions: Receive data-driven portfolio adjustments to optimize returns based on your risk acceptance score. Risk Assessment Overview: Understand your risk level and receive stock recommendations aligned with your investment strategy. STRATEGIC INVESTMENT ADVICE Stock Rockets: Discover top-performing companies with over 50% quarterly revenue growth and the highest North Star rankings. Concentrated Portfolio Strategy: Focus on high-potential stocks instead of broad diversification to maximize growth. Industry and Sector Insights: Stay ahead with detailed performance narratives and sector-specific trends. EDUCATIONAL SUPPORT & COMMUNITY Verbose Explanations: Break down complex financial concepts with in-depth explanations for beginners. Investment Strategies: Learn and apply various investment strategies with expert-backed insights. Community Chat Forum: Connect with fellow investors to share insights, ask questions, and discuss investment strategies. Build your Stock Portfolio in 3 easy steps! Discover Your Risk Tolerance: Take a quick 5-minute questionnaire to assess your ability to handle risk effortlessly. Search Stocks Aligned With Your Personal Values: Use an intuitive stock-picking interface to confidently find winning stocks. Build Your Portfolio: Utilize the Done-For-You Portfolio Builder to simplify investing and remove the guesswork. Good to know: Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: desktop or mobile Only available to new users Updates included A lifetime subscription to Sterling Stock Picker normally has a suggested price of $486, but you can pick it up for just $68.99 for a limited time - that represents a saving of $417 (85% off). For a full description, specs, and license info, click the link below. Sterling Stock Picker lifetime subscription for $68.99 (was $486) Although priced in U.S. dollars, this deal is available for digital purchase worldwide. We post these because we earn commission on each sale 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 Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • What if... both hardware AND software (due to their annual release cycles) got matching year release numbers? iPhone Pro 26 releases with iOS 26... For Macs, that'd be MacBook Pro 2026 releases with macOS 26 baked-in. With this proposal, the Major Version signifies latest-stable for both hardware and software, and gives them wiggle-room to optimize iOS releases for older hardware by a few months... while also incentivizing consumers to upgrade hardware for the latest-greatest software. (It would double-down on breaking their old support strategy but that's not a bad thing.)
    • Why doesn't Microsoft post updated the ISOs on the website, then have users download new install media? Too simple and obvious? Sometimes I swear Microsoft is a Government operation!!
  • Recent Achievements

    • Week One Done
      abortretryfail earned a badge
      Week One Done
    • First Post
      Mr bot earned a badge
      First Post
    • First Post
      Bkl211 earned a badge
      First Post
    • One Year In
      Mido gaber earned a badge
      One Year In
    • One Year In
      Vladimir Migunov earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      492
    2. 2
      +FloatingFatMan
      256
    3. 3
      snowy owl
      248
    4. 4
      ATLien_0
      226
    5. 5
      +Edouard
      190
  • Tell a friend

    Love Neowin? Tell a friend!