1 19 20 package com.maverick.crypto.publickey; 21 22 import java.io.IOException ; 23 24 import com.maverick.crypto.digests.SHA1Digest; 25 import java.math.BigInteger ; 26 import com.maverick.crypto.security.SecureRandom; 27 28 public class RsaPrivateKey 29 extends RsaKey { 30 31 protected BigInteger privateExponent; 32 33 protected final static byte[] ASN_SHA1 = { 34 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 35 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 36 }; 37 38 public RsaPrivateKey(BigInteger modulus, BigInteger privateExponent) { 39 super(modulus); 40 this.privateExponent = privateExponent; 41 } 42 43 46 public BigInteger getPrivateExponent() { 47 return privateExponent; 48 } 49 50 53 public byte[] sign(byte[] msg) throws IOException { 54 55 56 SHA1Digest hash = new SHA1Digest(); 57 hash.update(msg, 0, msg.length); 58 59 byte[] data = new byte[hash.getDigestSize()]; 60 hash.doFinal(data, 0); 61 62 byte[] tmp = new byte[data.length + ASN_SHA1.length]; 63 System.arraycopy(ASN_SHA1, 0, tmp, 0, ASN_SHA1.length); 64 System.arraycopy(data, 0, tmp, ASN_SHA1.length, data.length); 65 data = tmp; 66 67 BigInteger dataInt = new BigInteger (1, data); 68 int mLen = (getModulus().bitLength() + 7) / 8; 69 70 dataInt = Rsa.padPKCS1(dataInt, 1, mLen); 71 72 BigInteger signatureInt = null; 73 74 BigInteger privateExponent = getPrivateExponent(); 75 BigInteger modulus = getModulus(); 76 signatureInt = Rsa.doPrivate(dataInt, 77 modulus, privateExponent); 78 79 byte[] sig = unsignedBigIntToBytes(signatureInt, mLen); 80 81 return sig; 82 83 } 84 85 protected static byte[] unsignedBigIntToBytes(BigInteger bi, int size) { 86 byte[] tmp = bi.toByteArray(); 87 byte[] tmp2 = null; 88 if (tmp.length > size) { 89 tmp2 = new byte[size]; 90 System.arraycopy(tmp, tmp.length - size, tmp2, 0, size); 91 } 92 else if (tmp.length < size) { 93 tmp2 = new byte[size]; 94 System.arraycopy(tmp, 0, tmp2, size - tmp.length, tmp.length); 95 } 96 else { 97 tmp2 = tmp; 98 } 99 return tmp2; 100 } 101 102 public boolean equals(Object obj) { 103 if (obj instanceof RsaPrivateKey) { 104 RsaPrivateKey key = (RsaPrivateKey) obj; 105 return key.getBitLength() == getBitLength() 106 && key.getModulus().compareTo(getModulus()) == 0 107 && key.getPrivateExponent().compareTo(getPrivateExponent()) == 0; 108 } 109 return false; 110 } 111 } 112 | Popular Tags |