1 package com.quadcap.crypto; 2 3 40 41 import java.util.Random ; 42 import java.math.BigInteger ; 43 import java.nio.ByteBuffer ; 44 45 import com.quadcap.util.Debug; 46 import com.quadcap.util.Util; 47 48 54 public abstract class RSAKey implements Key { 55 static final BigInteger e = new BigInteger ("3"); 56 protected BigInteger n; 57 String text; 58 Random random; 59 int size; 60 byte[] buf; 61 62 protected void init(String text, int size, BigInteger n) { 63 this.text = text; 64 this.size = size; 65 this.n = n; 66 this.buf = new byte[blockSize()]; 67 } 68 69 73 public void engine(ByteBuffer in, ByteBuffer out) { 74 int byteCnt = blockSize(); 75 Debug.println("BLOCK SIZE: " + byteCnt + " bytes"); 76 Debug.println("in: [" + in.position() + "/" + in.limit() + "-" + 77 in.capacity() + "]"); 78 Debug.println("out: [" + out.position() + "/" + out.limit() + "-" + 79 out.capacity() + "]"); 80 while (in.remaining() > 0) { 81 int len = Math.min(byteCnt, in.remaining()); 82 in.get(buf, 0, len); 83 BigInteger pi = new BigInteger (1, buf); 84 BigInteger xi = engine(pi); 85 byte[] t = xi.toByteArray(); 86 if (t.length > byteCnt) { 87 if (t.length > byteCnt + 1) { 88 throw new RuntimeException ("---- t.length = " + t.length); 89 } else { 90 out.put(t, 0, byteCnt); 91 } 92 } else { 93 if (t.length < byteCnt) { 94 int lim = byteCnt - t.length; 95 while (lim-- > 0) out.put((byte)0); 96 } 97 out.put(t); 98 } 99 for (int i = 0; i < buf.length; i++) buf[i] = 0; 100 } 101 } 102 103 106 public abstract void f(ByteBuffer src, ByteBuffer dst); 107 108 111 protected abstract BigInteger engine(BigInteger x); 112 113 final Random getRandom() { 114 if (random == null) { 115 random = new Random (); 116 } 117 return random; 118 } 119 120 final void randomBytes(byte[] buf, int pos, int cnt) { 121 byte[] tbuf = new byte[cnt]; 122 getRandom().nextBytes(tbuf); 123 System.arraycopy(tbuf, 0, buf, pos, cnt); 124 } 125 126 public int blockSize() { 127 return size >> 3; 128 } 129 130 } 131 | Popular Tags |