1 package testrsa;
2
3 import java.io.UnsupportedEncodingException;
4 import java.math.BigInteger;
5
6
7
8
9 @author
10
11 public class RSAToString {
12
13 RSA rsa = null;
14
15
16
17 @param
18
19 public RSAToString(RSA rsa) {
20
21 this.rsa = rsa;
22
23 }
24
25
26
27
28
29
30
31 @param
32 @return
33
34 public String doEncryption(String s) {
35 BigInteger big = new BigInteger("0");
36 try {
37 byte[] b = s.getBytes("ISO-8859-1");
38 big = rsa.encrypt(this.byteToBigInteger(b));
39 } catch (RsaException ex) {
40 ex.printStackTrace();
41 } catch (UnsupportedEncodingException ex) {
42 ex.printStackTrace();
43 }
44
45 return this.BigIntegerToHexString(big);
46
47 }
48
49
50 <br><br>
51
52
53
54
55
56 @param
57 @return
58 @throws
59
60
61 public String doDecryption(String s) {
62 BigInteger big = new BigInteger(s, 16);
63 try {
64 big = rsa.decrypt(big);
65 } catch (RsaException ex) {
66 ex.printStackTrace();
67 }
68
69
70 return this.BigIntegerToString(big).trim();
71
72 }
73
74
75
76 @param
77 @return
78
79 public String doSign(String s) {
80
81 BigInteger big = new BigInteger(s, 16);
82 try {
83 big = rsa.sign(big);
84 } catch (RsaException ex) {
85 ex.printStackTrace();
86 }
87
88
89 return this.BigIntegerToHexString(big);
90 }
91
92
93 <br><br>
94
95
96 <br><br>
97
98
99
100
101 <br><br>
102
103
104
105 @param
106 @return
107 @throws
108
109 public String doVerify(String s) {
110
111 BigInteger big = new BigInteger(s, 16);
112
113 big = rsa.verify(big);
114 return this.BigIntegerToHexString(big);
115
116 }
117
118
119
120
121 @param
122 @return
123
124 private BigInteger byteToBigInteger(byte[] b) {
125 BigInteger bigInt = new BigInteger("0");
126
127 for (int i = 0; i < b.length; i++) {
128 bigInt = bigInt.shiftLeft(8);
129 Integer value = new Integer((b[i] & 0x7F) + (b[i] < 0 ? 128 : 0));
130 bigInt = bigInt.or(new BigInteger(value.toString()));
131 }
132 return bigInt;
133 }
134
135
136 <br><br>
137
138
139
140
141
142 @param
143 @return
144
145 private String BigIntegerToString(BigInteger big) {
146 byte[] bnew = big.toByteArray();
147 StringBuffer sb = new StringBuffer();
148 for (int i = 0; i < bnew.length; i++) {
149 int value = (bnew[i] & 0x7F) + (bnew[i] < 0 ? 128 : 0);
150 sb.append((char) value);
151 }
152 return sb.toString();
153 }
154
155
156
157 @param
158 @return
159
160 private String BigIntegerToHexString(BigInteger big) {
161
162 String str = big.toString(16);
163
164
165 return str;
166
167 }
168
169
170
171
172 @param
173 @param
174 @return
175
176 public String fitStringToOneSize(String str, int Blocksize) {
177
178 StringBuffer sbuftemp = new StringBuffer(str);
179 int block = str.length() / Blocksize;
180
181 int rappend = Blocksize - (str.length() - (block * Blocksize));
182
183 if (rappend > 0) {
184 for (int i = 0; i < rappend; i++) {
185 sbuftemp.append(" ");
186 }
187 }
188 return sbuftemp.toString();
189 }
190 }
191
192
193
194