# Calculate e to the power x

Use the static method exp in the Math class:

```import java.math.*;

public class Main
{
public static void main(String args[]) throws Exception {
System.out.println(Math.exp(2.5));
System.out.println(Math.pow(Math.E, 2.5));
}
}
```

outputs:

```12.182493960703473
12.182493960703471
```

# Determining whether a BigInteger is prime

The class BigInteger has a method isProbablePrime that takes a certainty argument that determines how sure you can be about the result. The probability that the number is prime is (1 – 1/2^certainty).
We can deduct:

```for certainty:
1  --> P(number is prime) > 0.5
2  --> P(number is prime) > 0.75
5  --> P(number is prime) > 0.96875
10 --> P(number is prime) > 0.9990234375
20 --> P(number is prime) > 0.99999904632568359375
```

The higher the certainty, the longer it takes to compute.

Main.java:

```import java.math.*;

public class Main {
public static void main(String args[]) {
calculatePrimes(1);
calculatePrimes(5);
calculatePrimes(10);
calculatePrimes(20);
}

public static void calculatePrimes(int certainty) {
System.out.println("With certainty " + certainty);
System.out.println(new BigInteger("12345678").isProbablePrime(certainty));
System.out.println(new BigInteger("87654321").isProbablePrime(certainty));
System.out.println(new BigInteger("13").isProbablePrime(certainty));
System.out.println(new BigInteger("3215031751").isProbablePrime(certainty));
System.out.println();
}
}
```

outputs:

```With certainty 1
false
false
true
true

With certainty 5
false
false
true
false

With certainty 10
false
false
true
false

With certainty 20
false
false
true
false
```

# What does the setSoLinger option do?

It allows you to control a TCP socket close() method. eg.

```socket.setSoLinger(true, 5000);
...
socket.close();
```

the socket.close() method will block until the the data that is still
in the send-buffer is sent to the other end and acknowledged. If the linger
delay has passed (5000 milliseconds in this case), the socket will be forced
to be closed.

# Difference between a Socket and a ServerSocket

Socket class is meant for client side, so in a client side u need to make a object of Socket class for any networking application,
whereas for server side networking application ServerSocket class is used, in this class method named as serversocket_object.accept() is used by server to listen to clients at specific port addresses, for local computer it is either “localhost” or “127.0.0.1″ and might be u’r subnet address in case of some LAN.

# What is a digital signature?

A digital signature is an extra chunk of data send along with an (encrypted) message which tells the receiver that the message is coming from the one who claims to have sent it. It ensures that the message has not been tampered with by a man-in-the-middle, a person who spies on the communication line and intercepts messages. You also have a proof that the sender is the one who holds the private key of a public-private key pair.

It goes as follows:

```   - Two parties, A and B.  A wants to send a message M to B.

+-----+                              +-----+
|  A  |                              |  B  |
+-----+                              +-----+
- holds private key PVT of       - holds public key PUB of
public-private key pair          public-private key pair

Sender:
1. A calculates a message digest MD on M
2. A encrypts that message digest MD with his private
key PVT (A is the only one that has the private key
that belongs to him!) = digital signature DS
3. A sends message M and DS to B

1. B receives the message M and digital signature DS
2. B decrypts the digital signature DS with the public
key PUB and gets MD
3. B calculates a message digest on M = MD2
4. B compares MD with MD2.  Equality means that the
the PVT-PUB key pair.
```

But who says this public/private pair belongs to me? I could have identified myself as someone else, generate such a pair and distribute the public key to a sender who believes I am someone else and trick him with this above process claiming to be that someone else…

That’s where digital certificates come in. Check out What is a digital certificate?

# What is a message authentication code (MAC)?

A MAC is a type of a message digest but that requires a key. It uses that key to encrypt the hash. Only the receiver, who has access to that key, can decrypt the hash and verify whether the message has not been tampered with.

This is to solve the problem that a man-in-the-middle, one that spies the communication line, intercepts a message with a conventional message digest and then sends out another message with another message digest. The receiver is unable to know whether the whole thing comes from the original sender. If the sender and receiver would use a MAC utilizing a (secret) key, there would be no way for the man-in-the-middle to intercept and send out a new message as he doesn’t know the key.

The problem with MACs is that secret keys need to be shared between both parties.

A MAC works with available hashing methods (MD5 or SHA).

# How do I encrypt/decrypt using Twofish?

Main.java:

```import javax.crypto.spec.*;
import java.security.*;
import javax.crypto.*;
import org.bouncycastle.util.encoders.Hex;

public class Main
{
public static void main(String []args) throws Exception {
String toEncrypt = "The shorter you live, the longer you're dead!";

System.out.println("Encrypting...");

System.out.println("Decrypting...");

System.out.println("Decrypted text: " + decrypted);
}

public static byte[] encrypt(String toEncrypt, String key) throws Exception {
// create a binary key from the argument key (seed)
SecureRandom sr = new SecureRandom(key.getBytes());
KeyGenerator kg = KeyGenerator.getInstance("twofish");
kg.init(sr);
SecretKey sk = kg.generateKey();

// create an instance of cipher
Cipher cipher = Cipher.getInstance("twofish");

// initialize the cipher with the key
cipher.init(Cipher.ENCRYPT_MODE, sk);

// enctypt!
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());

return encrypted;
}

public static String decrypt(byte[] toDecrypt, String key) throws Exception {
// create a binary key from the argument key (seed)
SecureRandom sr = new SecureRandom(key.getBytes());
KeyGenerator kg = KeyGenerator.getInstance("twofish");
kg.init(sr);
SecretKey sk = kg.generateKey();

// do the decryption with that key
Cipher cipher = Cipher.getInstance("twofish");
cipher.init(Cipher.DECRYPT_MODE, sk);
byte[] decrypted = cipher.doFinal(toDecrypt);

return new String(decrypted);
}
}```

