Search in sources :

Example 6 with SimpleDataStructure

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

the class KeyGenerator method generateSigningKeys.

/**
 *  DSA-SHA1 only.
 *
 *  Same as above but different return type
 *  @since 0.8.7
 */
public SimpleDataStructure[] generateSigningKeys() {
    SimpleDataStructure[] keys = new SimpleDataStructure[2];
    BigInteger x = null;
    // make sure the random key is less than the DSA q and greater than zero
    do {
        x = new NativeBigInteger(160, _context.random());
    } while (x.compareTo(CryptoConstants.dsaq) >= 0 || x.equals(BigInteger.ZERO));
    BigInteger y = CryptoConstants.dsag.modPow(x, CryptoConstants.dsap);
    keys[0] = new SigningPublicKey();
    keys[1] = new SigningPrivateKey();
    try {
        keys[0].setData(SigUtil.rectify(y, SigningPublicKey.KEYSIZE_BYTES));
        keys[1].setData(SigUtil.rectify(x, SigningPrivateKey.KEYSIZE_BYTES));
    } catch (InvalidKeyException ike) {
        throw new IllegalStateException(ike);
    }
    return keys;
}
Also used : SigningPrivateKey(net.i2p.data.SigningPrivateKey) SigningPublicKey(net.i2p.data.SigningPublicKey) NativeBigInteger(net.i2p.util.NativeBigInteger) BigInteger(java.math.BigInteger) NativeBigInteger(net.i2p.util.NativeBigInteger) InvalidKeyException(java.security.InvalidKeyException) SimpleDataStructure(net.i2p.data.SimpleDataStructure)

Example 7 with SimpleDataStructure

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

the class KeyGenerator method testSig.

private static void testSig(SigType type, int runs) throws GeneralSecurityException {
    byte[] src = new byte[512];
    double gtime = 0;
    long stime = 0;
    long vtime = 0;
    SimpleDataStructure[] keys = null;
    long st = System.nanoTime();
    // RSA super slow, limit to 5
    int genruns = (type.getBaseAlgorithm() == SigAlgo.RSA) ? Math.min(runs, 5) : runs;
    for (int i = 0; i < genruns; i++) {
        keys = KeyGenerator.getInstance().generateSigningKeys(type);
    }
    long en = System.nanoTime();
    gtime = ((en - st) / (1000 * 1000d)) / genruns;
    System.out.println(type + " key gen " + genruns + " times: " + gtime + " ms each");
    SigningPublicKey pubkey = (SigningPublicKey) keys[0];
    SigningPrivateKey privkey = (SigningPrivateKey) keys[1];
    SigningPublicKey pubkey2 = getSigningPublicKey(privkey);
    if (pubkey.equals(pubkey2))
        System.out.println(type + " private-to-public test PASSED");
    else
        System.out.println(type + " private-to-public test FAILED");
    // System.out.println("privkey " + keys[1]);
    MessageDigest md = type.getDigestInstance();
    for (int i = 0; i < runs; i++) {
        RandomSource.getInstance().nextBytes(src);
        md.update(src);
        byte[] sha = md.digest();
        SimpleDataStructure hash = type.getHashInstance();
        hash.setData(sha);
        long start = System.nanoTime();
        Signature sig = DSAEngine.getInstance().sign(src, privkey);
        Signature sig2 = DSAEngine.getInstance().sign(hash, privkey);
        if (sig == null)
            throw new GeneralSecurityException("signature generation failed");
        if (sig2 == null)
            throw new GeneralSecurityException("signature generation (H) failed");
        long mid = System.nanoTime();
        boolean ok = DSAEngine.getInstance().verifySignature(sig, src, pubkey);
        boolean ok2 = DSAEngine.getInstance().verifySignature(sig2, hash, pubkey);
        long end = System.nanoTime();
        stime += mid - start;
        vtime += end - mid;
        if (!ok)
            throw new GeneralSecurityException(type + " V(S(data)) fail");
        if (!ok2)
            throw new GeneralSecurityException(type + " V(S(H(data))) fail");
    }
    stime /= 1000 * 1000;
    vtime /= 1000 * 1000;
    System.out.println(type + " sign/verify " + runs + " times: " + (vtime + stime) + " ms = " + (((double) stime) / runs) + " each sign, " + (((double) vtime) / runs) + " each verify, " + (((double) (stime + vtime)) / runs) + " s+v");
}
Also used : SigningPrivateKey(net.i2p.data.SigningPrivateKey) SigningPublicKey(net.i2p.data.SigningPublicKey) Signature(net.i2p.data.Signature) GeneralSecurityException(java.security.GeneralSecurityException) MessageDigest(java.security.MessageDigest) SimpleDataStructure(net.i2p.data.SimpleDataStructure) ECPoint(java.security.spec.ECPoint)

Example 8 with SimpleDataStructure

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

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

the class SelfSignedGenerator method generate.

