Search in sources :

Example 6 with PrivateKey

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

the class ElGamalTest method testRoundTrip.

public void testRoundTrip() {
    Object[] keys = KeyGenerator.getInstance().generatePKIKeypair();
    PublicKey pubKey = (PublicKey) keys[0];
    PrivateKey privKey = (PrivateKey) keys[1];
    String msg = "Hello world";
    Set toBeDelivered = new HashSet();
    SessionKey key = _context.sessionKeyManager().getCurrentKey(pubKey);
    if (key == null)
        key = _context.sessionKeyManager().createSession(pubKey);
    byte[] encrypted = _context.elGamalAESEngine().encrypt(DataHelper.getASCII(msg), pubKey, key, null, null, 64);
    byte[] decrypted = null;
    try {
        decrypted = _context.elGamalAESEngine().decrypt(encrypted, privKey, _context.sessionKeyManager());
    } catch (DataFormatException dfe) {
        dfe.printStackTrace();
        fail();
    }
    assertNotNull(decrypted);
    String read = new String(decrypted);
    assertEquals(msg, read);
}
Also used : PrivateKey(net.i2p.data.PrivateKey) Set(java.util.Set) HashSet(java.util.HashSet) DataFormatException(net.i2p.data.DataFormatException) PublicKey(net.i2p.data.PublicKey) SessionKey(net.i2p.data.SessionKey) HashSet(java.util.HashSet)

Example 7 with PrivateKey

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

the class ElGamalTest method testVerifyCompatability.

public void testVerifyCompatability() {
    PublicKey pub = new PublicKey();
    PrivateKey priv = new PrivateKey();
    try {
        pub.fromBase64(PUBLIC_KEY);
        priv.fromBase64(PRIVATE_KEY);
    } catch (DataFormatException dfe) {
        dfe.printStackTrace();
        fail();
    }
    for (int i = 0; i < ENCRYPTED.length; i++) {
        byte[] enc = Base64.decode(ENCRYPTED[i]);
        byte[] decrypted = _context.elGamalEngine().decrypt(enc, priv);
        assertTrue(DataHelper.eq(decrypted, DataHelper.getASCII(UNENCRYPTED[i])));
    }
}
Also used : PrivateKey(net.i2p.data.PrivateKey) DataFormatException(net.i2p.data.DataFormatException) PublicKey(net.i2p.data.PublicKey)

Example 8 with PrivateKey

use of net.i2p.data.PrivateKey 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 9 with PrivateKey

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

the class GarlicMessageReceiver method receive.

public void receive(GarlicMessage message) {
    PrivateKey decryptionKey;
    SessionKeyManager skm;
    if (_clientDestination != null) {
        LeaseSetKeys keys = _context.keyManager().getKeys(_clientDestination);
        skm = _context.clientManager().getClientSessionKeyManager(_clientDestination);
        if (keys != null && skm != null) {
            decryptionKey = keys.getDecryptionKey();
        } else {
            if (_log.shouldLog(Log.WARN))
                _log.warn("Not trying to decrypt a garlic routed message to a disconnected client");
            return;
        }
    } else {
        decryptionKey = _context.keyManager().getPrivateKey();
        skm = _context.sessionKeyManager();
    }
    CloveSet set = _context.garlicMessageParser().getGarlicCloves(message, decryptionKey, skm);
    if (set != null) {
        for (int i = 0; i < set.getCloveCount(); i++) {
            GarlicClove clove = set.getClove(i);
            handleClove(clove);
        }
    } else {
        if (_log.shouldLog(Log.WARN))
            _log.warn("CloveMessageParser failed to decrypt the message [" + message.getUniqueId() + "]", new Exception("Decrypt garlic failed"));
        _context.statManager().addRateData("crypto.garlic.decryptFail", 1);
        _context.messageHistory().messageProcessingError(message.getUniqueId(), message.getClass().getName(), "Garlic could not be decrypted");
    }
}
Also used : PrivateKey(net.i2p.data.PrivateKey) LeaseSetKeys(net.i2p.router.LeaseSetKeys) SessionKeyManager(net.i2p.crypto.SessionKeyManager) GarlicClove(net.i2p.data.i2np.GarlicClove)

Example 10 with PrivateKey

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

Aggregations

PrivateKey (net.i2p.data.PrivateKey)28 PublicKey (net.i2p.data.PublicKey)23 DataFormatException (net.i2p.data.DataFormatException)11 SigningPrivateKey (net.i2p.data.SigningPrivateKey)11 SessionKey (net.i2p.data.SessionKey)10 IOException (java.io.IOException)8 SigningPublicKey (net.i2p.data.SigningPublicKey)8 SessionKeyManager (net.i2p.crypto.SessionKeyManager)6 SigType (net.i2p.crypto.SigType)6 SimpleDataStructure (net.i2p.data.SimpleDataStructure)6 HashSet (java.util.HashSet)5 Destination (net.i2p.data.Destination)5 GeneralSecurityException (java.security.GeneralSecurityException)4 SessionTag (net.i2p.data.SessionTag)4 BufferedInputStream (java.io.BufferedInputStream)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 File (java.io.File)3 FileInputStream (java.io.FileInputStream)3 InputStream (java.io.InputStream)3 Properties (java.util.Properties)3