Search in sources :

Example 1 with PrivateKeyFile

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

the class EditBean method getSigningPrivateKey.

/**
 **
 *    public String getNameSignature(int tunnel) {
 *        String spoof = getSpoofedHost(tunnel);
 *        if (spoof.length() <= 0)
 *            return "";
 *        TunnelController tun = getController(tunnel);
 *        if (tun == null)
 *            return "";
 *        String keyFile = tun.getPrivKeyFile();
 *        if (keyFile != null && keyFile.trim().length() > 0) {
 *            File f = new File(keyFile);
 *            if (!f.isAbsolute())
 *                f = new File(_context.getConfigDir(), keyFile);
 *            PrivateKeyFile pkf = new PrivateKeyFile(f);
 *            try {
 *                Destination d = pkf.getDestination();
 *                if (d == null)
 *                    return "";
 *                SigningPrivateKey privKey = pkf.getSigningPrivKey();
 *                if (privKey == null)
 *                    return "";
 *                Signature sig = _context.dsa().sign(spoof.getBytes("UTF-8"), privKey);
 *                if (sig == null)
 *                    return "";
 *                return Base64.encode(sig.getData());
 *            } catch (I2PException e) {
 *            } catch (IOException e) {}
 *        }
 *        return "";
 *    }
 ***
 */
/**
 *  @since 0.9.26
 *  @return key or null
 */
public SigningPrivateKey getSigningPrivateKey(int tunnel) {
    TunnelController tun = getController(tunnel);
    if (tun == null)
        return null;
    String keyFile = tun.getPrivKeyFile();
    if (keyFile != null && keyFile.trim().length() > 0) {
        File f = new File(keyFile);
        if (!f.isAbsolute())
            f = new File(_context.getConfigDir(), keyFile);
        PrivateKeyFile pkf = new PrivateKeyFile(f);
        return pkf.getSigningPrivKey();
    }
    return null;
}
Also used : TunnelController(net.i2p.i2ptunnel.TunnelController) PrivateKeyFile(net.i2p.data.PrivateKeyFile) PrivateKeyFile(net.i2p.data.PrivateKeyFile) File(java.io.File)

Example 2 with PrivateKeyFile

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

the class IndexBean method modifyDestination.

/**
 * Modify or create a destination
 */
private String modifyDestination() {
    String privKeyFile = _config.getPrivKeyFile();
    if (privKeyFile == null)
        return "Private Key File not specified";
    TunnelController tun = getController(_tunnel);
    Properties config = getConfig();
    if (tun == null) {
        // creating new
        tun = new TunnelController(config, "", true);
        _group.addController(tun);
        saveChanges();
    } else if (tun.getIsRunning() || tun.getIsStarting()) {
        return "Tunnel must be stopped before modifying destination";
    }
    File keyFile = new File(privKeyFile);
    if (!keyFile.isAbsolute())
        keyFile = new File(_context.getConfigDir(), privKeyFile);
    PrivateKeyFile pkf = new PrivateKeyFile(keyFile);
    try {
        pkf.createIfAbsent();
    } catch (I2PException e) {
        return "Create private key file failed: " + e;
    } catch (IOException e) {
        return "Create private key file failed: " + e;
    }
    switch(_certType) {
        case Certificate.CERTIFICATE_TYPE_NULL:
        case Certificate.CERTIFICATE_TYPE_HIDDEN:
            pkf.setCertType(_certType);
            break;
        case Certificate.CERTIFICATE_TYPE_HASHCASH:
            pkf.setHashCashCert(_hashCashValue);
            break;
        case Certificate.CERTIFICATE_TYPE_SIGNED:
            if (_certSigner == null || _certSigner.trim().length() <= 0)
                return "No signing destination specified";
            // find the signer's key file...
            String signerPKF = null;
            for (int i = 0; i < getTunnelCount(); i++) {
                TunnelController c = getController(i);
                if (_certSigner.equals(c.getConfig("").getProperty(TunnelController.PROP_NAME)) || _certSigner.equals(c.getConfig("").getProperty(TunnelController.PROP_SPOOFED_HOST))) {
                    signerPKF = c.getConfig("").getProperty(TunnelController.PROP_FILE);
                    break;
                }
            }
            if (signerPKF == null || signerPKF.length() <= 0)
                return "Signing destination " + _certSigner + " not found";
            if (privKeyFile.equals(signerPKF))
                return "Self-signed destinations not allowed";
            Certificate c = pkf.setSignedCert(new PrivateKeyFile(signerPKF));
            if (c == null)
                return "Signing failed - does signer destination exist?";
            break;
        default:
            return "Unknown certificate type";
    }
    Destination newdest;
    try {
        pkf.write();
        newdest = pkf.getDestination();
    } catch (I2PException e) {
        return "Modification failed: " + e;
    } catch (IOException e) {
        return "Modification failed: " + e;
    }
    return "Destination modified - " + "New Base32 is " + newdest.toBase32() + "New Destination is " + newdest.toBase64();
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) TunnelController(net.i2p.i2ptunnel.TunnelController) PrivateKeyFile(net.i2p.data.PrivateKeyFile) IOException(java.io.IOException) Properties(java.util.Properties) PrivateKeyFile(net.i2p.data.PrivateKeyFile) File(java.io.File) Certificate(net.i2p.data.Certificate)

