00001
package com.quadcap.crypto;
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
import java.util.Random;
00042
import java.math.BigInteger;
00043
import java.nio.ByteBuffer;
00044
00045
import com.quadcap.util.Debug;
00046
import com.quadcap.util.Util;
00047
00048
00049
00050
00051
00052
00053
00054 public abstract class RSAKey implements Key {
00055 static final BigInteger
e =
new BigInteger(
"3");
00056 protected BigInteger
n;
00057 String
text;
00058 Random
random;
00059 int size;
00060 byte[]
buf;
00061
00062 protected void init(String text,
int size, BigInteger n) {
00063
this.text = text;
00064
this.size = size;
00065
this.n = n;
00066
this.buf =
new byte[
blockSize()];
00067 }
00068
00069
00070
00071
00072
00073 public void engine(ByteBuffer in, ByteBuffer out) {
00074
int byteCnt =
blockSize();
00075
Debug.println(
"BLOCK SIZE: " + byteCnt +
" bytes");
00076
Debug.println(
"in: [" + in.position() +
"/" + in.limit() +
"-" +
00077 in.capacity() +
"]");
00078
Debug.println(
"out: [" + out.position() +
"/" + out.limit() +
"-" +
00079 out.capacity() +
"]");
00080
while (in.remaining() > 0) {
00081
int len = Math.min(byteCnt, in.remaining());
00082 in.get(
buf, 0, len);
00083 BigInteger pi =
new BigInteger(1,
buf);
00084 BigInteger xi = engine(pi);
00085 byte[] t = xi.toByteArray();
00086
if (t.length > byteCnt) {
00087
if (t.length > byteCnt + 1) {
00088
throw new RuntimeException(
"---- t.length = " + t.length);
00089 }
else {
00090 out.put(t, 0, byteCnt);
00091 }
00092 }
else {
00093
if (t.length < byteCnt) {
00094
int lim = byteCnt - t.length;
00095
while (lim-- > 0) out.put((byte)0);
00096 }
00097 out.put(t);
00098 }
00099
for (
int i = 0; i <
buf.length; i++)
buf[i] = 0;
00100 }
00101 }
00102
00103
00104
00105
00106
public abstract void f(ByteBuffer src, ByteBuffer dst);
00107
00108
00109
00110
00111
protected abstract BigInteger engine(BigInteger x);
00112
00113 final Random
getRandom() {
00114
if (
random == null) {
00115
random =
new Random();
00116 }
00117
return random;
00118 }
00119
00120 final void randomBytes(byte[] buf,
int pos,
int cnt) {
00121 byte[] tbuf =
new byte[cnt];
00122
getRandom().nextBytes(tbuf);
00123 System.arraycopy(tbuf, 0, buf, pos, cnt);
00124 }
00125
00126 public int blockSize() {
00127
return size >> 3;
00128 }
00129
00130 }