/* * [PublicKey.java] * * Summary: Represents a public RSA key. * * Copyright: (c) 2004-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 1.4 2006-03-05 reformat with IntelliJ and add Javadoc. */ package com.mindprod.transporter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; /** * Represents a public RSA key. * * @author Roedy Green, Canadian Mind Products * @version 1.4 2006-03-05 reformat with IntelliJ and add Javadoc. * @since 2004-06-08 */ public class PublicKey { /** * product of two large primes. */ public BigInteger n; /** * size in bits of key, 512 .. 4096 */ public int keySize; /** * constructor * * @param publicKeyStream where to find serialised public key information. * * @throws IOException */ public PublicKey( InputStream publicKeyStream ) throws IOException { loadKey( publicKeyStream ); } /** * Constructor. Do not use */ protected PublicKey() { } /** * Save the PublicKey as a serialised object. * * @param os OutputStream to contain the key * * @throws IOException */ void savePublicKey( OutputStream os ) throws IOException { // We avoid serialisation here even though the rest of the package // depends on it to make it easier for somone to cannibalise // a serialisation-free version. // O P E N DataOutputStream dos = new DataOutputStream( os ); // W R I T E dos.writeInt( keySize ); byte[] exportn = n.toByteArray(); dos.writeInt( exportn.length ); dos.write( exportn, 0, exportn.length ); // C L O S E dos.close(); } /** * read a public key off disk * * @param publicKeyStream stream containing key (public/private?) * * @throws IOException if cannot load the publickey */ public void loadKey( InputStream publicKeyStream ) throws IOException { try { DataInputStream dis = new DataInputStream( publicKeyStream ); // R E A D keySize = dis.readInt(); // public key preceded by length int nsize = dis.readInt(); byte[] importn = new byte[ nsize ]; final int actualSize = dis.read( importn ); if ( actualSize != nsize ) { throw new IOException( "Public key corrupt" ); } n = new BigInteger( importn ); // C L O S E dis.close(); } catch ( IOException e ) { throw new IOException( "Corrupt private key " + e.getMessage() ); } } }