Example 3 with PrivateKeyFile

use of net.i2p.data.PrivateKeyFile 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 4 with PrivateKeyFile

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

the class GeneralHelper method getDestination.

/**
 *  Works even if tunnel is not running.
 *  @return Destination or null
 */
public Destination getDestination(int tunnel) {
    TunnelController tun = getController(tunnel);
    if (tun != null) {
        Destination rv = tun.getDestination();
        if (rv != null)
            return rv;
        // if not running, do this the hard way
        File keyFile = tun.getPrivateKeyFile();
        if (keyFile != null) {
            PrivateKeyFile pkf = new PrivateKeyFile(keyFile);
            try {
                rv = pkf.getDestination();
                if (rv != null)
                    return rv;
            } catch (I2PException e) {
            } catch (IOException e) {
            }
        }
    }
    return null;
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) TunnelController(net.i2p.i2ptunnel.TunnelController) PrivateKeyFile(net.i2p.data.PrivateKeyFile) IOException(java.io.IOException) SecureFile(net.i2p.util.SecureFile) PrivateKeyFile(net.i2p.data.PrivateKeyFile) File(java.io.File)

Example 5 with PrivateKeyFile

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

the class TunnelController method createAltPrivateKey.

/**
 * Creates alternate Destination with the same encryption keys as the primary Destination,
 * but a different signing key.
 *
 * Must have already called createPrivateKey() successfully.
 * Does nothing unless option OPT_ALT_PKF is set with the privkey file name.
 * Does nothing if the file already exists.
 *
 * @return success
 * @since 0.9.30
 */
