Search in sources :

Example 21 with SigningPublicKey

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

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

the class Packet method verifySignature.

/**
 * Determine whether the signature on the data is valid.
 *
 * @param ctx Application context
 * @param from the Destination the data came from
 * @param buffer data to validate with signature
 * @return true if the signature exists and validates against the data,
 *         false otherwise.
 */
public boolean verifySignature(I2PAppContext ctx, Destination from, byte[] buffer) {
    if (!isFlagSet(FLAG_SIGNATURE_INCLUDED))
        return false;
    if (_optionSignature == null)
        return false;
    // prevent receiveNewSyn() ... !active ... sendReset() ... verifySignature ... NPE
    if (from == null)
        return false;
    int size = writtenSize();
    if (buffer == null)
        buffer = new byte[size];
    SigningPublicKey spk = from.getSigningPublicKey();
    SigType type = spk.getType();
    if (type == null) {
        Log l = ctx.logManager().getLog(Packet.class);
        if (l.shouldLog(Log.WARN))
            l.warn("Unknown sig type in " + from + " cannot verify " + toString());
        return false;
    }
    int written = writePacket(buffer, 0, type.getSigLen());
    if (written != size) {
        ctx.logManager().getLog(Packet.class).error("Written " + written + " size " + size + " for " + toString(), new Exception("moo"));
        return false;
    }
    // on a close or reset packet where we have a signature without a FROM
    if (type != _optionSignature.getType() && type.getSigLen() == _optionSignature.length())
        _optionSignature = new Signature(type, _optionSignature.getData());
    boolean ok = ctx.dsa().verifySignature(_optionSignature, buffer, 0, size, spk);
    if (!ok) {
        Log l = ctx.logManager().getLog(Packet.class);
        if (l.shouldLog(Log.WARN))
            l.warn("Signature failed on " + toString(), new Exception("moo"));
    // if (false) {
    // l.error(Base64.encode(buffer, 0, size));
    // l.error("Signature: " + Base64.encode(_optionSignature.getData()));
    // }
    }
    return ok;
}
Also used : SigningPublicKey(net.i2p.data.SigningPublicKey) Log(net.i2p.util.Log) Signature(net.i2p.data.Signature) SigType(net.i2p.crypto.SigType) DataFormatException(net.i2p.data.DataFormatException) IOException(java.io.IOException)

Example 23 with SigningPublicKey

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

Example 24 with SigningPublicKey

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

the class LoadRouterInfoJob method readKeyData.

/**
 *  @param rkf1 in router.keys format, tried second
 *  @param rkf2 in eepPriv.dat format, tried first
 *  @return non-null, throws IOE if neither exisits
 *  @since 0.9.16
 */
public static KeyData readKeyData(File rkf1, File rkf2) throws DataFormatException, IOException {
    RouterIdentity ri;
    PrivateKey privkey;
    SigningPrivateKey signingPrivKey;
    if (rkf2.exists()) {
        RouterPrivateKeyFile pkf = new RouterPrivateKeyFile(rkf2);
        ri = pkf.getRouterIdentity();
        if (!pkf.validateKeyPairs())
            throw new DataFormatException("Key pairs invalid");
        privkey = pkf.getPrivKey();
        signingPrivKey = pkf.getSigningPrivKey();
    } else {
        InputStream fis = null;
        try {
            fis = new BufferedInputStream(new FileInputStream(rkf1));
            privkey = new PrivateKey();
            privkey.readBytes(fis);
            signingPrivKey = new SigningPrivateKey();
            signingPrivKey.readBytes(fis);
            PublicKey pubkey = new PublicKey();
            pubkey.readBytes(fis);
            SigningPublicKey signingPubKey = new SigningPublicKey();
            signingPubKey.readBytes(fis);
            // validate
            try {
                if (!pubkey.equals(KeyGenerator.getPublicKey(privkey)))
                    throw new DataFormatException("Key pairs invalid");
                if (!signingPubKey.equals(KeyGenerator.getSigningPublicKey(signingPrivKey)))
                    throw new DataFormatException("Key pairs invalid");
            } catch (IllegalArgumentException iae) {
                throw new DataFormatException("Key pairs invalid", iae);
            }
            ri = new RouterIdentity();
            ri.setPublicKey(pubkey);
            ri.setSigningPublicKey(signingPubKey);
            ri.setCertificate(Certificate.NULL_CERT);
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException ioe) {
                }
        }
    }
    return new KeyData(ri, privkey, signingPrivKey);
}
Also used : SigningPublicKey(net.i2p.data.SigningPublicKey) PrivateKey(net.i2p.data.PrivateKey) SigningPrivateKey(net.i2p.data.SigningPrivateKey) RouterIdentity(net.i2p.data.router.RouterIdentity) 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) FileInputStream(java.io.FileInputStream) SigningPrivateKey(net.i2p.data.SigningPrivateKey) RouterPrivateKeyFile(net.i2p.data.router.RouterPrivateKeyFile) DataFormatException(net.i2p.data.DataFormatException) BufferedInputStream(java.io.BufferedInputStream)

