Search in sources :

Example 11 with SigningPrivateKey

use of net.i2p.data.SigningPrivateKey in project i2p.i2p by i2p.

the class SigUtil method fromJavaKey.

/**
 *  As of 0.9.31, if pk is a RSAPrivateCrtKey,
 *  this will return a RSASigningPrivateCrtKey.
 */
public static SigningPrivateKey fromJavaKey(RSAPrivateKey pk, SigType type) throws GeneralSecurityException {
    // private key is modulus (pubkey) + exponent
    BigInteger n = pk.getModulus();
    BigInteger d = pk.getPrivateExponent();
    byte[] b = combine(n, d, type.getPrivkeyLen());
    if (pk instanceof RSAPrivateCrtKey)
        return RSASigningPrivateCrtKey.fromJavaKey((RSAPrivateCrtKey) pk);
    return new SigningPrivateKey(type, b);
}
Also used : SigningPrivateKey(net.i2p.data.SigningPrivateKey) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey) BigInteger(java.math.BigInteger) NativeBigInteger(net.i2p.util.NativeBigInteger)

Example 12 with SigningPrivateKey

use of net.i2p.data.SigningPrivateKey in project i2p.i2p by i2p.

the class TrustedUpdate method sign.

/**
 * Uses the given private key to sign the given input file along with its
 * version string using DSA. The output will be a signed update file where
 * the first 40 bytes are the resulting DSA signature, the next 16 bytes are
 * the input file's version string encoded in UTF-8 (padded with trailing
 * <code>0h</code> characters if necessary), and the remaining bytes are the
 * raw bytes of the input file.
 *
 * @param inputFile      The file to be signed.
 * @param signedFile     The signed update file to write.
 * @param privateKeyFile The name of the file containing the private key to
 *                       sign <code>inputFile</code> with.
 * @param version        The version string of the input file. If this is
 *                       longer than 16 characters it will be truncated.
 *
 * @return An instance of {@link net.i2p.data.Signature}, or
 *         <code>null</code> if there was an error.
 */
public Signature sign(String inputFile, String signedFile, String privateKeyFile, String version) {
    FileInputStream fileInputStream = null;
    SigningPrivateKey signingPrivateKey = new SigningPrivateKey();
    try {
        fileInputStream = new FileInputStream(privateKeyFile);
        signingPrivateKey.readBytes(fileInputStream);
    } catch (IOException ioe) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("Unable to load the signing key", ioe);
        return null;
    } catch (DataFormatException dfe) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("Unable to load the signing key", dfe);
        return null;
    } finally {
        if (fileInputStream != null)
            try {
                fileInputStream.close();
            } catch (IOException ioe) {
            }
    }
    return sign(inputFile, signedFile, signingPrivateKey, version);
}
Also used : SigningPrivateKey(net.i2p.data.SigningPrivateKey) DataFormatException(net.i2p.data.DataFormatException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream)

Example 13 with SigningPrivateKey

use of net.i2p.data.SigningPrivateKey in project i2p.i2p by i2p.

the class RouterPrivateKeyFile method getRouterIdentity.

/**
 *  Read it in from the file.
 *  Also sets the local privKey and signingPrivKey.
 */
public RouterIdentity getRouterIdentity() throws IOException, DataFormatException {
    InputStream in = null;
    try {
        in = new BufferedInputStream(new FileInputStream(this.file));
        RouterIdentity ri = new RouterIdentity();
        ri.readBytes(in);
        privKey = new PrivateKey();
        privKey.readBytes(in);
        SigType type = ri.getSigningPublicKey().getType();
        if (type == null)
            throw new DataFormatException("Unknown sig type");
        signingPrivKey = new SigningPrivateKey(type);
        signingPrivKey.readBytes(in);
        // set it a Destination, so we may call validateKeyPairs()
        // or other methods
        dest = new Destination();
        dest.setPublicKey(ri.getPublicKey());
        dest.setSigningPublicKey(ri.getSigningPublicKey());
        dest.setCertificate(ri.getCertificate());
        dest.setPadding(ri.getPadding());
        return ri;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
            }
        }
    }
}
Also used : SigningPrivateKey(net.i2p.data.SigningPrivateKey) Destination(net.i2p.data.Destination) SigningPrivateKey(net.i2p.data.SigningPrivateKey) PrivateKey(net.i2p.data.PrivateKey) DataFormatException(net.i2p.data.DataFormatException) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) SigType(net.i2p.crypto.SigType)

