Search in sources :

Example 16 with SigningPublicKey

use of net.i2p.data.SigningPublicKey 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)

Example 17 with SigningPublicKey

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

the class FamilyKeyCrypto method verify.

/**
 *  Verify the family in a RouterInfo, name already retrieved
 *  @since 0.9.28
 */
private boolean verify(RouterInfo ri, String name) {
    Hash h = ri.getHash();
    String ssig = ri.getOption(OPT_SIG);
    if (ssig == null) {
        if (_log.shouldInfo())
            _log.info("No sig for " + h + ' ' + name);
        return false;
    }
    String nameAndSig = _verified.get(h);
    String riNameAndSig = name + ssig;
    if (nameAndSig != null) {
        if (nameAndSig.equals(riNameAndSig))
            return true;
        // name or sig changed
        _verified.remove(h);
    }
    SigningPublicKey spk;
    if (name.equals(_fname)) {
        // us
        spk = _pubkey;
    } else {
        if (_negativeCache.contains(h))
            return false;
        spk = loadCert(name);
        if (spk == null) {
            // look for a b64 key in the RI
            String skey = ri.getOption(OPT_KEY);
            if (skey != null) {
                int colon = skey.indexOf(':');
                // switched from ';' to ':' during dev, remove this later
                if (colon < 0)
                    colon = skey.indexOf(';');
                if (colon > 0) {
                    try {
                        int code = Integer.parseInt(skey.substring(0, colon));
                        SigType type = SigType.getByCode(code);
                        if (type != null) {
                            byte[] bkey = Base64.decode(skey.substring(colon + 1));
                            if (bkey != null) {
                                spk = new SigningPublicKey(type, bkey);
                            }
                        }
                    } catch (NumberFormatException e) {
                        if (_log.shouldInfo())
                            _log.info("Bad b64 family key: " + ri, e);
                    } catch (IllegalArgumentException e) {
                        if (_log.shouldInfo())
                            _log.info("Bad b64 family key: " + ri, e);
                    } catch (ArrayIndexOutOfBoundsException e) {
                        if (_log.shouldInfo())
                            _log.info("Bad b64 family key: " + ri, e);
                    }
                }
            }
            if (spk == null) {
                _negativeCache.add(h);
                if (_log.shouldInfo())
                    _log.info("No cert or valid key for " + h + ' ' + name);
                return false;
            }
        }
    }
    if (!spk.getType().isAvailable()) {
        _negativeCache.add(h);
        if (_log.shouldInfo())
            _log.info("Unsupported crypto for sig for " + h);
        return false;
    }
    byte[] bsig = Base64.decode(ssig);
    if (bsig == null) {
        _negativeCache.add(h);
        if (_log.shouldInfo())
            _log.info("Bad sig for " + h + ' ' + name + ' ' + ssig);
        return false;
    }
    Signature sig;
    try {
        sig = new Signature(spk.getType(), bsig);
    } catch (IllegalArgumentException iae) {
        // wrong size (type mismatch)
        _negativeCache.add(h);
        if (_log.shouldInfo())
            _log.info("Bad sig for " + ri, iae);
        return false;
    }
    byte[] nb = DataHelper.getUTF8(name);
    byte[] b = new byte[nb.length + Hash.HASH_LENGTH];
    System.arraycopy(nb, 0, b, 0, nb.length);
    System.arraycopy(ri.getHash().getData(), 0, b, nb.length, Hash.HASH_LENGTH);
    boolean rv = _context.dsa().verifySignature(sig, b, spk);
    if (rv)
        _verified.put(h, riNameAndSig);
    else
        _negativeCache.add(h);
    if (_log.shouldInfo())
        _log.info("Verified? " + rv + " for " + h + ' ' + name + ' ' + ssig);
    return rv;
}
Also used : SigningPublicKey(net.i2p.data.SigningPublicKey) Signature(net.i2p.data.Signature) Hash(net.i2p.data.Hash) SigType(net.i2p.crypto.SigType)

Example 18 with SigningPublicKey

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

the class SigUtil method fromJavaKey.

public static SigningPublicKey fromJavaKey(DSAPublicKey pk) throws GeneralSecurityException {
    BigInteger y = pk.getY();
    SigType type = SigType.DSA_SHA1;
    int len = type.getPubkeyLen();
    byte[] by = rectify(y, len);
    return new SigningPublicKey(type, by);
}
Also used : SigningPublicKey(net.i2p.data.SigningPublicKey) BigInteger(java.math.BigInteger) NativeBigInteger(net.i2p.util.NativeBigInteger) ECPoint(java.security.spec.ECPoint)