private boolean createAltPrivateKey() {
    if (PREFERRED_SIGTYPE == SigType.DSA_SHA1)
        return false;
    File keyFile = getPrivateKeyFile();
    if (keyFile == null)
        return false;
    if (!keyFile.exists())
        return false;
    File altFile = getAlternatePrivateKeyFile();
    if (altFile == null)
        return false;
    if (altFile.equals(keyFile))
        return false;
    if (altFile.exists())
        return true;
    PrivateKeyFile pkf = new PrivateKeyFile(keyFile);
    FileOutputStream out = null;
    try {
        Destination dest = pkf.getDestination();
        if (dest == null)
            return false;
        if (dest.getSigType() != SigType.DSA_SHA1)
            return false;
        PublicKey pub = dest.getPublicKey();
        PrivateKey priv = pkf.getPrivKey();
        SimpleDataStructure[] signingKeys = KeyGenerator.getInstance().generateSigningKeys(PREFERRED_SIGTYPE);
        SigningPublicKey signingPubKey = (SigningPublicKey) signingKeys[0];
        SigningPrivateKey signingPrivKey = (SigningPrivateKey) signingKeys[1];
        KeyCertificate cert = new KeyCertificate(signingPubKey);
        Destination d = new Destination();
        d.setPublicKey(pub);
        d.setSigningPublicKey(signingPubKey);
        d.setCertificate(cert);
        int len = signingPubKey.length();
        if (len < 128) {
            byte[] pad = new byte[128 - len];
            RandomSource.getInstance().nextBytes(pad);
            d.setPadding(pad);
        } else if (len > 128) {
        // copy of excess data handled in KeyCertificate constructor
        }
        out = new SecureFileOutputStream(altFile);
        d.writeBytes(out);
        priv.writeBytes(out);
        signingPrivKey.writeBytes(out);
        try {
            out.close();
        } catch (IOException ioe) {
        }
        String destStr = d.toBase64();
        log("Alternate private key created and saved in " + altFile.getAbsolutePath());
        log("You should backup this file in a secure place.");
        log("New alternate destination: " + destStr);
        String b32 = d.toBase32();
        log("Base32: " + b32);
        File backupDir = new SecureFile(I2PAppContext.getGlobalContext().getConfigDir(), KEY_BACKUP_DIR);
        if (backupDir.isDirectory() || backupDir.mkdir()) {
            String name = b32 + '-' + I2PAppContext.getGlobalContext().clock().now() + ".dat";
            File backup = new File(backupDir, name);
            if (FileUtil.copy(altFile, backup, false, true)) {
                SecureFileOutputStream.setPerms(backup);
                log("Alternate private key backup saved to " + backup.getAbsolutePath());
            }
        }
        return true;
    } catch (GeneralSecurityException e) {
        log("Error creating keys " + e);
        return false;
    } catch (I2PSessionException e) {
        log("Error creating keys " + e);
        return false;
    } catch (I2PException e) {
        log("Error creating keys " + e);
        return false;
    } catch (IOException e) {
        log("Error creating keys " + e);
        return false;
    } catch (RuntimeException e) {
        log("Error creating keys " + e);
        return false;
    } finally {
        if (out != null)
            try {
                out.close();
            } catch (IOException ioe) {
            }
    }
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) SigningPublicKey(net.i2p.data.SigningPublicKey) PrivateKey(net.i2p.data.PrivateKey) SigningPrivateKey(net.i2p.data.SigningPrivateKey) SecureFile(net.i2p.util.SecureFile) SigningPublicKey(net.i2p.data.SigningPublicKey) PublicKey(net.i2p.data.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) PrivateKeyFile(net.i2p.data.PrivateKeyFile) IOException(java.io.IOException) SigningPrivateKey(net.i2p.data.SigningPrivateKey) KeyCertificate(net.i2p.data.KeyCertificate) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) FileOutputStream(java.io.FileOutputStream) I2PSessionException(net.i2p.client.I2PSessionException) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) SecureFile(net.i2p.util.SecureFile) PrivateKeyFile(net.i2p.data.PrivateKeyFile) File(java.io.File) SimpleDataStructure(net.i2p.data.SimpleDataStructure)

Aggregations

File (java.io.File)5 PrivateKeyFile (net.i2p.data.PrivateKeyFile)5 IOException (java.io.IOException)4 I2PException (net.i2p.I2PException)3 Destination (net.i2p.data.Destination)3 TunnelController (net.i2p.i2ptunnel.TunnelController)3 GeneralSecurityException (java.security.GeneralSecurityException)2 Properties (java.util.Properties)2 Certificate (net.i2p.data.Certificate)2 KeyCertificate (net.i2p.data.KeyCertificate)2 PrivateKey (net.i2p.data.PrivateKey)2 PublicKey (net.i2p.data.PublicKey)2 SigningPrivateKey (net.i2p.data.SigningPrivateKey)2 SigningPublicKey (net.i2p.data.SigningPublicKey)2 SimpleDataStructure (net.i2p.data.SimpleDataStructure)2 SecureFile (net.i2p.util.SecureFile)2 SecureFileOutputStream (net.i2p.util.SecureFileOutputStream)2 BufferedOutputStream (java.io.BufferedOutputStream)1 FileOutputStream (java.io.FileOutputStream)1 OutputStream (java.io.OutputStream)1