• 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

    • Microsoft 365 Word gets SharePoint eSignature, now you can ditch third-party signing tools by Paul Hill Microsoft has just announced that it will be rolling out an extremely convenient feature for Microsoft 365 customers who use Word throughout this year. The Redmond giant said that you’ll now be able to use SharePoint’s native eSignature service directly in Microsoft Word. The new feature allows customers to request electronic signatures without converting the documents to a PDF or leaving the Word interface, significantly speeding up workflows. Microsoft’s integration of eSignatures also allows you to create eSignature templates which will speed up document approvals, eliminate physical signing steps, and help with compliance and security in the Microsoft 365 environment. This change has the potential to significantly improve the quality-of-life for those in work finding themselves adding lots of signatures to documents as they will no longer have to export PDFs from Word and apply the signature outside of Word. It’s also key to point out that this feature is integrated natively and is not an extension. The move is quite clever from Microsoft, if businesses were using third-party tools to sign their documents, they would no longer need to use these as it’s easier to do it in Word. Not only does it reduce reliance on other tools, it also makes Microsoft’s products more competitive against other office suites such as Google Workspace. Streamlined, secure, and compliant The new eSignature feature is tightly integrated into Word. It lets you insert signature fields seamlessly into documents and request other people’s signatures, all while remaining in Word. The eSignature feature can be accessed in Word by going to the Insert ribbon. When you send a signature request to someone from Word, the recipient will get an automatically generated PDF copy of the Word document to sign. The signed PDF will then be kept in the same SharePoint location as the original Word file. To ensure end-to-end security and compliance, the document never leaves the Microsoft 365 trust boundary. For anyone with a repetitive signing process, this integration allows you to turn Word documents into eSignature templates so they can be reused. Another feature that Microsoft has built in is audit trail and notifications. Both the senders and signers will get email notifications throughout the entire signing process. Additionally, you can view the activity history (audit trail) in the signed PDF to check who signed it and when. Finally, Microsoft said that administrators will be able to control how the feature is used in Word throughout the organization. They can decide to enable it for specific users via an Office group policy or limit it to particular SharePoint sites. The company said that SharePoint eSignature also lets admins log activities in the Purview Audit log. A key security measure included by Microsoft, which was mentioned above, was the Microsoft 365 trust boundary. By keeping documents in this boundary, Microsoft ensures that all organizations can use this feature without worry. The inclusion of automatic PDF creation is all a huge benefit to users as it will cut out the step of manual PDF creation. While creating a PDF isn’t complicated, it can be time consuming. The eSignature feature looks like a win-win-win for organizations that rely on digital signatures. Not only does it speed things along and remain secure, but it’s also packed with features like tracking, making it really useful and comprehensive. When and how your organization gets it SharePoint eSignature has started rolling out to Word on the M365 Beta and Current Channels in the United States, Canada, the United Kingdom, Europe, and Australia-Pacific. This phase of the rollout is expected to be completed by early July. People in the rest of the world will also be gaining this time-saving feature but it will not reach everyone right away, though Microsoft promises to reach everybody by the end of the year. To use the feature, it will need to be enabled by administrators. If you’re an admin who needs to enable this, just go to the M365 Admin Center and enable SharePoint eSignature, ensuring the Word checkbox is selected. Once the service is enabled, apply the “Allow the use of SharePoint eSignature for Microsoft Word” policy. The policy can be enabled via Intune, Group Policy manager, or the Cloud Policy service for Microsoft 365 Assuming the admins have given permission to use the feature, users will be able to access SharePoint eSignatures on Word Desktop using the Microsoft 365 Current Channel or Beta Channel. The main caveats include that the rollout is phased, so you might not get it right away, and it requires IT admins to enable the feature - in which case, it may never get enabled at all. Overall, this feature stands to benefit users who sign documents a lot as it can save huge amounts of time cumulatively. It’s also good for Microsoft who increase organizations’ dependence on Word.
    • It's always good to have an option to secure your stuff to another medium. I did that with DVD/CD collection, and run my own media server now. It's more convenient that way and no need for separate players anymore.
    • Google Search AI Mode gets support for data visualization and custom charts by Aditya Tiwari Google announced it is rolling out support for data visualizations and graphs for finance-related queries in Google Search's AI Mode. Introduced last month at the Google I/O 2025 keynote, the feature lets you analyze complex datasets and create custom charts simply using natural language prompts. The updated AI Mode lets you compare and analyze information over a specific period, Google explained. It generates interactive graphs and provides a comprehensive explanation for your questions. AI Mode utilizes Gemini's multimodal capabilities and multi-step reasoning approach to comprehend the question's intent while accessing historical and real-time information relevant to the question. For instance, instead of manually researching individual companies and their stock prices, you can use AI Mode to compare the stock performance of different companies for a specific year. Once the graph is generated, you can choose the desired time period using the mouse cursor and ask follow-up questions based on the data presented. These new data visualizations for finance queries are available to users who have enabled the AI Mode experiment in Labs. AI Mode was introduced earlier this year as an experimental feature in the US. The feature is an upgraded version of AI Overviews, and Google closely worked with AI power users through the initial development process. It uses the “query fan-out” technique to perform multiple related searches across subtopics and different data sources, then combines them to come up with a comprehensive response. Google updated AI Mode last month to use a custom version of the latest Gemini 2.5 model. It added several new features, including Deep Search, live capabilities, agentic capabilities of Project Mariner, a new shopping experience, and the ability to add personal context by linking Google apps. The search giant is planning to turn AI Mode into its bread and butter. It has begun testing ads for the feature, which will appear below and be integrated into AI Mode responses where relevant.
    • Guys, you should find another way to promote your deals... It's the third article in the last months that promote this deal for an upgrade from 10. Considering that upgrade from 10 to 11 is free it's a total non-sense.
    • Store should be a shrine of useful applications, vetted and verified. Easily sorted by publisher. Windows should start with not much installed and have things as options in the store. Not the wild west mess that it is. You could delete 95%+ of the crap on there and no one would notice. They need to add a better UI to the updates, it's awful right now.
  • Recent Achievements

    • Week One Done
      luxoxfurniture earned a badge
      Week One Done
    • First Post
      Uranus_enjoyer earned a badge
      First Post
    • Week One Done
      Uranus_enjoyer earned a badge
      Week One Done
    • Week One Done
      jfam earned a badge
      Week One Done
    • First Post
      survivor303 earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      432
    2. 2
      +FloatingFatMan
      239
    3. 3
      snowy owl
      213
    4. 4
      ATLien_0
      211
    5. 5
      Xenon
      157
  • Tell a friend

    Love Neowin? Tell a friend!