(tested with the BouncyCastle JCE provider, http://www.bouncycastle.org)

# Tokenizing a text into non-breakable substrings

Use the BreakIterator class. First get an instance through the factory method getLineInstance, initialize it with the text using setText and iterate through the elements with first and next.
The LineInstance BreakIterator determines where a linebreak can occur. It breaks between a sequence of whitespace or a hyphen.

This example uses the following text: text.txt:

```It is, in fact, nothing short of a miracle that the modern methods
of instruction have not yet entirely strangled the holy curiosity
of inquiry; for this delicate little plant, aside from stimulation,
stands mainly in need of freedom; without this it goes to wrack and
ruin without fail. It is a very grave mistake to think that the
enjoyment of seeing and searching can promoted by means of coercion
and sense of duty. To the contrary, I believe that it would be
possible to rob even a healthy beast of prey of its voraciousness,
if it were possible, with the aid of a whip, to force the beast to
devour continuously, even when not hungry,especiallyif the food,
handed out under such coercion, were to be selected accordingly.

Albert Einstein ```

Main.java:

```import java.text.*;
import java.io.*;

public class Main {
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Usage: java Main <file.txt>");
System.exit(1);
}

BreakIterator biLine = BreakIterator.getLineInstance();
biLine.setText(text);
System.out.println("Splitting text up into line breaksn");
printInstances(biLine, text);
}

public static void printInstances(BreakIterator bi, String text) {
int start = bi.first();
int end = bi.next();
while (end != BreakIterator.DONE) {
System.out.println("Found: " + text.substring(start, end));
start = end;
end = bi.next();
}
}

public static String readFile(String filename) {
StringBuffer total = new StringBuffer();

try {
String line;
while ((line = br.readLine()) != null) {
total.append(line + "n");
}
}
catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
```

outputs:

```Splitting text up into line breaks

Found: It
Found: is,
Found: in
Found: fact,
Found: nothing
Found: short
Found: of
Found: a
Found: miracle
Found: that
Found: the
Found: modern
Found: methods

Found: of
Found: instruction
Found: have
Found: not
Found: yet
. . .
```

# Using a TreeSet in Java

A TreeSet maintains objects in sorted order by using a balanced red-black tree. A red-black tree is a balanced binary tree, meaning a parent node has maximum 2 children and as an entry is inserted, the tree is monitored as to keep it well-balanced. For more information about red-black trees, check out the sites below!

Keeping the binary tree balanced ensures the fast lookup time of O(log n). Not as fast as a HashMap (lookup time is constant), but remember that the TreeSet has the advantage of being sorted on key.

This example creates a typical TreeSet but also shows you how to manipulate the way objects are inserted into the tree by passing in a custom Comparator object.

Main.java:

```import java.util.*;
import java.io.*;

public class Main
{
public static void main(String []args) throws Exception {
String[] keywords = { "volatile", "boolean", "private", "case", "cast",
"catch", "void", "switch", "instanceof", "transient",
"do", "implements", "double", "else", "extends", "final",
"float", "for", "this", "future", "generic", "goto", "if",
"finally", "import", "break", "continue", "int", "operator",
"interface", "long", "native", "inner", "new",
"outer", "package", "byte", "protected", "throws", "public",
"rest", "return", "short", "static", "super", "class",
"synchronized", "throw", "default", "null",
"try", "var", "abstract", "char" };

// convert this array to a Collection and create a HashSet
TreeSet ts = new TreeSet(Arrays.asList(keywords));

System.out.print("First version of TreeSet, sorted ascendingly:nnt");
System.out.println(ts);

TreeSet ts2 = new TreeSet(new Comparator() {
public int compare(Object o1, Object o2) {
return -((String) o1).compareTo(o2);
}
});

System.out.print("nSecond version of TreeSet, sorted descendingly:nnt");
System.out.println(ts2);
}
}
```

outputs:

```First version of TreeSet, sorted ascendingly:

[abstract, boolean, break, byte, case, cast, catch, char, class, continue,
default, do, double, else, extends, final, finally, float, for, future, generic,
goto, if, implements, import, inner, instanceof, int, interface, long,
native, new, null, operator, outer, package, private, protected, public, rest,
return, short, static, super, switch, synchronized, this, throw, throws,
transient, try, var, void, volatile]

Second version of TreeSet, sorted descendingly:

[volatile, void, var, try, transient, throws, throw, this,
synchronized, switch, super, static, short, return, rest, public, protected,
private, package, outer, operator, null, new, native, long, interface, int,
instanceof, inner, import, implements, if, goto, generic, future, for, float,
finally, final, extends, else, double, do, default, continue, class,
char, catch, cast, case, byte, break, boolean, abstract]
```

# Reading a text resource from a jar file

This example reads the file ansi.txt that is stored in rt.jar. Just make sure the jar file in which your text file is stored is in your classpath!

Main.java:

```import java.io.*;
import java.util.*;
import java.util.jar.*;

public class Main
{
public static void main(String[] args) throws IOException
{
System.out.println(getTextResourceFromJar("javax/swing/text/rtf/charsets/ansi.txt"));
}

public static String getTextResourceFromJar(String resourceName) throws IOException {
InputStream is = Main.class.getResourceAsStream(resourceName);