Download presentation
Presentation is loading. Please wait.
Published byQuentin Edwards Modified over 9 years ago
1
Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )
2
Basics OOP, I/O, Exceptions Threads Sockets Connection oriented Connectionless Cryptography API Security API JCA (JCE) Topics
3
Java Basics
4
Data encapsulation Inheritance Simple Multiple Polymorphism Parametric Sub type Information hiding Objects and Classes OOP
5
Objects and Classes Class Abstract entity representing structure Consists of declarations/definitions for variables and methods Object Instance of a class Consists of actual data and methods that operate on them Many instances of the same class The real data structure on which operations are performed
6
Java Classes Java programs are a collection of class declarations One class in each file with the file having the same name as the class Each class defines a collection of data and function members
7
Object in Java – A Class ! All classes in Java are descendants of the class Object Class descendency Trace back through the inheritance chain All chains lead to the class Object Object class is default inheritance when not specified
8
Java Package Archival of portable objects for reuse Similar to a “library” Steps for making/using a package Make an object “public” Add “package” statement to object definition Compile object source code (compiler will store compiled code according to package statement) Import object into other code via “import” statement
9
Packages Methods are grouped within classes A class is declared to be part of a package using the package keyword Classes are imported using the import keyword package srd.math; public class ComplexNumber { private double m_dReal; private double m_dImag; // constructors public ComplexNumber(double dR, double dI){ m_dReal = dR; m_dImag = dI; }
10
Class and Method Access Control Modifiers
11
Constructors A method for creating an instance of a class Same name as class it is contained in “NO” return type or return values Instance variable initialization can be done here At least one public constructor in every class Constructors (and all methods) can be overloaded Default constructor is always a “no argument” No default constructor is provided if the programmer supplies at least one
12
Constants using Final NO change in value through the lifetime of the variable Similar to the const keyword in C Variables declared with final Can be initialized in a constructor, but must be assigned a value in every constructor of the class
13
Building Composite Objects Objects with objects as instance variables Building up complex classes is good object oriented design Reuse of existing classes To detect bugs incrementally Debugging with test drivers as classes are developed
14
Symbolic Constants No global constants in Java Static members of a class give similar functionality Examples: public final static float PI = 3.1415926; where “final indicates this value cannot be altered Static variable identifier can be a class if PI definition above is contained in class Math, it can be referenced as Math.PI
15
Static Initializers Sometimes a static data member needs to be initialized too class BankAccount{ static private int m_nNextAccountNumber = 100001;} Sometimes initialization requires more steps class TelephoneConnection{ static final int m_nNUMBERCHANNELS = 64; static Channel[] m_channel;} Java provides a special construct for this purpose class TelephoneConnection{ static final int m_nNUMBERCHANNELS = 64; static Channel[] m_channel; static{ for (int i = 0; i < m_nNUMBERCHANNELS; i++){ m_channel[i] = new Channel(i); } } }
16
Class extension - Inheritance Classes can be defined as extensions (subclasses) of already-defined classes Inherits methods,variables from the parent May contain additional attribute fields May provide additional functionality by providing new methods May provide replacement functionality by overriding methods in the superclass Often, a subclass constructor executes the parent constructor by invoking super(…)
17
Overloading methods void fn(TV mytv, Radio myradio){ mytv.ChangeChannel(); // tune the TV myradio.ChangeChannel(); // tune the radio } Current class assumed when no qualification Overloading based on different types of arguments double fn(BankAccount baMyAccount){ baMyAccount.Rate(8.0); // sets the rate return baMyAccount.Rate(); // queries the rate } No overloading based on return value
18
this keyword A class declaration is like a template for making objects The code is shared by all objects of the class Each object has its own values for the data members The object itself is an implicit parameter to each method In the class declarations, one can use the keyword “this” to refer to the object itself explicitly
19
Java I/O - Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for data (sometimes both) Different streams have different characteristics A file has a definite length, and therefore an end Keyboard input has no specific end
20
How to do I/O import java.io.*; Open the stream Use the stream (read, write, or both) Close the stream
21
Why Java I/O is hard Java I/O is very powerful, with an overwhelming number of options Any given kind of I/O is not particularly difficult Buffered Formatted etc The trick is to find your way through the maze of possibilities It’s all about picking the right one
22
Opening a stream When you open a stream, you are making a connection to an external entity The entity to which you wish to write data to or read data from Streams encapsulate complexity of external entity Streams also provide flexibility in usage of data – Different types
23
Example - Opening a stream A FileReader is a used to connect to a file that will be used for input FileReader fileReader = new FileReader(fileName); The fileName specifies where the (external) file is to be found You never use fileName again; instead, you use fileReader
24
Using a stream Some streams can be used only for input, others only for output, still others for both Using a stream means doing input from it or output to it But it’s not usually that simple One needs to manipulate the data in some way as it comes in or goes out
25
Example of using a stream int ch; ch = fileReader.read( ); The fileReader.read() method reads one character and returns it as an integer, or -1 if there are no more characters to read (EOF) The meaning of the integer depends on the file encoding (ASCII, Unicode, other)
26
Closing A stream is an expensive resource There is a limit on the number of streams that you can have open at one time You should not have more than one stream open on the same file You must close a stream before you can open it again Always close your streams!
27
Serialization You can also read and write objects to files Object I/O goes by the awkward name of serialization Serialization can be very difficult objects may contain references to other objects Java makes serialization (almost) easy
28
Conditions for serializability If an object is to be serialized The class must be declared as public Class must implement Serializable The class must have a no-argument constructor All fields of the class must be serializable Either primitive types or serializable objects
29
Exceptions Historically, programs would provide a message and halt on errors Hardly acceptable in today’s interactive environment In Java, methods “throw” exceptions when such errors occur Method which invoked the method encountering the error can either “catch” the exception, or pass it up the heirarchy
30
General exception handling If you write code including methods from which an exception may be thrown, here is an outline of what to do
31
Exception Example package srd.math; import java.lang.Exception; public class ComplexNumber{ //... other data and methods as before // division operator written to use exceptions public ComplexNumber Divide(double d) throws Exception{ if (d == 0.0){ throw new Exception("Divide by zero in ComplexNumber.divide"); } return new ComplexNumber(m_dReal / d, m_dImag / d); }}
32
Java Threads
33
Multitasking v/s Multithreading Multitasking refers to a computer's ability to perform multiple jobs concurrently A thread is a single sequence of execution within a program Multithreading refers to multiple threads of control within a single program each program can run multiple threads of control within it
34
Threads - Need To maintain responsiveness of an application during a long running task To enable cancellation of separable tasks Some problems are intrinsically parallel Some APIs and systems demand it Swings Animation
35
Example - Animation Suppose you set up Buttons and attach Listeners to those buttons Then your code goes into a loop doing the animation Who’s listening ? Not this code; it’s busy doing the animation sleep( ms ) doesn’t help!
36
Application Thread When we execute an application The JVM creates a Thread object whose task is defined by the main() method It starts the thread The thread executes the statements of the program one by one until the method returns and the thread dies
37
Multiple Threads Each thread has its private run-time stack If two threads execute the same method, each will have its own copy of the local variables the methods uses All threads see the same dynamic memory, heap Two different threads can act on the same object and same static fields concurrently Race conditions Deadlocks
38
Creating Threads There are two ways to create our own Thread object 1. Sub classing the Thread class and instantiating a new object of that class 2. Implementing the Runnable interface In both cases the run() method should be implemented
39
Example – Sub class public class ThreadExample extends Thread { public void run () { for (int i = 1; i <= 100; i++) { System.out.println( “ Thread: ” + i); } } }
40
Thread Methods void start() Creates new thread and makes it runnable This method can be called only once void run() The new thread begins its life inside this method void stop() The thread is being terminated
41
Thread Methods (Continued) yield() Causes currently executing thread object to temporarily pause and allow other threads to execute Allows only threads of the same priority to run sleep(int m)/sleep(int m,int n) The thread sleeps for m milliseconds, plus n nanoseconds
42
Example - Implementing Runnable public class RunnableExample implements Runnable { public void run () { for (int i = 1; i <= 100; i++) { System.out.println ( “ Runnable: ” + i); } } }
43
Why two mechanisms ? Java supports simple inheritance A class can have only one super class But it can implement many interfaces Allows threads to run, regardless of inheritance Example – an applet that is also a thread
44
Starting the Threads public class ThreadsStartExample { public static void main (String argv[]) { new ThreadExample ().start (); new Thread(new RunnableExample ()).start (); }
45
Scheduling Threads I/O operation completes start() Currently executed thread Ready queue Newly created threads
46
Alive Thread State Diagram New ThreadDead Thread Running Runnable new ThreadExample(); run() method returns while (…) { … } Blocked Object.wait() Thread.sleep() blocking IO call waiting on a monitor thread.start();
47
Example public class PrintThread1 extends Thread { String name; public PrintThread1(String name) { this.name = name; } public void run() { for (int i=1; i<500 ; i++) { try { sleep((long)(Math.random() * 100)); } catch (InterruptedException ie) { } System.out.print(name); } }
48
Example (cont) public static void main(String args[]) { PrintThread1 a = new PrintThread1("*"); PrintThread1 b = new PrintThread1("-"); PrintThread1 c = new PrintThread1("="); a.start(); b.start(); c.start(); }
49
Scheduling Thread scheduling is the mechanism used to determine how runnable threads are allocated CPU time Priority is taken into consideration Thread-scheduling mechanisms preemptive or nonpreemptive
50
Preemptive Scheduling Preemptive scheduling Scheduler preempts a running thread to allow different threads to execute Nonpreemptive scheduling Scheduler never interrupts a running thread The nonpreemptive scheduler relies on the running thread to yield control of the CPU so that other threads may execute
51
Java Scheduling Scheduler is preemptive and based on priority of threads Uses fixed-priority scheduling Threads are scheduled according to their priority w.r.t. other threads in the ready queue The highest priority runnable thread is always selected for execution When multiple threads have equally high priorities, only one of those threads is guaranteed to be executing Java threads are guaranteed to be preemptive but not time sliced
52
Thread Priority Every thread has a priority When a thread is created, it inherits the priority of the thread that created it The priority values range from 1 to 10, in increasing priority The priority can be adjusted using setPriority() and getPriority() methods Pre defined priority constants MIN_PRIORITY=1 MAX_PRIORITY=10 NORM_PRIORITY=5
53
ThreadGroup The ThreadGroup class is used to create groups of similar threads. Why is this needed? “Thread groups are best viewed as an unsuccessful experiment, and you may simply ignore their existence.” Joshua Bloch, software architect at Sun
54
Race Condition Race conditions Outcome of a program is affected by the order in which the program's threads are allocated CPU time Two threads are simultaneously modifying a single object Both threads “race” to store their value Outcome depends on which one wins the “race”
55
Monitors Each object has a “monitor” that is a token used to determine which application thread has control of a particular object instance In execution of a synchronized method (or block), access to the object monitor must be gained before the execution Synchronized method – Method that executes critical section Access to the object monitor is queued This avoids “Race Conditions”
56
Example public class BankAccount { private float balance; public synchronized void deposit(float amount) { balance += amount; } public synchronized void withdraw(float amount) { balance -= amount; }
57
Static Synchronized Methods Marking a static method as synchronized, associates a monitor with the class itself The execution of synchronized static methods of the same class is mutually exclusive. Why?
58
Example public class PrintThread2 extends Thread { String name; public PrintThread2(String name) { this.name = name; } public static synchronized void print(String name) { for (int i=1; i<500 ; i++) { try { Thread.sleep((long)(Math.random() * 100)); } catch (InterruptedException ie) { } System.out.print(str); } }
59
Example (cont) public void run() { print(name); } public static void main(String args[]) { PrintThread2 a = new PrintThread2("* “ ); PrintThread2 b = new PrintThread2("- “ ); PrintThread2 c = new PrintThread2("= “ ); a.start(); b.start(); c.start(); } }
60
Synchronized Statements A monitor can be assigned to a block It can be used to monitor access to a data element that is not an object, e.g., array Example: void arrayShift(byte[] array, int count) { synchronized(array) { System.arraycopy (array, count,array, 0, array.size - count); } }
61
The wait() Method The wait() method is part of the java.lang.Object interface It requires a lock on the object ’ s monitor to execute It must be called from a synchronized method, or from a synchronized segment of code Why?
62
The wait() Method wait() causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object Upon call for wait(), the thread releases ownership of this monitor and waits until another thread notifies the waiting threads of the object
63
The wait() Method wait() is also similar to yield() Both take the current thread off the execution stack and force it to be rescheduled However, wait() is not automatically put back into the scheduler queue notify() must be called in order to get a thread back into the scheduler ’ s queue
64
Things Thread should NOT do The Thread controls its own destiny Deprecated methods myThread.stop( ) myThread.suspend( ) myThread.resume( ) Outside control turned out to be a Bad Idea Don’t do this!
65
Controlling another Thread Don’t use the deprecated methods! Instead, put a request where the other Thread can find it boolean okToRun = true; animation.start( ); public void run( ) { while (controller.okToRun) {…}
66
Java Sockets
67
Why Java Sockets ? Why use sockets to communicate with remote objects when RMI is available? To communicate with non-java objects and programs Not all software on networks is written in Java To communicate as efficiently as possible Convenience of RPC and RMI extract a price in the form of processing overhead A well-designed socket interface between programs can outperform them
68
What Is a Socket ? Server side Server has a socket bound to a specific port number The server just waits, listening to the socket for a client to make a connection request If everything goes well, the server accepts the connection Upon acceptance, the server gets a new socket bound to a different port Client-side The client knows the hostname of the machine on which the server is running and the port number to which the server is connected To make a connection request, the client tries to rendezvous with the server on the server's machine and port if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server The client and server can now communicate by writing to or reading from their sockets.
69
Socket Communication There are two forms of socket communication, connection oriented and connectionless TCP (Transmission Control Protocol) TCP is a connection oriented, transport layer protocol that works on top of IP Provides a permanent connection oriented virtual circuit Circuit has to be established before data transfer can begin The client will send out a send a number of initialization packets to the server so that the circuit path through the network can be established A host will usually establish two streams, one for incoming and one for out going data Other mechanisms to ensure that data integrity is maintained Packets are numbered to avoid lost packets and incorrect ordering
70
Socket Communication Overview UDP (User Datagram Protocol) UDP is a connectionless transport layer protocol that also sits on top of IP Provides no data integrity mechanisms except for checksum Simply packages it’s data into, what is known as a Datagram, along with the destination address and port number If the destination host is alive and listening it will receive the Datagram No guaranteed delivery, there is a possibility that datagrams will be lost corrupted or delivered in the wrong order Protocol has few built-in facilities thereby resulting in very low management overhead Lack of "permanent" connection also means UDP can adapt better to network failures Examples - DNS lookups, PING
71
Network byte ordering Standard way in which bytes are ordered for network communication Network byte order says that the high-byte (the byte on the right) should be written first and low-byte (the byte on the left) last For example, the following byte representation of an integer, 10 12 45 32 should be written 32 45 12 10 when sending it across the network
72
Socket communication: Java Classes Classes listed below are from java.net and java.io packages Obtaining Internet address information Class InetAddress This class provides methods to access host names and IP addresses The following methods are provided to create InetAddress objects Static InetAddress getLocalHost() throws UnknownHostException Static InetAddress getByName(String host) throws UnknownHostException The host name can be either a pneumonic identifier such as "www.Java.com" or an IP address such as 121.1.28.54
73
Socket Class Class Socket These constructors allow the Socket connection to be established Socket(String host, int port) throws IOException This creates a Socket and connects to the specified host and port Host can be a host name or IP address and port must be in a range of 1- 65535 Socket(InetAddress address, int port) throws IOException This creates a Socket and connects to the specified port The port must be in a range of 1-65535 InetAddress getInetAddress() This method returns the IP address of a remote host int getPort() This method returns the port number of the remote host int getLocalPort() The local port number is returned by this method
74
I/O Streams InputStream getInputStream()throws IOException Returns an InputStream that allows the Socket to receive data across the TCP connection An InputStream can be buffered or standard OutputStream getOutputStream()throws IOException Returns an OutputStream that allows the Socket to send data across the TCP connection An OutputStream should be buffered to avoid lost bytes, especially when the Socket is closed void close() throws IOException Closes the Socket, releasing any network resources
75
Exceptions IOException Generic I/O error that can be thrown by many of the methods SecurityException Thrown if the Java security manager has restricted the desired action Applets may not open sockets to any host other than the originating host, i.e. the web server Any attempt to open a socket to a destination other than the host address will cause this exception to be thrown
76
TCP Client Connections - Sample Code // Input and output streams for TCP socket protected DataInputStream in; protected DataOutputStream out; protected Socket connect (int port) throws IOException { // Connect method output.appendText ("\nHi\n"); Socket socket = new Socket (server, port); OutputStream rawOut = socket.getOutputStream(); InputStream rawIn = socket.getInputStream (); BufferedOutputStream buffOut = new BufferedOutputStream (rawOut); out = new DataOutputStream (buffOut); in = new DataInputStream (rawIn); return socket; }
77
ServerSocket Class The ServerSocket class creates a Socket for each client connection ServerSocket(int port, int count) throws IOException Constructs a ServerSocket that listens on the specified port of the local machine Argument 1 is mandatory, but argument 2, the outstanding connection requests parameter, may be omitted Default of 50 is used Socket accept() throws IOException This method blocks until a client makes a connection to the port on which the ServerSocket is listening void close() throws IOException This method closes the ServerSocket It does not close any of the currently accepted connections int getLocalPort() Returns the integer value of the port on which ServerSocket is listening
78
TCP Server Connections - Code Example static Socket accept (int port) throws IOException { // Setup ServerSocket ServerSocket server = new ServerSocket (port); Socket ClientSocket = server.accept (); // Extract the address of the connected user System.out.println ("Accepted from " + ClientSocket.getInetAddress ()); server.close (); // return the client sock so that communication can begin return ClientSocket; } }
79
Datagram Communication When using Datagram communication there are several differences to stream based TCP Firstly a datagram packet is required, as we do not have a "permanent" stream we cannot simply read and write data to and from a communication channel Instead we must construct datagrams, that contains the destination address, the port number, the data and the length of the data Therefore we must deal with creating and dissecting packets
80
DatagramPacket Class Class DatagramPacket Used to create the datagram packets for transmission and receipt DatagramPacket(byte inbuf[], int buflength) Constructs a datagram packet for receiving datagrams Inbuff is a byte array that holds the data received and buflength is the maximum number of bytes to read DatagramPacket(byte inbuf[], int buflength, InetAddress iaddr, int port) Constructs a datagram packet for transmission iaddr is the address of the destination and port is the port number on the remote host int getPort() Returns the port number of the packet byte() getData() Returns a byte array corresponding to the data in the DatagramPacket
81
Example protected DatagramPacket buildPacket (String message, String host, int port) throws IOException { // Create a byte array from a string ByteArrayOutputStream byteOut = new ByteArrayOutputStream (); DataOutputStream dataOut = new DataOutputStream (byteOut); dataOut.writeBytes(message); byte[] data = byteOut.toByteArray (); //Return the new object with the byte array payload return new DatagramPacket (data, data.length, InetAddress.getByName(host), port); }
82
Class DatagramSocket Used to create sockets for DatagramPackets DatagramSocket(int port) throws SocketException Creates a DatagramSocket using the specified port number void send(DatagramPacket p) throws IOException Sends the packet out onto the network syncronized void receive(DatagramPacket p) throws IOException Receives a packet into the specified DatagramPacket Blocks until a packet has been received successfully. syncronized void close() Closes the DatagramSocket
83
Example protected void receivePacket () throws IOException { byte buffer[] = new byte[65535]; DatagramPacket packet = new DatagramPacket (buffer,buffer.length); socket.receive (packet); // Convert the byte array read from network into a string ByteArrayInputStream byteIn = new ByteArrayInputStream (packet.getData (), 0, packet.getLength ()); DataInputStream dataIn = new DataInputStream (byteIn); // Read in data from a standard format String input = ""; while((input = dataIn.readLine ()) != null) output.appendText("SERVER REPLIED : " + input +); }
84
Java Cryptography
85
Goals Learn about JAVA Crypto Architecture How to use JAVA Crypto API’s Understand the SunJCE Implementation Be able to use java crypto functions (meaningfully) in your code
86
Introduction JDK Security API Core API for Java Built around the java.security package First release of JDK Security introduced "Java Cryptography Architecture" (JCA) Framework for accessing and developing cryptographic functionality JCA encompasses Parts of JDK 1.2 Security API related to cryptography Architecture that allows for multiple and interoperable cryptography implementations The Java Cryptography Extension (JCE) extends JCA Includes APIs for encryption, key exchange, and Message Authentication Code (MAC)
87
Java Cryptography Extension (JCE) Adds encryption, key exchange, key generation, message authentication code (MAC) Multiple “providers” supported Keys & certificates in “keystore” database Separate due to export control
88
JCE Architecture JCE: Cipher KeyAgreement KeyGenerator SecretKeyFactory MAC CSP 1 CSP 2 SPI API App 1App 2
89
Design Principles Implementation independence and interoperability "provider“ based architecture Set of packages implementing cryptographic services digital signature algorithms Programs request a particular type of object Various implementations working together, use each other's keys, or verify each other's signatures Algorithm independence and extensibility Cryptographic classes providing the functionality Classes are called engine classes, example Signature Addition of new algorithms straight forward
90
Building Blocks Key Certificate Keystore Message Digest Digital Signature SecureRandom Cipher MAC
91
Engine Classes and SPI Interface to specific type of cryptographic service Defines API methods to access cryptographic service Actual implementation specific to algorithms For example : Signature engine class Provides access to the functionality of a digital signature algorithm Actual implementation supplied by specific algorithm subclass "Service Provider Interface" (SPI) Each engine class has a corresponding abstract SPI class Defines the Service Provider Interface to be used by implementors SPI class is abstract - To supply implementation, provider must subclass
92
JCA Implementation SPI (Service Provider Interface) say FooSpi Engine Foo Algorithm MyAlgorithm Foo f = Foo.getInstance(MyAlgorithm);
93
General Usage No need to call constructor directly Define the algorithm reqd. getInstance() Initialize the keysize init() or initialize() Use the Object generateKey() or doFinal()
94
java.security classes Key KeyPair KeyPairGenerator KeyFactory Certificate CertificateFactory Keystore MessageDigest Signature SignedObject SecureRandom
95
Key Types SecretKey PublicKey PrivateKey Methods getAlgorthm() getEncoded() KeyPair= {PrivateKey, PublicKey}
96
KeyGenerator Generates instances of key Requires Algorithm getInstance(algo) Keylength, (random) Initialize(param, random) Generates required key/keypair
97
KeyFactory/SecretKeyFactory Converts a KeySpec into Keys KeySpec Depends on the algorithm Usually a byte[] (DES) Could also be a set of numbers (DSA) Required when the key is encoded and transferred across the network
98
Certificate Problem Java.security.Certificate is an interface Java.security.cert.Certificate is a class Which one to use when you ask for a Certificate? Import only the correct type Avoid “import java.security.*” Use X509Certificate
99
KeyStore Access to a physical keystore Can import/export certificates Can import keys from certificates Certificate.getPublicKey() Certificate.getPrivateKey() Check for certificate validity Check for authenticity
100
keytool Reads/writes to a keystore Unique alias for each certificate Password Encrypted Functionality Import Sign Request Export NOTE: Default is DSA !
101
Signature DSA, RSA Obtain a Signature Object getInstance(algo) getInstance(algorithm,provider)
102
Signature (signing) Initialize for signing initSign(PrivateKey) Give the data to be signed update(byte [] input) and variations doFinal(byte [] input) and variations Sign byte[] Signature.sign() NOTE: Signature does not contain the actual signature
103
Signature (verifying) Initialize for verifying initVerify(PublicKey) Give the data to be verifieded update(byte [] input) and variations doFinal(byte [] input) and variations Verify boolean Signature.verify()
104
SignedObject Signs and encapsulates a signed object Sign SignedObject(Serializable, Signature) Recover Object getContent() byte[] getSignature() Verify Verify(PublicKey, Signature) ! Need to initialize the instance of the signature
105
javax.crypto classes Cipher Mac KeyGenerator SecretKeyFactory SealedObject
106
Cipher DES, DESede, RSA, Blowfish, IDEA … Obtain a Cipher Object getInstance(algorithm/mode/padding) or getInstance(algorithm) or getInstance(algorithm, provider) eg “DES/ECB/NoPadding” or “RSA” Initialize init(mode, key) mode= ENCRYPT_MODE / DECRYPT_MODE
107
Cipher cont. Encrypt/Decrypt byte[] update(byte [] input) and variations byte[] doFinal(byte [] input) and variations Exceptions NoSuchAlgorithmException NoSuchPadding Exception InvalidKeyException
108
SealedObject Encrypts and encapsulates an encrypted object Encrypt SealedObject(Serializable, Cipher) Recover getObject(Cipher) or getObject(key) Cipher mode should be different!!
109
Wrapper Class : Crypto.java Adding a provider public Crypto() { java.security.Security.addProvider(new cryptix.provider.Cryptix());}
110
Enrcyption using RSA public synchronized byte[] encryptRSA(Serializable obj, PublicKey kPub) throws KeyException, IOException { try { Cipher RSACipher = Cipher.getInstance("RSA"); return encrypt(RSACipher, obj, kPub); } catch (NoSuchAlgorithmException e) { System.exit(1); } return null; }
111
Decryption using RSA public synchronized Object decryptRSA(byte[] msgE, PrivateKey kPriv) throws KeyException, IOException { try { Cipher RSACipher = Cipher.getInstance("RSA"); return decrypt(RSACipher, msgE, kPriv); } catch (NoSuchAlgorithmException e) { System.exit(1); } return null; }
112
Creating a signature public synchronized byte[] sign(byte[] msg, PrivateKey kPriv) throws SignatureException, KeyException, IOException { // Initialize the signature object for signing debug("Initializing signature."); try { Signature RSASig = Signature.getInstance("SHA-1/RSA/PKCS#1"); debug("Using algorithm: " + RSASig.getAlgorithm()); RSASig.initSign(kPriv); RSASig.update(msg); return RSASig.sign(); } catch (NoSuchAlgorithmException e) { System.exit(1); } return null; }
113
Verifying a signature public synchronized boolean verify(byte[] msg, byte[] sig, PublicKey kPub) throws SignatureException, KeyException { // Initialize the signature object for verifying debug("Initializing signature."); try { Signature RSASig = Signature.getInstance("SHA- 1/RSA/PKCS#1"); RSASig.initVerify(kPub); RSASig.update(msg); return RSASig.verify(sig); } catch (NoSuchAlgorithmException e) { System.exit(1); } return false; }
114
References Sun’s Java website: http://java.sun.com
115
Thanks for staying awake
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.