Example 25 with SigningPublicKey

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

the class DSABench method main.

public static void main(String[] args) {
    int times = 100;
    long keygentime = 0;
    long signtime = 0;
    long verifytime = 0;
    long maxKey = 0;
    long minKey = 0;
    long maxS = 0;
    long minS = 0;
    long maxV = 0;
    long minV = 0;
    Object[] keys = KeyGenerator.getInstance().generateSigningKeypair();
    byte[] message = new byte[32 + 32];
    for (int i = 0; i < message.length; i++) message[i] = (byte) ((i % 26) + 'a');
    for (int x = 0; x < times; x++) {
        long startkeys = System.currentTimeMillis();
        keys = KeyGenerator.getInstance().generateSigningKeypair();
        SigningPublicKey pubkey = (SigningPublicKey) keys[0];
        SigningPrivateKey privkey = (SigningPrivateKey) keys[1];
        long endkeys = System.currentTimeMillis();
        long startsign = System.currentTimeMillis();
        Signature s = DSAEngine.getInstance().sign(message, privkey);
        Signature s1 = DSAEngine.getInstance().sign(new ByteArrayInputStream(message), privkey);
        long endsignstartverify = System.currentTimeMillis();
        boolean v = DSAEngine.getInstance().verifySignature(s, message, pubkey);
        boolean v1 = DSAEngine.getInstance().verifySignature(s1, new ByteArrayInputStream(message), pubkey);
        boolean v2 = DSAEngine.getInstance().verifySignature(s1, message, pubkey);
        boolean v3 = DSAEngine.getInstance().verifySignature(s, new ByteArrayInputStream(message), pubkey);
        long endverify = System.currentTimeMillis();
        System.out.print(".");
        keygentime += endkeys - startkeys;
        signtime += endsignstartverify - startsign;
        verifytime += endverify - endsignstartverify;
        if (!v) {
            throw new RuntimeException("Holy crap, did not verify");
        }
        if (!(v1 && v2 && v3))
            throw new RuntimeException("Stream did not verify");
        if ((minKey == 0) && (minS == 0) && (minV == 0)) {
            minKey = endkeys - startkeys;
            maxKey = endkeys - startkeys;
            minS = endsignstartverify - startsign;
            maxS = endsignstartverify - startsign;
            minV = endverify - endsignstartverify;
            maxV = endverify - endsignstartverify;
        } else {
            if (minKey > endkeys - startkeys)
                minKey = endkeys - startkeys;
            if (maxKey < endkeys - startkeys)
                maxKey = endkeys - startkeys;
            if (minS > endsignstartverify - startsign)
                minS = endsignstartverify - startsign;
            if (maxS < endsignstartverify - startsign)
                maxS = endsignstartverify - startsign;
            if (minV > endverify - endsignstartverify)
                minV = endverify - endsignstartverify;
            if (maxV < endverify - endsignstartverify)
                maxV = endverify - endsignstartverify;
        }
    }
    System.out.println();
    System.out.println("Key Generation Time Average: " + (keygentime / times) + "\ttotal: " + keygentime + "\tmin: " + minKey + "\tmax: " + maxKey + "\tKeygen/second: " + (keygentime == 0 ? "NaN" : "" + (times * 1000) / keygentime));
    System.out.println("Signing Time Average       : " + (signtime / times) + "\ttotal: " + signtime + "\tmin: " + minS + "\tmax: " + maxS + "\tSigning Bps: " + (times * message.length * 1000) / signtime);
    System.out.println("Verification Time Average  : " + (verifytime / times) + "\ttotal: " + verifytime + "\tmin: " + minV + "\tmax: " + maxV + "\tDecryption Bps: " + (times * message.length * 1000) / verifytime);
}
Also used : SigningPrivateKey(net.i2p.data.SigningPrivateKey) SigningPublicKey(net.i2p.data.SigningPublicKey) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(net.i2p.data.Signature)

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