Example 14 with SigningPrivateKey

use of net.i2p.data.SigningPrivateKey in project i2p.i2p by i2p.

the class CreateRouterInfoJob method createRouterInfo.

/**
 *  Writes 6 files: router.info (standard RI format),
 *  router.keys.dat, and 4 individual key files under keyBackup/
 *
 *  router.keys.dat file format: This is the
 *  same "eepPriv.dat" format used by the client code,
 *  as documented in PrivateKeyFile.
 *
 *  Old router.keys file format: Note that this is NOT the
 *  same "eepPriv.dat" format used by the client code.
 *<pre>
 *   - Private key (256 bytes)
 *   - Signing Private key (20 bytes)
 *   - Public key (256 bytes)
 *   - Signing Public key (128 bytes)
 *  Total 660 bytes
 *</pre>
 *
 *  Caller must hold Router.routerInfoFileLock.
 */
RouterInfo createRouterInfo() {
    SigType type = getSigTypeConfig(getContext());
    RouterInfo info = new RouterInfo();
    OutputStream fos1 = null;
    try {
        info.setAddresses(getContext().commSystem().createAddresses());
        // not necessary, in constructor
        // info.setPeers(new HashSet());
        info.setPublished(getCurrentPublishDate(getContext()));
        Object[] keypair = getContext().keyGenerator().generatePKIKeypair();
        PublicKey pubkey = (PublicKey) keypair[0];
        PrivateKey privkey = (PrivateKey) keypair[1];
        SimpleDataStructure[] signingKeypair = getContext().keyGenerator().generateSigningKeys(type);
        SigningPublicKey signingPubKey = (SigningPublicKey) signingKeypair[0];
        SigningPrivateKey signingPrivKey = (SigningPrivateKey) signingKeypair[1];
        RouterIdentity ident = new RouterIdentity();
        Certificate cert = createCertificate(getContext(), signingPubKey);
        ident.setCertificate(cert);
        ident.setPublicKey(pubkey);
        ident.setSigningPublicKey(signingPubKey);
        byte[] padding;
        int padLen = SigningPublicKey.KEYSIZE_BYTES - signingPubKey.length();
        if (padLen > 0) {
            padding = new byte[padLen];
            getContext().random().nextBytes(padding);
            ident.setPadding(padding);
        } else {
            padding = null;
        }
        info.setIdentity(ident);
        Properties stats = getContext().statPublisher().publishStatistics(ident.getHash());
        info.setOptions(stats);
        info.sign(signingPrivKey);
        if (!info.isValid())
            throw new DataFormatException("RouterInfo we just built is invalid: " + info);
        // remove router.keys
        (new File(getContext().getRouterDir(), KEYS_FILENAME)).delete();
        // write router.info
        File ifile = new File(getContext().getRouterDir(), INFO_FILENAME);
        fos1 = new BufferedOutputStream(new SecureFileOutputStream(ifile));
        info.writeBytes(fos1);
        // write router.keys.dat
        File kfile = new File(getContext().getRouterDir(), KEYS2_FILENAME);
        PrivateKeyFile pkf = new PrivateKeyFile(kfile, pubkey, signingPubKey, cert, privkey, signingPrivKey, padding);
        pkf.write();
        // set or overwrite old random keys
        Map<String, String> map = new HashMap<String, String>(2);
        byte[] rk = new byte[32];
        getContext().random().nextBytes(rk);
        map.put(Router.PROP_IB_RANDOM_KEY, Base64.encode(rk));
        getContext().random().nextBytes(rk);
        map.put(Router.PROP_OB_RANDOM_KEY, Base64.encode(rk));
        getContext().router().saveConfig(map, null);
        getContext().keyManager().setKeys(pubkey, privkey, signingPubKey, signingPrivKey);
        if (_log.shouldLog(Log.INFO))
            _log.info("Router info created and stored at " + ifile.getAbsolutePath() + " with private keys stored at " + kfile.getAbsolutePath() + " [" + info + "]");
        getContext().router().eventLog().addEvent(EventLog.REKEYED, ident.calculateHash().toBase64());
    } catch (GeneralSecurityException gse) {
        _log.log(Log.CRIT, "Error building the new router information", gse);
    } catch (DataFormatException dfe) {
        _log.log(Log.CRIT, "Error building the new router information", dfe);
    } catch (IOException ioe) {
        _log.log(Log.CRIT, "Error writing out the new router information", ioe);
    } finally {
        if (fos1 != null)
            try {
                fos1.close();
            } catch (IOException ioe) {
            }
    }
    return info;
}
Also used : PrivateKey(net.i2p.data.PrivateKey) SigningPrivateKey(net.i2p.data.SigningPrivateKey) HashMap(java.util.HashMap) RouterInfo(net.i2p.data.router.RouterInfo) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) Properties(java.util.Properties) SimpleDataStructure(net.i2p.data.SimpleDataStructure) BufferedOutputStream(java.io.BufferedOutputStream) SigningPublicKey(net.i2p.data.SigningPublicKey) SigningPublicKey(net.i2p.data.SigningPublicKey) PublicKey(net.i2p.data.PublicKey) RouterIdentity(net.i2p.data.router.RouterIdentity) GeneralSecurityException(java.security.GeneralSecurityException) PrivateKeyFile(net.i2p.data.PrivateKeyFile) IOException(java.io.IOException) SigType(net.i2p.crypto.SigType) SigningPrivateKey(net.i2p.data.SigningPrivateKey) DataFormatException(net.i2p.data.DataFormatException) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) PrivateKeyFile(net.i2p.data.PrivateKeyFile) File(java.io.File) Certificate(net.i2p.data.Certificate) KeyCertificate(net.i2p.data.KeyCertificate)

