Different content of &a
Im looking for a better understanding of the following 3 examples.
This is my questions to the following code examples.
Ex. 1. Example makes sense, it outputs the adress of which the int a is
stored.
Ex. 2. Makes a little less sense for. I think it is because the char
itself points to the char?
Ex. 3. Confuses me. In the output the first char output is always the on
stored in the char. But what are the appending chars and why do they
appear after saving &a to a char pointer?
Lastly how do i output the adress of the memory location of where a char
variable is saved?
Ex. 1
main(void)
{
int a = 1;
cout << &a;
}
Outputs the memory adress ex. 0x7fff4241b7b4
Ex 2.
main(void)
{
char a = 'a';
cout << &a;
}
Outputs the char a. ex. a
Ex. 3.
main(void)
{
char a = 'a';
char *b = &a;
cout << &a;
}
Outputs a��:��
Sunday, 18 August 2013
Python: NameError name '[input]' is not defined
Python: NameError name '[input]' is not defined
I'm trying to make a simple little tool for converting inches to
centimeters and am stuck at trying to take a user input ('y' or 'n') for
deciding whether to do another conversion or terminate. Here's what I've
done:
import time
def intro():
print "Welcome! This program will convert inches to centimeters for
you.\n"
convert()
def convert():
input_cm = input(("Inches: "))
inches_conv = input_cm * 2.54
print "Centimeters: %f\n" % inches_conv
time.sleep(3)
restart = str(input("Do you wish to make another conversion? [y]Yes or
[n]no: "))
if restart == 'y':
convert()
elif restart == 'n':
end_fast()
else:
print "I didn't quite understand that answer. Terminating."
end_slow()
def end_fast():
print "This program will close in 5 seconds."
time.sleep(5)
def end_slow():
print "This program will close in 30 seconds."
time.sleep(30)
intro()
And this results in:
Traceback (most recent call last): File
"C:\Users\Sam\Programming\Python\the hard way\ex5.4.py", line 29, in
intro() File "C:\Users\Sam\Programming\Python\the hard way\ex5.4.py", line
5, in intro convert() File "C:\Users\Sam\Programming\Python\the hard
way\ex5.4.py", line 12, in convert restart = str(input("Do you wish to
make another conversion? [y]Yes or [n]no?\n")) File "", line 1, in
NameError: name 'y' is not defined
Help appreciated.
I'm trying to make a simple little tool for converting inches to
centimeters and am stuck at trying to take a user input ('y' or 'n') for
deciding whether to do another conversion or terminate. Here's what I've
done:
import time
def intro():
print "Welcome! This program will convert inches to centimeters for
you.\n"
convert()
def convert():
input_cm = input(("Inches: "))
inches_conv = input_cm * 2.54
print "Centimeters: %f\n" % inches_conv
time.sleep(3)
restart = str(input("Do you wish to make another conversion? [y]Yes or
[n]no: "))
if restart == 'y':
convert()
elif restart == 'n':
end_fast()
else:
print "I didn't quite understand that answer. Terminating."
end_slow()
def end_fast():
print "This program will close in 5 seconds."
time.sleep(5)
def end_slow():
print "This program will close in 30 seconds."
time.sleep(30)
intro()
And this results in:
Traceback (most recent call last): File
"C:\Users\Sam\Programming\Python\the hard way\ex5.4.py", line 29, in
intro() File "C:\Users\Sam\Programming\Python\the hard way\ex5.4.py", line
5, in intro convert() File "C:\Users\Sam\Programming\Python\the hard
way\ex5.4.py", line 12, in convert restart = str(input("Do you wish to
make another conversion? [y]Yes or [n]no?\n")) File "", line 1, in
NameError: name 'y' is not defined
Help appreciated.
Unable to install anything on ubuntu 13.04 Raring Ringtail
Unable to install anything on ubuntu 13.04 Raring Ringtail
A few days back, I was on a stable Ubuntu 13.04 install that i messed up
while trying different Dekstop environments, and thus, i totally screwed
it up after trying to get a ful Gnome3 experience. As a result, The
right-click context menu stopped wrking in Unity, would freeze when i
minimize any window, + all the fonts were messed up, so i decided to go
for a clean re-install.
I did. After which, im unable to install anything on it. I first recieved
errors while installing Chrome or SKype, but considering it to be
perfectly normal, I mannually installed the missing Libraries and
succeeded installling chrome.
But nothing else installs. If i try installing something through the
Terminal, i get stupied errors like: E: Unable to locate package leafpad
or: Package synaptic is not available, but is referred to by another
package. This may mean that the package is missing, has been obsoleted, or
is only available from another source
or: E: Package 'synaptic' has no installation candidate.
IF i use the Software center i get this error:
http://www.flickr.com/photos/96009096@N06/9534183933/
or if the package is from the UNIVERSE or MULTIVERSE sources and i click
on 'USE THIS SOURCE' button, It starts some "updating cache" process that
fails after sometime, with a stupid message saying: "FAILEED TO UPDATE
REPOSITORY INFORMATION please check your internet connection and try
again." http://www.flickr.com/photos/96009096@N06/9536970330/
Please help me out of this.. I'm not exactly a complete newbie to Linux,
and have been using Ubuntu for ages, but never was much good at handling
errors, and this is a situation where i just am not 'allowed' to do
anything seeing as i get stupid errors every time i try installling
something. and thus for some reason or another, EVERY install fails...
A few days back, I was on a stable Ubuntu 13.04 install that i messed up
while trying different Dekstop environments, and thus, i totally screwed
it up after trying to get a ful Gnome3 experience. As a result, The
right-click context menu stopped wrking in Unity, would freeze when i
minimize any window, + all the fonts were messed up, so i decided to go
for a clean re-install.
I did. After which, im unable to install anything on it. I first recieved
errors while installing Chrome or SKype, but considering it to be
perfectly normal, I mannually installed the missing Libraries and
succeeded installling chrome.
But nothing else installs. If i try installing something through the
Terminal, i get stupied errors like: E: Unable to locate package leafpad
or: Package synaptic is not available, but is referred to by another
package. This may mean that the package is missing, has been obsoleted, or
is only available from another source
or: E: Package 'synaptic' has no installation candidate.
IF i use the Software center i get this error:
http://www.flickr.com/photos/96009096@N06/9534183933/
or if the package is from the UNIVERSE or MULTIVERSE sources and i click
on 'USE THIS SOURCE' button, It starts some "updating cache" process that
fails after sometime, with a stupid message saying: "FAILEED TO UPDATE
REPOSITORY INFORMATION please check your internet connection and try
again." http://www.flickr.com/photos/96009096@N06/9536970330/
Please help me out of this.. I'm not exactly a complete newbie to Linux,
and have been using Ubuntu for ages, but never was much good at handling
errors, and this is a situation where i just am not 'allowed' to do
anything seeing as i get stupid errors every time i try installling
something. and thus for some reason or another, EVERY install fails...
Saturday, 17 August 2013
Branching issue in C program
Branching issue in C program
My C program needs to skip rest of the code if particular event occurs. I
have used continue for that but there is some issue. I am not sure issue
is due to that only or something different but it's something logic
mistake.
I am sending word to BoyerMoore_positive(ch[i], strlen(ch[i]) ); function
to verify whether it exist in particular word list or not. If exist then
increment count values.
for skp = BoyerMoore_skip(ch[i], strlen(ch[i]) ); if word is present in
this function then I want to skip rest of the code and continue with next
word. So I incremented the i.
It checks "he is the you she am" this list. But when word is present in
this list and come back after performing actions in the function it does
not proceed to next word though I have incremented i. It keep looping in
BoyerMoore_skip(ch[i], strlen(ch[i]) ); for some times and then stops
without processing next word.
I know this is very specific issue to my program but any kinda help is
highly appreciable. I may making some silly mistake.
code:
while ((NULL != word) && (50 > i)) {
ch[i] = strdup(word);
//printf("%s n", ch[i]);
skp = BoyerMoore_skip(ch[i], strlen(ch[i]) );
// printf("skip is %s \n",skp);
if(skp != NULL)
{
i++;
printf("in\n");
continue;
}
// I tried with keeping i++ and continue in seperate if(skp != NULL) but
same result.
printf("\n hi2 \n");
str = BoyerMoore_positive(ch[i], strlen(ch[i]) );
str2= BoyerMoore_negative(ch[i], strlen(ch[i]) );
printf("Str is %s \n",str2);
if (str == NULL)
t++;
else {
printf("%s \n", ch[i]);
// puts("true");
pcount += 1;
printf("Positive count is: %d \n",pcount);
}
if(str2== NULL)
q++;
else {
printf("%s \n", ch[i]);
// puts("true");
ncount += 1;
printf("Nagative count is: %d \n",ncount);
}
i++;
word = strtok(NULL, " ");
if(str==NULL && str==NULL and skp !=NULL)
{
pcount=0;
ncount=0;
}
}
My C program needs to skip rest of the code if particular event occurs. I
have used continue for that but there is some issue. I am not sure issue
is due to that only or something different but it's something logic
mistake.
I am sending word to BoyerMoore_positive(ch[i], strlen(ch[i]) ); function
to verify whether it exist in particular word list or not. If exist then
increment count values.
for skp = BoyerMoore_skip(ch[i], strlen(ch[i]) ); if word is present in
this function then I want to skip rest of the code and continue with next
word. So I incremented the i.
It checks "he is the you she am" this list. But when word is present in
this list and come back after performing actions in the function it does
not proceed to next word though I have incremented i. It keep looping in
BoyerMoore_skip(ch[i], strlen(ch[i]) ); for some times and then stops
without processing next word.
I know this is very specific issue to my program but any kinda help is
highly appreciable. I may making some silly mistake.
code:
while ((NULL != word) && (50 > i)) {
ch[i] = strdup(word);
//printf("%s n", ch[i]);
skp = BoyerMoore_skip(ch[i], strlen(ch[i]) );
// printf("skip is %s \n",skp);
if(skp != NULL)
{
i++;
printf("in\n");
continue;
}
// I tried with keeping i++ and continue in seperate if(skp != NULL) but
same result.
printf("\n hi2 \n");
str = BoyerMoore_positive(ch[i], strlen(ch[i]) );
str2= BoyerMoore_negative(ch[i], strlen(ch[i]) );
printf("Str is %s \n",str2);
if (str == NULL)
t++;
else {
printf("%s \n", ch[i]);
// puts("true");
pcount += 1;
printf("Positive count is: %d \n",pcount);
}
if(str2== NULL)
q++;
else {
printf("%s \n", ch[i]);
// puts("true");
ncount += 1;
printf("Nagative count is: %d \n",ncount);
}
i++;
word = strtok(NULL, " ");
if(str==NULL && str==NULL and skp !=NULL)
{
pcount=0;
ncount=0;
}
}
findViewById() in OnActivityResult function causes crash
findViewById() in OnActivityResult function causes crash
In onActivityResult function I create layout and button in this layout.
And when I press the button, I want to edit data in it by calling a new
activity. I received data from new activity and want to find button by id
to apply changes. But function findViewById causes crash of my
application. How can I fix it?
This is part of my code:
if(requestCode == EditingMedicine)
{
if(resultCode == RESULT_OK)
{
int _id = data.getIntExtra(AddEditMedicineActivity.Id, -1);
String medName =
data.getStringExtra(AddEditMedicineActivity.medName);
String medTime =
data.getStringExtra(AddEditMedicineActivity.medTime);
Button btn = (Button)findViewById(_id);
btn.setText(Html.fromHtml(medName + " <br/>" + medTime));
}
}
Thanks.
In onActivityResult function I create layout and button in this layout.
And when I press the button, I want to edit data in it by calling a new
activity. I received data from new activity and want to find button by id
to apply changes. But function findViewById causes crash of my
application. How can I fix it?
This is part of my code:
if(requestCode == EditingMedicine)
{
if(resultCode == RESULT_OK)
{
int _id = data.getIntExtra(AddEditMedicineActivity.Id, -1);
String medName =
data.getStringExtra(AddEditMedicineActivity.medName);
String medTime =
data.getStringExtra(AddEditMedicineActivity.medTime);
Button btn = (Button)findViewById(_id);
btn.setText(Html.fromHtml(medName + " <br/>" + medTime));
}
}
Thanks.
MPMusicPlayerController applicationMusicPlayer hoses iPodMusicPlayer
MPMusicPlayerController applicationMusicPlayer hoses iPodMusicPlayer
I have an application where I would like to use the iPodMusicPlayer to
resume the user's currently selected iPod selection (an audiobook). At
other times I need to play music from the iPod library without disturbing
the state (selection/position) of the iPod player (so the user can pick up
his audiobook outside of my app where he left off listenting in my app).
The obvious way to do this is to play (resume) the user's audiobook using
the iPodMusicPlayer, then when switching to other music use the
applicationMusicPlayer (after first pausing the iPodMusicPlayer). Do
exactly that in exactly that sequence works ok, BUT... any reference to
the applicationMusicPlayer screws up the state of the iPodMusicPlayer from
then on, i.e. I can no longer play or get the duration of the
iPodMusicPlayer. Messages to the iPodMusicPlayer seem to be routed to the
applicationMusicPlayer.
I've adapted a simple example from another developer who had a similar
problem but worked around it by only using the applicationMusicPlayer. In
this test, the reference to the applicationMusicPlayer causes the
iPodMusicPlayer to misbehave. Commenting that line out causes correct
behavior.
Is sequential use of the two music players not supported? If so, that's
not documented anywhere that I can find.
#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h>
@interface ViewController ()
@property (strong, nonatomic) MPMusicPlayerController *MPPlayer;
- (void)updateProgressView;
@end
@implementation ViewController
@synthesize playPauseButton = _playPauseButton;
@synthesize progressView = _progressView;
@synthesize label = _label;
- (void)viewDidLoad {
[super viewDidLoad];
[[MPMusicPlayerController iPodMusicPlayer]
beginGeneratingPlaybackNotifications];
NSNotificationCenter *notificationCenter = [NSNotificationCenter
defaultCenter];
[notificationCenter addObserver:self
selector:@selector(handle_NowPlayingItemChanged:)
name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object:[MPMusicPlayerController
iPodMusicPlayer]];
[notificationCenter addObserver:self
selector:@selector(handle_PlaybackStateChanged:)
name:MPMusicPlayerControllerPlaybackStateDidChangeNotification
object:[MPMusicPlayerController
iPodMusicPlayer]];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self
selector:@selector(updateProgressView) userInfo:nil repeats:YES];
[self updateProgressView];
}
- (IBAction)playPauseButtonPressed {
// ****** this line (instantiation of the applicationMusicPlayer)
causes the iPodMusicPlayer to misbehave ******
NSLog(@"app player state:%i", [MPMusicPlayerController
applicationMusicPlayer].playbackState);
// ****** commented out the example behaves corectly
NSLog(@"iPod player state:%i", [MPMusicPlayerController
iPodMusicPlayer].playbackState);
if ([[MPMusicPlayerController iPodMusicPlayer] playbackState] ==
MPMusicPlaybackStatePlaying) {
NSLog(@"iPod pause");
[[MPMusicPlayerController iPodMusicPlayer] pause];
} else {
NSLog(@"iPod play");
[[MPMusicPlayerController iPodMusicPlayer] play];
}
}
- (void)handle_NowPlayingItemChanged:(NSNotification *)notification {
NSLog(@"now playing: %@", [[MPMusicPlayerController
iPodMusicPlayer].nowPlayingItem
valueForProperty:MPMediaItemPropertyTitle]);
self.label.text = [[MPMusicPlayerController
iPodMusicPlayer].nowPlayingItem
valueForProperty:MPMediaItemPropertyTitle];
}
- (void)handle_PlaybackStateChanged:(NSNotification *)notification {
NSLog(@"playback state: %i", [MPMusicPlayerController
iPodMusicPlayer].playbackState);
self.playPauseButton.selected = ([[MPMusicPlayerController
iPodMusicPlayer] playbackState] == MPMusicPlaybackStatePlaying);
}
- (void)updateProgressView {
NSTimeInterval currentTime = [[MPMusicPlayerController
iPodMusicPlayer] currentPlaybackTime];
NSNumber *duration = [[MPMusicPlayerController
iPodMusicPlayer].nowPlayingItem
valueForProperty:MPMediaItemPropertyPlaybackDuration];
self.progressView.progress = currentTime / [duration floatValue];
}
@end
I have an application where I would like to use the iPodMusicPlayer to
resume the user's currently selected iPod selection (an audiobook). At
other times I need to play music from the iPod library without disturbing
the state (selection/position) of the iPod player (so the user can pick up
his audiobook outside of my app where he left off listenting in my app).
The obvious way to do this is to play (resume) the user's audiobook using
the iPodMusicPlayer, then when switching to other music use the
applicationMusicPlayer (after first pausing the iPodMusicPlayer). Do
exactly that in exactly that sequence works ok, BUT... any reference to
the applicationMusicPlayer screws up the state of the iPodMusicPlayer from
then on, i.e. I can no longer play or get the duration of the
iPodMusicPlayer. Messages to the iPodMusicPlayer seem to be routed to the
applicationMusicPlayer.
I've adapted a simple example from another developer who had a similar
problem but worked around it by only using the applicationMusicPlayer. In
this test, the reference to the applicationMusicPlayer causes the
iPodMusicPlayer to misbehave. Commenting that line out causes correct
behavior.
Is sequential use of the two music players not supported? If so, that's
not documented anywhere that I can find.
#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h>
@interface ViewController ()
@property (strong, nonatomic) MPMusicPlayerController *MPPlayer;
- (void)updateProgressView;
@end
@implementation ViewController
@synthesize playPauseButton = _playPauseButton;
@synthesize progressView = _progressView;
@synthesize label = _label;
- (void)viewDidLoad {
[super viewDidLoad];
[[MPMusicPlayerController iPodMusicPlayer]
beginGeneratingPlaybackNotifications];
NSNotificationCenter *notificationCenter = [NSNotificationCenter
defaultCenter];
[notificationCenter addObserver:self
selector:@selector(handle_NowPlayingItemChanged:)
name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object:[MPMusicPlayerController
iPodMusicPlayer]];
[notificationCenter addObserver:self
selector:@selector(handle_PlaybackStateChanged:)
name:MPMusicPlayerControllerPlaybackStateDidChangeNotification
object:[MPMusicPlayerController
iPodMusicPlayer]];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self
selector:@selector(updateProgressView) userInfo:nil repeats:YES];
[self updateProgressView];
}
- (IBAction)playPauseButtonPressed {
// ****** this line (instantiation of the applicationMusicPlayer)
causes the iPodMusicPlayer to misbehave ******
NSLog(@"app player state:%i", [MPMusicPlayerController
applicationMusicPlayer].playbackState);
// ****** commented out the example behaves corectly
NSLog(@"iPod player state:%i", [MPMusicPlayerController
iPodMusicPlayer].playbackState);
if ([[MPMusicPlayerController iPodMusicPlayer] playbackState] ==
MPMusicPlaybackStatePlaying) {
NSLog(@"iPod pause");
[[MPMusicPlayerController iPodMusicPlayer] pause];
} else {
NSLog(@"iPod play");
[[MPMusicPlayerController iPodMusicPlayer] play];
}
}
- (void)handle_NowPlayingItemChanged:(NSNotification *)notification {
NSLog(@"now playing: %@", [[MPMusicPlayerController
iPodMusicPlayer].nowPlayingItem
valueForProperty:MPMediaItemPropertyTitle]);
self.label.text = [[MPMusicPlayerController
iPodMusicPlayer].nowPlayingItem
valueForProperty:MPMediaItemPropertyTitle];
}
- (void)handle_PlaybackStateChanged:(NSNotification *)notification {
NSLog(@"playback state: %i", [MPMusicPlayerController
iPodMusicPlayer].playbackState);
self.playPauseButton.selected = ([[MPMusicPlayerController
iPodMusicPlayer] playbackState] == MPMusicPlaybackStatePlaying);
}
- (void)updateProgressView {
NSTimeInterval currentTime = [[MPMusicPlayerController
iPodMusicPlayer] currentPlaybackTime];
NSNumber *duration = [[MPMusicPlayerController
iPodMusicPlayer].nowPlayingItem
valueForProperty:MPMediaItemPropertyPlaybackDuration];
self.progressView.progress = currentTime / [duration floatValue];
}
@end
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
javax.crypto.IllegalBlockSizeException: Input length must be multiple of
16 when decrypting with padded cipher
I am attempting to make a chat program that uses AES encryption but I have
ran into a problem. When I try to run the program, it gives the error that
you can see in the title. I will give you the code for both classes
because it seems that, that is the only way to fully diagnose the problem.
There are many duplicates of this but none seem to answer my specific
problem. Thanks for all your help! Client:
package Chat.Application;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.security.spec.AlgorithmParameterSpec;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
/**
* A simple Swing-based client for the chat server. Graphically it is a frame
* with a text field for entering messages and a textarea to see the whole
* dialog.
*
* The client follows the Chat Protocol which is as follows. When the server
* sends "SUBMITNAME" the client replies with the desired screen name. The
* server will keep sending "SUBMITNAME" requests as long as the client
submits
* screen names that are already in use. When the server sends a line
beginning
* with "NAMEACCEPTED" the client is now allowed to start sending the server
* arbitrary strings to be broadcast to all chatters connected to the server.
* When the server sends a line beginning with "MESSAGE " then all characters
* following this string should be displayed in its message area.
*/
public class ChatClient {
BufferedReader in;
PrintWriter out;
JFrame frame = new JFrame("ELECTRON Chatroom");
JTextField textField = new JTextField(40);
JTextArea messageArea = new JTextArea(8, 40);
Cipher cipher;
// password for encryption
final String strPassword = "1234567890123456";
// put this as key in AES
final SecretKeySpec key = new
SecretKeySpec(strPassword.getBytes(), "AES");
/**
* Constructs the client by laying out the GUI and registering a listener
* with the textfield so that pressing Return in the listener sends the
* textfield contents to the server. Note however that the textfield is
* initially NOT editable, and only becomes editable AFTER the client
* receives the NAMEACCEPTED message from the server.
*/
public ChatClient() {
// Layout GUI
textField.setEditable(false);
messageArea.setEditable(false);
messageArea.setWrapStyleWord(true);
messageArea.setLineWrap(true);
frame.getContentPane().add(textField, "North");
frame.getContentPane().add(new JScrollPane(messageArea), "Center");
frame.pack();
// Add Listeners
textField.addActionListener(new ActionListener() {
/**
* Responds to pressing the enter key in the textfield by sending
* the contents of the text field to the server. Then clear
the text
* area in preparation for the next message.
*/
@Override
public void actionPerformed(ActionEvent e) {
try {
String input = (textField.getText());
//ENCRYPTION
// Parameter specific algorithm
AlgorithmParameterSpec paramSpec = new
IvParameterSpec(strPassword.getBytes());
//Whatever you want to encrypt/decrypt
Cipher cipher =
Cipher.getInstance("AES/CBC/PKCS5Padding");
// You can use ENCRYPT_MODE (ENCRYPTunderscoreMODE)
or DECRYPT_MODE (DECRYPT underscore MODE)
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
// encrypt data
byte[] encrypted = cipher.doFinal(input.getBytes());
// encode data using standard encoder
//String output = new BASE64Encoder().encode(encrypted);
System.out.println("Orginal tring: " + input);
System.out.println("Encrypted string: " + encrypted);
textField.setText("");
} catch (NoSuchAlgorithmException | NoSuchPaddingException
| IllegalBlockSizeException | BadPaddingException |
InvalidKeyException | InvalidAlgorithmParameterException
ex) {
Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE,
null, ex);
}
}
});
}
/**
* Prompt for and return the address of the server.
*/
private String getServerAddress() {
return JOptionPane.showInputDialog(
frame,
"Enter IP Address of the Server:",
"ELECTRON Chatroom",
JOptionPane.QUESTION_MESSAGE);
}
/**
* Prompt for and return the desired screen name.
*/
private String getName() {
return JOptionPane.showInputDialog(
frame,
"Choose a screen name:",
"Screen name selection",
JOptionPane.PLAIN_MESSAGE);
}
/**
* Connects to the server then enters the processing loop.
*/
private void run() throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, IllegalBlockSizeException,
BadPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException {
// Make connection and initialize streams
String serverAddress = getServerAddress();
Socket socket = new Socket(serverAddress, 9001);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Process all messages from server, according to the protocol.
while (true) {
String line = in.readLine();
if (line.startsWith("SUBMITNAME")) {
out.println(getName());
} else if (line.startsWith("NAMEACCEPTED")) {
textField.setEditable(true);
} else if (line.startsWith("MESSAGE")) {
//DECRYPTION
line = line.substring(8);
System.out.println(line);
// Parameter specific algorithm
AlgorithmParameterSpec paramSpec = new
IvParameterSpec(strPassword.getBytes());
//Whatever you want to encrypt/decrypt
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// You can use ENCRYPT_MODE (ENCRYPTunderscoreMODE) or
DECRYPT_MODE (DECRYPT underscore MODE)
cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
byte messageByte[] = cipher.doFinal(line.getBytes());
String message = new String(messageByte, "UTF-8");
messageArea.append(message.substring(8) + "\n");
System.out.println(message);
}
}
}
/**
* Runs the client as an application with a closeable frame.
*/
public static void main(String[] args) throws Exception {
ChatClient client = new ChatClient();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setVisible(true);
client.run();
}
}
Server:
package Chat.Application;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
/**
* A multi-threaded chat room server. When a client connects the
* server requests a screen name by sending the client the
* text "SUBMITNAME", and keeps requesting a name until
* a unique one is received. After a client submits a unique
* name, the server acknowledges with "NAMEACCEPTED". Then
* all messages from that client will be broadcast to all other
* clients that have submitted a unique screen name. The
* broadcast messages are prefixed with "MESSAGE ".
*
* Because this is just a teaching example to illustrate a simple
* chat server, there are a few features that have been left out.
* Two are very useful and belong in production code:
*
* 1. The protocol should be enhanced so that the client can
* send clean disconnect messages to the server.
*
* 2. The server should do some logging.
*/
public class ChatServer {
/**
* The port that the server listens on.
*/
private static final int PORT = 9001;
/**
* The set of all names of clients in the chat room. Maintained
* so that we can check that new clients are not registering name
* already in use.
*/
private static HashSet<String> names = new HashSet<String>();
/**
* The set of all the print writers for all the clients. This
* set is kept so we can easily broadcast messages.
*/
private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();
/**
* The application main method, which just listens on a port and
* spawns handler threads.
*/
public static void main(String[] args) throws Exception {
System.out.println("Chat Server Activated");
ServerSocket listener = new ServerSocket(PORT);
try {
while (true) {
new Handler(listener.accept()).start();
}
} finally {
listener.close();
}
}
/**
* A handler thread class. Handlers are spawned from the listening
* loop and are responsible for a dealing with a single client
* and broadcasting its messages.
*/
private static class Handler extends Thread {
private String name;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private Integer length;
/**
* Constructs a handler thread, squirreling away the socket.
* All the interesting work is done in the run method.
*/
public Handler(Socket socket) {
this.socket = socket;
}
/**
* Services this thread's client by repeatedly requesting a
* screen name until a unique one has been submitted, then
* acknowledges the name and registers the output stream for
* the client in a global set, then repeatedly gets inputs and
* broadcasts them.
*/
public void run() {
try {
// Create character streams for the socket.
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Request a name from this client. Keep requesting until
// a name is submitted that is not already used. Note that
// checking for the existence of a name and adding the name
// must be done while locking the set of names.
while (true) {
out.println("SUBMITNAME");
/*Supposed to change anybody who tries to login as Admin
into different name... "Supposed" to....
if (name.equals("Admin")) {
out.println("SUBMITNAME");
return;
}*/
name = in.readLine();
length = name.length();
if (length == 0) {
out.println("SUBMITNAME");
return;
}
if (name == "null") {
out.println("SUBMITNAME");
return;
}
synchronized (names) {
if (!names.contains(name)) {
names.add(name);
break;
}
}
}
// Now that a successful name has been chosen, add the
// socket's print writer to the set of all writers so
// this client can receive broadcast messages.
out.println("NAMEACCEPTED");
//Announces that user is Online
out.println("MESSAGE " + name + " is now Online");
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + " is now Online");
}
writers.add(out);
// Accept messages from this client and broadcast them.
// Ignore other clients that cannot be broadcasted to.
while (true) {
String input = in.readLine();
System.out.println(input);
if (input == null) {
return;
}
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + ": " + input);
}
}
} catch (IOException e) {
System.out.println(e);
} finally {
// This client is going down! Remove its name and its print
// writer from the sets, and close its socket.
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + " is now Offline");
} if (name != null) {
names.remove(name);
}
if (out != null) {
writers.remove(out);
}
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}
Thanks so much for all your help in saving a complete noob at programming!
-Silver
16 when decrypting with padded cipher
I am attempting to make a chat program that uses AES encryption but I have
ran into a problem. When I try to run the program, it gives the error that
you can see in the title. I will give you the code for both classes
because it seems that, that is the only way to fully diagnose the problem.
There are many duplicates of this but none seem to answer my specific
problem. Thanks for all your help! Client:
package Chat.Application;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.security.spec.AlgorithmParameterSpec;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
/**
* A simple Swing-based client for the chat server. Graphically it is a frame
* with a text field for entering messages and a textarea to see the whole
* dialog.
*
* The client follows the Chat Protocol which is as follows. When the server
* sends "SUBMITNAME" the client replies with the desired screen name. The
* server will keep sending "SUBMITNAME" requests as long as the client
submits
* screen names that are already in use. When the server sends a line
beginning
* with "NAMEACCEPTED" the client is now allowed to start sending the server
* arbitrary strings to be broadcast to all chatters connected to the server.
* When the server sends a line beginning with "MESSAGE " then all characters
* following this string should be displayed in its message area.
*/
public class ChatClient {
BufferedReader in;
PrintWriter out;
JFrame frame = new JFrame("ELECTRON Chatroom");
JTextField textField = new JTextField(40);
JTextArea messageArea = new JTextArea(8, 40);
Cipher cipher;
// password for encryption
final String strPassword = "1234567890123456";
// put this as key in AES
final SecretKeySpec key = new
SecretKeySpec(strPassword.getBytes(), "AES");
/**
* Constructs the client by laying out the GUI and registering a listener
* with the textfield so that pressing Return in the listener sends the
* textfield contents to the server. Note however that the textfield is
* initially NOT editable, and only becomes editable AFTER the client
* receives the NAMEACCEPTED message from the server.
*/
public ChatClient() {
// Layout GUI
textField.setEditable(false);
messageArea.setEditable(false);
messageArea.setWrapStyleWord(true);
messageArea.setLineWrap(true);
frame.getContentPane().add(textField, "North");
frame.getContentPane().add(new JScrollPane(messageArea), "Center");
frame.pack();
// Add Listeners
textField.addActionListener(new ActionListener() {
/**
* Responds to pressing the enter key in the textfield by sending
* the contents of the text field to the server. Then clear
the text
* area in preparation for the next message.
*/
@Override
public void actionPerformed(ActionEvent e) {
try {
String input = (textField.getText());
//ENCRYPTION
// Parameter specific algorithm
AlgorithmParameterSpec paramSpec = new
IvParameterSpec(strPassword.getBytes());
//Whatever you want to encrypt/decrypt
Cipher cipher =
Cipher.getInstance("AES/CBC/PKCS5Padding");
// You can use ENCRYPT_MODE (ENCRYPTunderscoreMODE)
or DECRYPT_MODE (DECRYPT underscore MODE)
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
// encrypt data
byte[] encrypted = cipher.doFinal(input.getBytes());
// encode data using standard encoder
//String output = new BASE64Encoder().encode(encrypted);
System.out.println("Orginal tring: " + input);
System.out.println("Encrypted string: " + encrypted);
textField.setText("");
} catch (NoSuchAlgorithmException | NoSuchPaddingException
| IllegalBlockSizeException | BadPaddingException |
InvalidKeyException | InvalidAlgorithmParameterException
ex) {
Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE,
null, ex);
}
}
});
}
/**
* Prompt for and return the address of the server.
*/
private String getServerAddress() {
return JOptionPane.showInputDialog(
frame,
"Enter IP Address of the Server:",
"ELECTRON Chatroom",
JOptionPane.QUESTION_MESSAGE);
}
/**
* Prompt for and return the desired screen name.
*/
private String getName() {
return JOptionPane.showInputDialog(
frame,
"Choose a screen name:",
"Screen name selection",
JOptionPane.PLAIN_MESSAGE);
}
/**
* Connects to the server then enters the processing loop.
*/
private void run() throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, IllegalBlockSizeException,
BadPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException {
// Make connection and initialize streams
String serverAddress = getServerAddress();
Socket socket = new Socket(serverAddress, 9001);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Process all messages from server, according to the protocol.
while (true) {
String line = in.readLine();
if (line.startsWith("SUBMITNAME")) {
out.println(getName());
} else if (line.startsWith("NAMEACCEPTED")) {
textField.setEditable(true);
} else if (line.startsWith("MESSAGE")) {
//DECRYPTION
line = line.substring(8);
System.out.println(line);
// Parameter specific algorithm
AlgorithmParameterSpec paramSpec = new
IvParameterSpec(strPassword.getBytes());
//Whatever you want to encrypt/decrypt
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// You can use ENCRYPT_MODE (ENCRYPTunderscoreMODE) or
DECRYPT_MODE (DECRYPT underscore MODE)
cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
byte messageByte[] = cipher.doFinal(line.getBytes());
String message = new String(messageByte, "UTF-8");
messageArea.append(message.substring(8) + "\n");
System.out.println(message);
}
}
}
/**
* Runs the client as an application with a closeable frame.
*/
public static void main(String[] args) throws Exception {
ChatClient client = new ChatClient();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setVisible(true);
client.run();
}
}
Server:
package Chat.Application;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
/**
* A multi-threaded chat room server. When a client connects the
* server requests a screen name by sending the client the
* text "SUBMITNAME", and keeps requesting a name until
* a unique one is received. After a client submits a unique
* name, the server acknowledges with "NAMEACCEPTED". Then
* all messages from that client will be broadcast to all other
* clients that have submitted a unique screen name. The
* broadcast messages are prefixed with "MESSAGE ".
*
* Because this is just a teaching example to illustrate a simple
* chat server, there are a few features that have been left out.
* Two are very useful and belong in production code:
*
* 1. The protocol should be enhanced so that the client can
* send clean disconnect messages to the server.
*
* 2. The server should do some logging.
*/
public class ChatServer {
/**
* The port that the server listens on.
*/
private static final int PORT = 9001;
/**
* The set of all names of clients in the chat room. Maintained
* so that we can check that new clients are not registering name
* already in use.
*/
private static HashSet<String> names = new HashSet<String>();
/**
* The set of all the print writers for all the clients. This
* set is kept so we can easily broadcast messages.
*/
private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();
/**
* The application main method, which just listens on a port and
* spawns handler threads.
*/
public static void main(String[] args) throws Exception {
System.out.println("Chat Server Activated");
ServerSocket listener = new ServerSocket(PORT);
try {
while (true) {
new Handler(listener.accept()).start();
}
} finally {
listener.close();
}
}
/**
* A handler thread class. Handlers are spawned from the listening
* loop and are responsible for a dealing with a single client
* and broadcasting its messages.
*/
private static class Handler extends Thread {
private String name;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private Integer length;
/**
* Constructs a handler thread, squirreling away the socket.
* All the interesting work is done in the run method.
*/
public Handler(Socket socket) {
this.socket = socket;
}
/**
* Services this thread's client by repeatedly requesting a
* screen name until a unique one has been submitted, then
* acknowledges the name and registers the output stream for
* the client in a global set, then repeatedly gets inputs and
* broadcasts them.
*/
public void run() {
try {
// Create character streams for the socket.
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Request a name from this client. Keep requesting until
// a name is submitted that is not already used. Note that
// checking for the existence of a name and adding the name
// must be done while locking the set of names.
while (true) {
out.println("SUBMITNAME");
/*Supposed to change anybody who tries to login as Admin
into different name... "Supposed" to....
if (name.equals("Admin")) {
out.println("SUBMITNAME");
return;
}*/
name = in.readLine();
length = name.length();
if (length == 0) {
out.println("SUBMITNAME");
return;
}
if (name == "null") {
out.println("SUBMITNAME");
return;
}
synchronized (names) {
if (!names.contains(name)) {
names.add(name);
break;
}
}
}
// Now that a successful name has been chosen, add the
// socket's print writer to the set of all writers so
// this client can receive broadcast messages.
out.println("NAMEACCEPTED");
//Announces that user is Online
out.println("MESSAGE " + name + " is now Online");
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + " is now Online");
}
writers.add(out);
// Accept messages from this client and broadcast them.
// Ignore other clients that cannot be broadcasted to.
while (true) {
String input = in.readLine();
System.out.println(input);
if (input == null) {
return;
}
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + ": " + input);
}
}
} catch (IOException e) {
System.out.println(e);
} finally {
// This client is going down! Remove its name and its print
// writer from the sets, and close its socket.
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + " is now Offline");
} if (name != null) {
names.remove(name);
}
if (out != null) {
writers.remove(out);
}
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}
Thanks so much for all your help in saving a complete noob at programming!
-Silver
Subscribe to:
Posts (Atom)