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.text.Text; 46 47 52 public class RSAPrivateKey extends RSAKey implements PrivateKey { 53 private final BigInteger ZERO = BigInteger.ZERO; 54 private final BigInteger ONE = BigInteger.ONE; 55 private final BigInteger TWO = new BigInteger ("2"); 56 private final BigInteger THREE = new BigInteger ("3"); 57 58 private BigInteger p; private BigInteger q; 61 private BigInteger d; private BigInteger dP; private BigInteger dQ; private BigInteger qInv; 66 69 public RSAPrivateKey() {} 70 71 74 public void init(String s) { 75 String [] v = Text.extractN(s, "*:*:*:*:*:*:*:*"); 76 this.p = new BigInteger (v[2]); 77 this.q = new BigInteger (v[3]); 78 super.init(v[4], Integer.parseInt(v[1]), p.multiply(q)); 79 init(); 80 } 81 82 85 public String toString() { 86 return "RSAPriv:" + size + ":" + p + ":" + q + ":" + 87 dP + ":" + dQ + ":" + qInv + ":" + text; 88 } 89 90 93 public void init(String text, int siz, Random random) { 94 int s2 = (siz / 2); 95 int offset = (int)(random.nextDouble() * 10) - 5; 96 offset += (offset < 0) ? -5.0 : 5.0; 97 98 do { 99 this.p = makePrime(s2 + offset, random); 100 this.q = makePrime(s2 - offset, random); 101 this.n = p.multiply(q); 102 } while (n.bitLength() != siz); 103 104 super.init(text, siz, n); 105 init(); 106 } 107 108 111 public void f(ByteBuffer cipher, ByteBuffer plain) { 112 engine(cipher, plain); 113 } 114 115 118 public PublicKey getPublicKey() { 119 RSAPublicKey pub = new RSAPublicKey(); 120 pub.init(text, size, n); 121 return pub; 122 } 123 124 private final void init() { 125 BigInteger p1 = p.subtract(BigInteger.ONE); 126 BigInteger q1 = q.subtract(BigInteger.ONE); 127 BigInteger m = p1.multiply(q1); 129 this.d = e.modInverse(m); 130 131 dP = d.remainder(p1); 132 dQ = d.remainder(q1); 133 qInv = p.modInverse(q); 134 } 135 136 final private BigInteger makePrime(int size, Random random) { 137 BigInteger bn = new BigInteger (size, 100, random); 138 while (bn.subtract(ONE).remainder(THREE).equals(ZERO)) { 139 bn = new BigInteger (size, 100, random); 140 } 141 return bn; 142 } 143 144 final protected BigInteger engine(BigInteger c) { 145 if (false) { 146 return c.modPow(d, n); 147 } else { 148 BigInteger m1 = c.modPow(dP, p); 149 BigInteger m2 = c.modPow(dQ, q); 150 BigInteger h = ((m2.subtract(m1)).multiply(qInv)).remainder(q); 151 if (h.compareTo(BigInteger.ZERO) < 0) { 152 h = h.add(q); 153 } 154 return m1.add(h.multiply(p)); 155 } 156 } 157 158 } 159 | Popular Tags |