Example 19 with SigningPublicKey

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

the class SigUtil method fromJavaKey.

public static SigningPublicKey fromJavaKey(ECPublicKey pk, SigType type) throws GeneralSecurityException {
    ECPoint w = pk.getW();
    BigInteger x = w.getAffineX();
    BigInteger y = w.getAffineY();
    int len = type.getPubkeyLen();
    byte[] b = combine(x, y, len);
    return new SigningPublicKey(type, b);
}
Also used : SigningPublicKey(net.i2p.data.SigningPublicKey) BigInteger(java.math.BigInteger) NativeBigInteger(net.i2p.util.NativeBigInteger) ECPoint(java.security.spec.ECPoint) ECPoint(java.security.spec.ECPoint)

Example 20 with SigningPublicKey

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

the class TrustedUpdate method genKeysCLI.

/**
 * @return success
 */
private static final boolean genKeysCLI(String publicKeyFile, String privateKeyFile) {
    File pubFile = new File(publicKeyFile);
    File privFile = new File(privateKeyFile);
    if (pubFile.exists()) {
        System.out.println("Error: Not overwriting file " + publicKeyFile);
        return false;
    }
    if (privFile.exists()) {
        System.out.println("Error: Not overwriting file " + privateKeyFile);
        return false;
    }
    FileOutputStream fileOutputStream = null;
    I2PAppContext context = I2PAppContext.getGlobalContext();
    try {
        Object[] signingKeypair = context.keyGenerator().generateSigningKeypair();
        SigningPublicKey signingPublicKey = (SigningPublicKey) signingKeypair[0];
        SigningPrivateKey signingPrivateKey = (SigningPrivateKey) signingKeypair[1];
        fileOutputStream = new SecureFileOutputStream(pubFile);
        signingPublicKey.writeBytes(fileOutputStream);
        fileOutputStream.close();
        fileOutputStream = null;
        fileOutputStream = new SecureFileOutputStream(privFile);
        signingPrivateKey.writeBytes(fileOutputStream);
        System.out.println("\r\nPrivate key written to: " + privateKeyFile);
        System.out.println("Public key written to: " + publicKeyFile);
        System.out.println("\r\nPublic key: " + signingPublicKey.toBase64() + "\r\n");
    } catch (IOException e) {
        System.err.println("Error writing keys:");
        e.printStackTrace();
        return false;
    } catch (DataFormatException e) {
        System.err.println("Error writing keys:");
        e.printStackTrace();
        return false;
    } finally {
        if (fileOutputStream != null)
            try {
                fileOutputStream.close();
            } catch (IOException ioe) {
            }
    }
    return true;
}
Also used : SigningPrivateKey(net.i2p.data.SigningPrivateKey) SigningPublicKey(net.i2p.data.SigningPublicKey) DataFormatException(net.i2p.data.DataFormatException) I2PAppContext(net.i2p.I2PAppContext) FileOutputStream(java.io.FileOutputStream) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) IOException(java.io.IOException) File(java.io.File)

Aggregations

SigningPublicKey (net.i2p.data.SigningPublicKey)36 SigningPrivateKey (net.i2p.data.SigningPrivateKey)13 IOException (java.io.IOException)12 DataFormatException (net.i2p.data.DataFormatException)11 SigType (net.i2p.crypto.SigType)10 Signature (net.i2p.data.Signature)10 PublicKey (net.i2p.data.PublicKey)9 File (java.io.File)8 GeneralSecurityException (java.security.GeneralSecurityException)8 PublicKey (java.security.PublicKey)7 PrivateKey (net.i2p.data.PrivateKey)6 SimpleDataStructure (net.i2p.data.SimpleDataStructure)6 BigInteger (java.math.BigInteger)5 ECPoint (java.security.spec.ECPoint)5 Certificate (net.i2p.data.Certificate)5 Destination (net.i2p.data.Destination)5 NativeBigInteger (net.i2p.util.NativeBigInteger)5 FileInputStream (java.io.FileInputStream)3 StringWriter (java.io.StringWriter)3 CertificateTest (net.i2p.data.CertificateTest)3