-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRSACipher.java
More file actions
62 lines (59 loc) · 1.86 KB
/
RSACipher.java
File metadata and controls
62 lines (59 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package week03;
import java.math.BigInteger;
import java.util.Random;
/**
*
* @author levan
*/
public class RSACipher {
private BigInteger p,q,N,r,E,D;
private int bitLength;
public RSACipher(int bitLength){
this.bitLength = bitLength;
generateKeys();
}
private void generateKeys(){
p=BigInteger.probablePrime(bitLength / 2, new Random());
q=BigInteger.probablePrime(bitLength / 2, new Random());
N=p.multiply(q);
r= p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
do{
E = new BigInteger(bitLength, new Random());
}while ((E.compareTo(r) != -1)|| (E.gcd(r).compareTo(BigInteger.ONE) !=0));
D = E.modInverse(r);
}
public BigInteger[] encrypt (String message){
byte[] bytes= message.getBytes();
BigInteger[ ]encrypted = new BigInteger[bytes.length];
for (int i=0; i<bytes.length;i++){
encrypted[i]= new BigInteger(new byte []{bytes[i]}).modPow(E, N);
}
return encrypted;
}
public String decrypt(BigInteger[] message, BigInteger d, BigInteger n){
byte[] bytes = new byte[message.length];
for(int i=0;i<message.length;i++){
bytes[i] = message[i].modPow(d, n).byteValue();
}
return new String(bytes);
}
public BigInteger getP(){
return p;
}
public BigInteger getQ(){
return q;
}
public BigInteger getN(){
return N;
}
public BigInteger getE(){
return E;
}
public BigInteger getD(){
return D;
}
}