1 19 20 package com.sslexplorer.security.pki.rsa; 21 22 23 24 import java.io.IOException ; 25 import java.math.BigInteger ; 26 import java.security.KeyFactory ; 27 import java.security.PrivateKey ; 28 import java.security.Signature ; 29 import java.security.interfaces.RSAPrivateKey ; 30 import java.security.interfaces.RSAPublicKey ; 31 import java.security.spec.RSAPrivateKeySpec ; 32 import java.security.spec.RSAPublicKeySpec ; 33 34 import com.maverick.util.ByteArrayReader; 35 import com.maverick.util.ByteArrayWriter; 36 import com.sslexplorer.security.pki.InvalidKeyException; 37 import com.sslexplorer.security.pki.SshPrivateKey; 38 import com.sslexplorer.security.pki.SshPublicKey; 39 40 41 46 public class SshRsaPrivateKey extends SshPrivateKey { 47 RSAPrivateKey prvKey; 48 RSAPublicKey pubKey; 49 50 56 public SshRsaPrivateKey(RSAPrivateKey prv, RSAPublicKey pub) { 57 prvKey = prv; 58 pubKey = pub; 59 } 60 61 62 public PrivateKey getPrivateKey() { 63 return prvKey; 64 } 65 66 73 public SshRsaPrivateKey(byte[] encoded) throws InvalidKeyException { 74 try { 75 ByteArrayReader bar = new ByteArrayReader(encoded); 77 78 String header = bar.readString(); 80 81 if (!header.equals(getAlgorithmName())) { 82 throw new InvalidKeyException(); 83 } 84 85 BigInteger e = bar.readBigInteger(); 86 BigInteger n = bar.readBigInteger(); 87 88 BigInteger p = bar.readBigInteger(); 90 RSAPrivateKeySpec prvSpec = new RSAPrivateKeySpec (n, p); 91 RSAPublicKeySpec pubSpec = new RSAPublicKeySpec (n, e); 92 KeyFactory kf = KeyFactory.getInstance("RSA"); 93 prvKey = (RSAPrivateKey ) kf.generatePrivate(prvSpec); 94 pubKey = (RSAPublicKey ) kf.generatePublic(pubSpec); 95 } catch (Exception e) { 96 throw new InvalidKeyException(); 97 } 98 } 99 100 107 public boolean equals(Object obj) { 108 if (obj instanceof SshRsaPrivateKey) { 109 return prvKey.equals(((SshRsaPrivateKey) obj).prvKey); 110 } 111 112 return false; 113 } 114 115 120 public int hashCode() { 121 return prvKey.hashCode(); 122 } 123 124 129 public String getAlgorithmName() { 130 return "ssh-rsa"; 131 } 132 133 138 public int getBitLength() { 139 return prvKey.getModulus().bitLength(); 140 } 141 142 147 public byte[] getEncoded() { 148 try { 149 ByteArrayWriter baw = new ByteArrayWriter(); 150 151 baw.write(getPublicKey().getEncoded()); 153 154 baw.writeBigInteger(prvKey.getPrivateExponent()); 156 157 return baw.toByteArray(); 158 } catch (IOException ioe) { 159 return null; 160 } 161 } 162 163 168 public SshPublicKey getPublicKey() { 169 return new SshRsaPublicKey(pubKey); 170 } 171 172 179 public byte[] generateSignature(byte[] data) { 180 try { 181 Signature sig = Signature.getInstance("SHA1withRSA"); 182 sig.initSign(prvKey); 183 sig.update(data); 184 185 ByteArrayWriter baw = new ByteArrayWriter(); 186 baw.writeString(getAlgorithmName()); 187 baw.writeBinaryString(sig.sign()); 188 189 return baw.toByteArray(); 190 } catch (Exception e) { 191 return null; 192 } 193 } 194 } 195 | Popular Tags |