/**
 *  @param cname the common name, non-null. Must be a hostname or email address. IP addresses will not be correctly encoded.
 *  @param altNames the Subject Alternative Names. May be null. May contain hostnames and/or IP addresses.
 *                  cname, localhost, 127.0.0.1, and ::1 will be automatically added.
 *  @param ou The OU (organizational unit) in the distinguished name, non-null before 0.9.28, may be null as of 0.9.28
 *  @param o The O (organization)in the distinguished name, non-null before 0.9.28, may be null as of 0.9.28
 *  @param l The L (city or locality) in the distinguished name, non-null before 0.9.28, may be null as of 0.9.28
 *  @param st The ST (state or province) in the distinguished name, non-null before 0.9.28, may be null as of 0.9.28
 *  @param c The C (country) in the distinguished name, non-null before 0.9.28, may be null as of 0.9.28
 *
 *  @return length 4 array:
 *  rv[0] is a Java PublicKey
 *  rv[1] is a Java PrivateKey
 *  rv[2] is a Java X509Certificate
 *  rv[3] is a Java X509CRL
 *
 *  @since 0.9.34 added altNames param
 */
public static Object[] generate(String cname, Set<String> altNames, String ou, String o, String l, String st, String c, int validDays, SigType type) throws GeneralSecurityException {
    SimpleDataStructure[] keys = KeyGenerator.getInstance().generateSigningKeys(type);
    SigningPublicKey pub = (SigningPublicKey) keys[0];
    SigningPrivateKey priv = (SigningPrivateKey) keys[1];
    PublicKey jpub = SigUtil.toJavaKey(pub);
    PrivateKey jpriv = SigUtil.toJavaKey(priv);
    return generate(jpub, jpriv, priv, type, cname, altNames, ou, o, l, st, c, validDays);
}
Also used : SigningPrivateKey(net.i2p.data.SigningPrivateKey) SigningPublicKey(net.i2p.data.SigningPublicKey) SigningPrivateKey(net.i2p.data.SigningPrivateKey) PrivateKey(java.security.PrivateKey) SigningPublicKey(net.i2p.data.SigningPublicKey) PublicKey(java.security.PublicKey) DHPublicKey(javax.crypto.interfaces.DHPublicKey) SimpleDataStructure(net.i2p.data.SimpleDataStructure)

Example 10 with SimpleDataStructure

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

the class KeyPairGenerator method generateKeyPair.

public KeyPair generateKeyPair() {
    if (!initialized)
        initialize(DEFAULT_STRENGTH, RandomSource.getInstance());
    KeyGenerator kg = KeyGenerator.getInstance();
    SimpleDataStructure[] keys = kg.generatePKIKeys();
    PublicKey pubKey = (PublicKey) keys[0];
    PrivateKey privKey = (PrivateKey) keys[1];
    ElGamalPublicKey epubKey = new ElGamalPublicKeyImpl(new NativeBigInteger(1, pubKey.getData()), elgParams);
    ElGamalPrivateKey eprivKey = new ElGamalPrivateKeyImpl(new NativeBigInteger(1, privKey.getData()), elgParams);
    return new KeyPair(epubKey, eprivKey);
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(net.i2p.data.PrivateKey) ElGamalPublicKeyImpl(net.i2p.crypto.elgamal.impl.ElGamalPublicKeyImpl) NativeBigInteger(net.i2p.util.NativeBigInteger) ElGamalPrivateKeyImpl(net.i2p.crypto.elgamal.impl.ElGamalPrivateKeyImpl) PublicKey(net.i2p.data.PublicKey) KeyGenerator(net.i2p.crypto.KeyGenerator) SimpleDataStructure(net.i2p.data.SimpleDataStructure)

Aggregations

SimpleDataStructure (net.i2p.data.SimpleDataStructure)14 GeneralSecurityException (java.security.GeneralSecurityException)7 SigningPrivateKey (net.i2p.data.SigningPrivateKey)7 SigningPublicKey (net.i2p.data.SigningPublicKey)7 PrivateKey (net.i2p.data.PrivateKey)6 PublicKey (net.i2p.data.PublicKey)6 IOException (java.io.IOException)5 SigType (net.i2p.crypto.SigType)5 MessageDigest (java.security.MessageDigest)4 DataFormatException (net.i2p.data.DataFormatException)4 Signature (net.i2p.data.Signature)4 SecureFileOutputStream (net.i2p.util.SecureFileOutputStream)4 FileOutputStream (java.io.FileOutputStream)3 InputStream (java.io.InputStream)3 DigestInputStream (java.security.DigestInputStream)3 I2PException (net.i2p.I2PException)3 KeyCertificate (net.i2p.data.KeyCertificate)3 NativeBigInteger (net.i2p.util.NativeBigInteger)3 BufferedInputStream (java.io.BufferedInputStream)2 BufferedOutputStream (java.io.BufferedOutputStream)2