• 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

    • It's been an age since I did desktop support, but here goes: You have an issue with Windows 11, which is fair.  You are using a freeware 3rd party app to make modifications to the default Windows 11.  Since an update, this 3rd party application no longer plays nice with Windows 11.  And this is somehow Windows 11's fault? Sorry, not buying that this is a Windows 11 problem... it's a customization issue that has just appeared, but standard 3rd party support.   Clearly you're upset.  You can't make Windows do anything, just like you can't make MacOS run Explorer or Linux run Nintendo games natively.  And I know people are going to say "sure, it's possible..." but those aren't defining elements of the OS.  You can't have animated backgrounds in Windows 11 natively -- so it's trash amirite??? I did quick searches about changing the default fonts and there are ways to do it, and clearly 3rd party freeware apps can do it (basically my guess is they're making registry changes on your behalf) and clearly they're having issue.   You can make your computer do a lot of things, but sometimes you get what you pay for. Did a quick search and don't see an easy option in Windows 10 either.  Some of these links - ironically - are for Windows 10.  They still apply. Here's a video tutorial of how it can be done without a 3rd party:   Same reference here with a bit more detail: https://www.howtogeek.com/716407/how-to-change-the-default-system-font-on-windows-10/ Once the font is chosen, the size can be changed via personalization from my understanding. Hope this helps.
    • Videomass 5.0.26 by Razvan Serea Videomass is not just a common converter, it features file concatenation, time trimmer, ability to create thumbnails, tiled mosaics and animated giffs from movies; it has sophisticated GUIs for video filters, previews for video stabilization, resizing, croping, transposing, color equalization. It features PEAK, RMS and EBU audio normalization with streams indexing capabilities, a volume analyzer, audio preview and many more interesting features… For the people that are familiar with FFmpeg, it has a highly customizable preset manager with the possibility to easily make your own presets through the GUI and adapt this to your specific needs or create new presets using the FFmpeg command line. For less experienced people there are also ready-to-use presets. It offers out-of-the-box all possible file formats like MP4, M4V, M4A, MKV, AVI, OGV, WEBM, MP3, AC-3, WAV, OPUS, FLAC, OGG and encoders like MPEG-4, H.264/AVC, H.265/HEVC, VP8, VP9, LIBAOM-AVI, VORBIS, PCM, LAME, ALAC, etc. Also you can copy audio or video streams (lossless mode) without re-encoding, or extract audio from videos and much more! Main features No ads Multi-Platform, work on Linux, MacOs, Windows, FreeBsd. Batch processing. Queue management (only available for Presets Manager and A/V Conversions). Advanced log file management. Multi-panels, switch between panels using keyboard shortcuts. Audio/video processing using advanced tools and sophisticated filters interfaces. While downloading audio or video you can now do other transcoding tasks. Multi languages support (English, French, Italian, Russian, Dutch, Portuguese-BR, simplified Chinese, Spanish-ES, Spanish-CU, Spanish-MX) Conversions and transcoding Drag and drop to add multiple files simultaneously. Fully customizable presets and profiles. Possibility to create your new presets and profiles from scratch. Has useful presets to start with. Using the Presets Manager, you can set any format and codec supported by your FFmpeg build. Media file info (from FFprobe) and streams analyzer (from volumedetect). Shows the estimated time of arrival during encodings. Concatenate, merge media files losslessly. Create Slideshows. Extract images from video. Ability to switch between different FFmpeg builds. Has useful graphical tools for evaluating the supported features of a specific FFmpeg build. Audio stream mapping using selectable indexes. You can set both audio and video to copy when you just want to convert formats (lossless process). Timeline editor to slice time segments or trim the duration of your media even without re-encoding and therefore without loss of quality. It has GUI video filters such as: Resize Crop Transpose Deinterlace Denoise Stabilize Equalize Audio filters for volume normalization such us: PEAK, RMS and EBU-R128 normalizers. PEAK and RMS volume analysis reporting. Ability to select specified audio streams in videos to apply volume normalization. and much more… Videomass 5.0.26 changelog: Fixed yt-dlp preferences tab issue #372 Enabled import of the external «yt_dlp» package also on the standalone executable built by Pyinstaller. Improved handling of the yt-dlp executable (yt-dlp.exe on Windows) which now provides some automation and useful information for the users. Added «Whale» browser to the supported browser list for cookie automations. Update it_IT i18n, thanks to @bovirus Update zh_CN i18n, thanks to @userwljs Removed API functionality for download operations. Now only the yt-dlp executable is used for download operations. The API is still needed and will only be used for statistics extraction and format code listing. Fixed #374 Added «FLAC resampler» new preset. Notes: FFmpeg is not included in this archive. Before launching the application, ensure you have a compatible version of FFmpeg for your system architecture (requires ffmpeg.exe, ffprobe.exe, and ffplay.exe, version 5.1 or newer). For more details and downloads, visit: Gyan's FFmpeg builds page BtbN's FFmpeg GitHub releases page Antivirus False Positive Detection Some antivirus programs may mistakenly flag Videomass.exe as malicious. These are false positives. To resolve this, submit the Videomass.exe file to your antivirus vendor for further analysis and request a false positive review. Download: Videomass 5.0.26 | 18.4 MB (Open Source) Links: Videomass Home Page | Screenshots | Other OSes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Who could have thought that Microsoft's (not an ad business) browser is better at blocking ads than Google's (the ad business) browser.
    • So, Microsoft Edge should be behind Firefox and Chrome, because most average users have not heard about it and don't know it's exist.
  • 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
      488
    2. 2
      +FloatingFatMan
      259
    3. 3
      snowy owl
      244
    4. 4
      ATLien_0
      222
    5. 5
      +Edouard
      191
  • Tell a friend

    Love Neowin? Tell a friend!