Example 15 with SigningPrivateKey

use of net.i2p.data.SigningPrivateKey in project i2p.i2p by i2p.

the class LoadRouterInfoJob method loadRouterInfo.

/**
 *  Loads router.info and either router.keys.dat or router.keys.
 *
 *  See CreateRouterInfoJob for file formats
 */
private void loadRouterInfo() {
    RouterInfo info = null;
    File rif = new File(getContext().getRouterDir(), CreateRouterInfoJob.INFO_FILENAME);
    boolean infoExists = rif.exists();
    File rkf = new File(getContext().getRouterDir(), CreateRouterInfoJob.KEYS_FILENAME);
    boolean keysExist = rkf.exists();
    File rkf2 = new File(getContext().getRouterDir(), CreateRouterInfoJob.KEYS2_FILENAME);
    boolean keys2Exist = rkf2.exists();
    InputStream fis1 = null;
    try {
        // so pretend the RI isn't there if there is no keyfile
        if (infoExists && (keys2Exist || keysExist)) {
            fis1 = new BufferedInputStream(new FileInputStream(rif));
            info = new RouterInfo();
            info.readBytes(fis1);
            // Catch this here before it all gets worse
            if (!info.isValid())
                throw new DataFormatException("Our RouterInfo has a bad signature");
            if (_log.shouldLog(Log.DEBUG))
                _log.debug("Reading in routerInfo from " + rif.getAbsolutePath() + " and it has " + info.getAddresses().size() + " addresses");
            // don't reuse if family name changed
            if (DataHelper.eq(info.getOption(FamilyKeyCrypto.OPT_NAME), getContext().getProperty(FamilyKeyCrypto.PROP_FAMILY_NAME))) {
                _us = info;
            } else {
                _log.logAlways(Log.WARN, "NetDb family name changed");
            }
        }
        if (keys2Exist || keysExist) {
            KeyData kd = readKeyData(rkf, rkf2);
            PublicKey pubkey = kd.routerIdentity.getPublicKey();
            SigningPublicKey signingPubKey = kd.routerIdentity.getSigningPublicKey();
            PrivateKey privkey = kd.privateKey;
            SigningPrivateKey signingPrivKey = kd.signingPrivateKey;
            SigType stype = signingPubKey.getType();
            // check if the sigtype config changed
            SigType cstype = CreateRouterInfoJob.getSigTypeConfig(getContext());
            boolean sigTypeChanged = stype != cstype;
            if (sigTypeChanged && getContext().getProperty(CreateRouterInfoJob.PROP_ROUTER_SIGTYPE) == null) {
                // TODO reduce to ~3 (i.e. increase probability) in future release
                if (getContext().random().nextInt(4) > 0) {
                    sigTypeChanged = false;
                    if (_log.shouldWarn())
                        _log.warn("Deferring RI rekey from " + stype + " to " + cstype);
                }
            }
            if (sigTypeChanged || shouldRebuild(privkey)) {
                if (_us != null) {
                    Hash h = _us.getIdentity().getHash();
                    _log.logAlways(Log.WARN, "Deleting old router identity " + h.toBase64());
                    // the netdb hasn't started yet, but we want to delete the RI
                    File f = PersistentDataStore.getRouterInfoFile(getContext(), h);
                    f.delete();
                    // the banlist can be called at any time
                    getContext().banlist().banlistRouterForever(h, "Our previous identity");
                    _us = null;
                }
                if (sigTypeChanged)
                    _log.logAlways(Log.WARN, "Rebuilding RouterInfo with new signature type " + cstype);
                // windows... close before deleting
                if (fis1 != null) {
                    try {
                        fis1.close();
                    } catch (IOException ioe) {
                    }
                    fis1 = null;
                }
                rif.delete();
                rkf.delete();
                rkf2.delete();
                return;
            }
            getContext().keyManager().setKeys(pubkey, privkey, signingPubKey, signingPrivKey);
        }
    } catch (IOException ioe) {
        _log.log(Log.CRIT, "Error reading the router info from " + rif.getAbsolutePath() + " and the keys from " + rkf.getAbsolutePath(), ioe);
        _us = null;
        // windows... close before deleting
        if (fis1 != null) {
            try {
                fis1.close();
            } catch (IOException ioe2) {
            }
            fis1 = null;
        }
        rif.delete();
        rkf.delete();
        rkf2.delete();
    } catch (DataFormatException dfe) {
        _log.log(Log.CRIT, "Corrupt router info or keys at " + rif.getAbsolutePath() + " / " + rkf.getAbsolutePath(), dfe);
        _us = null;
        // windows... close before deleting
        if (fis1 != null) {
            try {
                fis1.close();
            } catch (IOException ioe) {
            }
            fis1 = null;
        }
        rif.delete();
        rkf.delete();
        rkf2.delete();
    } finally {
        if (fis1 != null)
            try {
                fis1.close();
            } catch (IOException ioe) {
            }
    }
}
Also used : SigningPublicKey(net.i2p.data.SigningPublicKey) PrivateKey(net.i2p.data.PrivateKey) SigningPrivateKey(net.i2p.data.SigningPrivateKey) RouterInfo(net.i2p.data.router.RouterInfo) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SigningPublicKey(net.i2p.data.SigningPublicKey) PublicKey(net.i2p.data.PublicKey) IOException(java.io.IOException) Hash(net.i2p.data.Hash) FileInputStream(java.io.FileInputStream) SigType(net.i2p.crypto.SigType) SigningPrivateKey(net.i2p.data.SigningPrivateKey) DataFormatException(net.i2p.data.DataFormatException) BufferedInputStream(java.io.BufferedInputStream) File(java.io.File) RouterPrivateKeyFile(net.i2p.data.router.RouterPrivateKeyFile)

Aggregations

SigningPrivateKey (net.i2p.data.SigningPrivateKey)31 SigningPublicKey (net.i2p.data.SigningPublicKey)14 DataFormatException (net.i2p.data.DataFormatException)11 IOException (java.io.IOException)10 PrivateKey (net.i2p.data.PrivateKey)10 GeneralSecurityException (java.security.GeneralSecurityException)8 PublicKey (net.i2p.data.PublicKey)7 File (java.io.File)6 PrivateKey (java.security.PrivateKey)6 SigType (net.i2p.crypto.SigType)6 SimpleDataStructure (net.i2p.data.SimpleDataStructure)6 FileInputStream (java.io.FileInputStream)5 Properties (java.util.Properties)5 Destination (net.i2p.data.Destination)5 Signature (net.i2p.data.Signature)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 BigInteger (java.math.BigInteger)4 RouterInfo (net.i2p.data.router.RouterInfo)4 BufferedInputStream (java.io.BufferedInputStream)3 InputStream (java.io.InputStream)3