Example usage for org.bouncycastle.crypto.params DSAPrivateKeyParameters DSAPrivateKeyParameters

List of usage examples for org.bouncycastle.crypto.params DSAPrivateKeyParameters DSAPrivateKeyParameters

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.params DSAPrivateKeyParameters DSAPrivateKeyParameters.

Prototype

public DSAPrivateKeyParameters(BigInteger x, DSAParameters params) 

Source Link

Usage

From source file:com.google.nigori.common.DSASign.java

License:Apache License

/**
 * Given {@code privateKey} create a object capable of generating DSA signatures with it.
 * //from   w  ww.  j a va 2  s . com
 * @param privateKey an arbitrary-length big-Endian <i>positive</i> integer.
 * @throws NoSuchAlgorithmException
 */
public DSASign(byte[] privateKey) throws NoSuchAlgorithmException {
    super(NigoriConstants.DSA_G.modPow(Util.byteToBigInt(privateKey), NigoriConstants.DSA_P));
    this.privateKey = Util.byteToBigInt(privateKey);
    this.privateParams = new DSAPrivateKeyParameters(this.privateKey, NigoriConstants.DSA_PARAMS);
}

From source file:com.licel.jcardsim.crypto.DSAPrivateKeyImpl.java

License:Apache License

public CipherParameters getParameters() {
    if (!isInitialized()) {
        CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY);
    }//from   w  w w .  java 2  s.c o m
    return new DSAPrivateKeyParameters(x.getBigInteger(),
            ((DSAKeyParameters) super.getParameters()).getParameters());
}

From source file:edu.vt.middleware.crypt.signature.DSASignature.java

License:Open Source License

/** {@inheritDoc} */
public void initSign() {
    if (signKey == null) {
        throw new IllegalStateException("Sign key must be set prior to initialization.");
    }//from  www.  ja  v a 2 s. c om

    final DSAPrivateKey privKey = (DSAPrivateKey) signKey;
    final DSAParams params = privKey.getParams();
    final DSAPrivateKeyParameters bcParams = new DSAPrivateKeyParameters(privKey.getX(),
            new DSAParameters(params.getP(), params.getQ(), params.getG()));
    init(true, bcParams);
}

From source file:freenet.keys.InsertableClientSSK.java

License:GNU General Public License

public ClientSSKBlock encode(Bucket sourceData, boolean asMetadata, boolean dontCompress,
        short alreadyCompressedCodec, long sourceLength, RandomSource r, String compressordescriptor,
        boolean pre1254) throws SSKEncodeException, IOException, InvalidCompressionCodecException {
    byte[] compressedData;
    short compressionAlgo;
    try {//  w  w w. j a  v a2  s . co m
        Compressed comp = Key.compress(sourceData, dontCompress, alreadyCompressedCodec, sourceLength,
                ClientSSKBlock.MAX_DECOMPRESSED_DATA_LENGTH, SSKBlock.DATA_LENGTH, true, compressordescriptor,
                pre1254);
        compressedData = comp.compressedData;
        compressionAlgo = comp.compressionAlgorithm;
    } catch (KeyEncodeException e) {
        throw new SSKEncodeException(e.getMessage(), e);
    }
    // Pad it
    MessageDigest md256 = SHA256.getMessageDigest();
    try {
        byte[] data;
        // First pad it
        if (compressedData.length != SSKBlock.DATA_LENGTH) {
            // Hash the data
            if (compressedData.length != 0)
                md256.update(compressedData);
            byte[] digest = md256.digest();
            MersenneTwister mt = new MersenneTwister(digest);
            data = Arrays.copyOf(compressedData, SSKBlock.DATA_LENGTH);
            if (compressedData.length > data.length) {
                throw new RuntimeException(
                        "compressedData.length = " + compressedData.length + " but data.length=" + data.length);
            }
            Util.randomBytes(mt, data, compressedData.length, SSKBlock.DATA_LENGTH - compressedData.length);
        } else {
            data = compressedData;
        }

        // Implicit hash of data
        byte[] origDataHash = md256.digest(data);

        Rijndael aes;
        try {
            aes = new Rijndael(256, 256);
        } catch (UnsupportedCipherException e) {
            throw new Error("256/256 Rijndael not supported!");
        }

        // Encrypt data. Data encryption key = H(plaintext data).

        aes.initialize(origDataHash);
        PCFBMode pcfb = PCFBMode.create(aes, origDataHash);

        pcfb.blockEncipher(data, 0, data.length);

        byte[] encryptedDataHash = md256.digest(data);

        // Create headers

        byte[] headers = new byte[SSKBlock.TOTAL_HEADERS_LENGTH];
        // First two bytes = hash ID
        int x = 0;
        headers[x++] = (byte) (KeyBlock.HASH_SHA256 >> 8);
        headers[x++] = (byte) (KeyBlock.HASH_SHA256);
        // Then crypto ID
        headers[x++] = (byte) (Key.ALGO_AES_PCFB_256_SHA256 >> 8);
        headers[x++] = Key.ALGO_AES_PCFB_256_SHA256;
        // Then E(H(docname))
        // Copy to headers
        System.arraycopy(ehDocname, 0, headers, x, ehDocname.length);
        x += ehDocname.length;
        // Now the encrypted headers
        byte[] encryptedHeaders = Arrays.copyOf(origDataHash, SSKBlock.ENCRYPTED_HEADERS_LENGTH);
        int y = origDataHash.length;
        short len = (short) compressedData.length;
        if (asMetadata)
            len |= 32768;
        encryptedHeaders[y++] = (byte) (len >> 8);
        encryptedHeaders[y++] = (byte) len;
        encryptedHeaders[y++] = (byte) (compressionAlgo >> 8);
        encryptedHeaders[y++] = (byte) compressionAlgo;
        if (encryptedHeaders.length != y)
            throw new IllegalStateException("Have more bytes to generate encoding SSK");
        aes.initialize(cryptoKey);
        pcfb.reset(ehDocname);
        pcfb.blockEncipher(encryptedHeaders, 0, encryptedHeaders.length);
        System.arraycopy(encryptedHeaders, 0, headers, x, encryptedHeaders.length);
        x += encryptedHeaders.length;
        // Generate implicit overall hash.
        md256.update(headers, 0, x);
        md256.update(encryptedDataHash);
        byte[] overallHash = md256.digest();
        // Now sign it
        DSASigner dsa = new DSASigner(new HMacDSAKCalculator(new SHA256Digest()));
        dsa.init(true, new DSAPrivateKeyParameters(privKey.getX(), Global.getDSAgroupBigAParameters()));
        BigInteger[] sig = dsa.generateSignature(Global.truncateHash(overallHash));
        // Pack R and S into 32 bytes each, and copy to headers.
        // Then create and return the ClientSSKBlock.
        byte[] rBuf = truncate(sig[0].toByteArray(), SSKBlock.SIG_R_LENGTH);
        byte[] sBuf = truncate(sig[1].toByteArray(), SSKBlock.SIG_S_LENGTH);
        System.arraycopy(rBuf, 0, headers, x, rBuf.length);
        x += rBuf.length;
        System.arraycopy(sBuf, 0, headers, x, sBuf.length);
        x += sBuf.length;
        if (x != SSKBlock.TOTAL_HEADERS_LENGTH)
            throw new IllegalStateException("Too long");
        try {
            return new ClientSSKBlock(data, headers, this, !logMINOR);
        } catch (SSKVerifyException e) {
            throw (AssertionError) new AssertionError("Impossible encoding error").initCause(e);
        }
    } finally {
        SHA256.returnMessageDigest(md256);
    }
}

From source file:net.java.otr4j.crypto.DSAKeyPair.java

License:LGPL

/**
 * Sign data 'b' using DSA private key 'privateKey' and return signature components 'r' and 's'.
 *
 * @param b          The data to be signed.
 * @return Signature components 'r' and 's'.
 *//*from  www  .  j  av a 2 s  . c o  m*/
@Nonnull
public DSASignature signRS(final byte[] b) {
    assert !allZeroBytes(
            b) : "Expected non-zero bytes for b. This may indicate that a critical bug is present, or it may be a false warning.";
    final DSAParams dsaParams = privateKey.getParams();
    final DSAParameters bcDSAParameters = new DSAParameters(dsaParams.getP(), dsaParams.getQ(),
            dsaParams.getG());
    final DSAPrivateKeyParameters bcDSAPrivateKeyParms = new DSAPrivateKeyParameters(privateKey.getX(),
            bcDSAParameters);

    final DSASigner dsaSigner = new DSASigner();
    dsaSigner.init(true, bcDSAPrivateKeyParms);

    final BigInteger q = dsaParams.getQ();

    // Ian: Note that if you can get the standard DSA implementation you're
    // using to not hash its input, you should be able to pass it ((256-bit
    // value) mod q), (rather than truncating the 256-bit value) and all
    // should be well.
    // ref: Interop problems with libotr - DSA signature
    final BigInteger bmpi = new BigInteger(1, b);
    final BigInteger[] signature = dsaSigner.generateSignature(asUnsignedByteArray(bmpi.mod(q)));
    assert signature.length == 2 : "signRS result does not contain the expected 2 components: r and s";
    return new DSASignature(signature[0], signature[1]);
}

From source file:net.java.otr4j.crypto.OtrCryptoEngineImpl.java

License:Apache License

@Override
public byte[] sign(byte[] b, PrivateKey privatekey) throws OtrCryptoException {
    if (!(privatekey instanceof DSAPrivateKey))
        throw new IllegalArgumentException();

    DSAParams dsaParams = ((DSAPrivateKey) privatekey).getParams();
    DSAParameters bcDSAParameters = new DSAParameters(dsaParams.getP(), dsaParams.getQ(), dsaParams.getG());

    DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) privatekey;
    DSAPrivateKeyParameters bcDSAPrivateKeyParms = new DSAPrivateKeyParameters(dsaPrivateKey.getX(),
            bcDSAParameters);/*from  www. ja va  2 s .  c  om*/

    DSASigner dsaSigner = new DSASigner();
    dsaSigner.init(true, bcDSAPrivateKeyParms);

    BigInteger q = dsaParams.getQ();

    // Ian: Note that if you can get the standard DSA implementation you're
    // using to not hash its input, you should be able to pass it ((256-bit
    // value) mod q), (rather than truncating the 256-bit value) and all
    // should be well.
    // ref: Interop problems with libotr - DSA signature
    BigInteger bmpi = new BigInteger(1, b);
    BigInteger[] rs = dsaSigner.generateSignature(BigIntegers.asUnsignedByteArray(bmpi.mod(q)));

    int siglen = q.bitLength() / 4;
    int rslen = siglen / 2;
    byte[] rb = BigIntegers.asUnsignedByteArray(rs[0]);
    byte[] sb = BigIntegers.asUnsignedByteArray(rs[1]);

    // Create the final signature array, padded with zeros if necessary.
    byte[] sig = new byte[siglen];
    System.arraycopy(rb, 0, sig, rslen - rb.length, rb.length);
    System.arraycopy(sb, 0, sig, sig.length - sb.length, sb.length);
    return sig;
}

From source file:net.jradius.client.auth.EAPTLSAuthenticator.java

License:Open Source License

/**
 * Create a private key parameter from the passed in PKCS8 PrivateKeyInfo object.
 * // ww  w.j  a v a 2  s  . c o  m
 * @param keyInfo the PrivateKeyInfo object containing the key material
 * @return a suitable private key parameter
 * @throws IOException on an error decoding the key
 */
public static AsymmetricKeyParameter createKey(PrivateKeyInfo keyInfo) throws IOException {
    AlgorithmIdentifier algId = keyInfo.getAlgorithmId();

    if (algId.getObjectId().equals(PKCSObjectIdentifiers.rsaEncryption)) {
        RSAPrivateKeyStructure keyStructure = new RSAPrivateKeyStructure(
                (ASN1Sequence) keyInfo.getPrivateKey());

        return new RSAPrivateCrtKeyParameters(keyStructure.getModulus(), keyStructure.getPublicExponent(),
                keyStructure.getPrivateExponent(), keyStructure.getPrime1(), keyStructure.getPrime2(),
                keyStructure.getExponent1(), keyStructure.getExponent2(), keyStructure.getCoefficient());
    } else if (algId.getObjectId().equals(PKCSObjectIdentifiers.dhKeyAgreement)) {
        DHParameter params = new DHParameter((ASN1Sequence) keyInfo.getAlgorithmId().getParameters());
        DERInteger derX = (DERInteger) keyInfo.getPrivateKey();

        BigInteger lVal = params.getL();
        int l = lVal == null ? 0 : lVal.intValue();
        DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l);

        return new DHPrivateKeyParameters(derX.getValue(), dhParams);
    } else if (algId.getObjectId().equals(OIWObjectIdentifiers.elGamalAlgorithm)) {
        ElGamalParameter params = new ElGamalParameter((ASN1Sequence) keyInfo.getAlgorithmId().getParameters());
        DERInteger derX = (DERInteger) keyInfo.getPrivateKey();

        return new ElGamalPrivateKeyParameters(derX.getValue(),
                new ElGamalParameters(params.getP(), params.getG()));
    } else if (algId.getObjectId().equals(X9ObjectIdentifiers.id_dsa)) {
        DERInteger derX = (DERInteger) keyInfo.getPrivateKey();
        DEREncodable de = keyInfo.getAlgorithmId().getParameters();

        DSAParameters parameters = null;
        if (de != null) {
            DSAParameter params = DSAParameter.getInstance(de.getDERObject());
            parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
        }

        return new DSAPrivateKeyParameters(derX.getValue(), parameters);
    } else if (algId.getObjectId().equals(X9ObjectIdentifiers.id_ecPublicKey)) {
        X962Parameters params = new X962Parameters((DERObject) keyInfo.getAlgorithmId().getParameters());
        ECDomainParameters dParams = null;

        if (params.isNamedCurve()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) params.getParameters();
            X9ECParameters ecP = X962NamedCurves.getByOID(oid);

            if (ecP == null) {
                ecP = SECNamedCurves.getByOID(oid);

                if (ecP == null) {
                    ecP = NISTNamedCurves.getByOID(oid);

                    if (ecP == null) {
                        ecP = TeleTrusTNamedCurves.getByOID(oid);
                    }
                }
            }

            dParams = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed());
        } else {
            X9ECParameters ecP = new X9ECParameters((ASN1Sequence) params.getParameters());
            dParams = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed());
        }

        ECPrivateKeyStructure ec = new ECPrivateKeyStructure((ASN1Sequence) keyInfo.getPrivateKey());

        return new ECPrivateKeyParameters(ec.getKey(), dParams);
    } else {
        throw new RuntimeException("algorithm identifier in key not recognised");
    }
}

From source file:org.cryptacular.asn.OpenSSLPrivateKeyDecoder.java

License:Open Source License

@Override
protected AsymmetricKeyParameter decodeASN1(final byte[] encoded) {
    final ASN1Object o;
    try {/*  ww w. ja va 2s . co m*/
        o = ASN1Primitive.fromByteArray(encoded);
    } catch (Exception e) {
        throw new IllegalArgumentException("Invalid encoded key");
    }

    final AsymmetricKeyParameter key;
    if (o instanceof ASN1ObjectIdentifier) {
        // EC private key with named curve in the default OpenSSL format emitted
        // by
        //
        // openssl ecparam -name xxxx -genkey
        //
        // which is the concatenation of the named curve OID and a sequence of 1
        // containing the private point
        final ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(o);
        final int len = encoded[1];
        final byte[] privatePart = new byte[encoded.length - len - 2];
        System.arraycopy(encoded, len + 2, privatePart, 0, privatePart.length);

        final ASN1Sequence seq = ASN1Sequence.getInstance(privatePart);
        final X9ECParameters params = ECUtil.getNamedCurveByOid(oid);
        key = new ECPrivateKeyParameters(ASN1Integer.getInstance(seq.getObjectAt(0)).getValue(),
                new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH(),
                        params.getSeed()));
    } else {
        // OpenSSL "traditional" format is an ASN.1 sequence of key parameters

        // Detect key type based on number and types of parameters:
        // RSA -> {version, mod, pubExp, privExp, prime1, prime2, exp1, exp2, c}
        // DSA -> {version, p, q, g, pubExp, privExp}
        // EC ->  {version, privateKey, parameters, publicKey}
        final ASN1Sequence sequence = ASN1Sequence.getInstance(o);
        if (sequence.size() == 9) {
            // RSA private certificate key
            key = new RSAPrivateCrtKeyParameters(ASN1Integer.getInstance(sequence.getObjectAt(1)).getValue(),
                    ASN1Integer.getInstance(sequence.getObjectAt(2)).getValue(),
                    ASN1Integer.getInstance(sequence.getObjectAt(3)).getValue(),
                    ASN1Integer.getInstance(sequence.getObjectAt(4)).getValue(),
                    ASN1Integer.getInstance(sequence.getObjectAt(5)).getValue(),
                    ASN1Integer.getInstance(sequence.getObjectAt(6)).getValue(),
                    ASN1Integer.getInstance(sequence.getObjectAt(7)).getValue(),
                    ASN1Integer.getInstance(sequence.getObjectAt(8)).getValue());
        } else if (sequence.size() == 6) {
            // DSA private key
            key = new DSAPrivateKeyParameters(ASN1Integer.getInstance(sequence.getObjectAt(5)).getValue(),
                    new DSAParameters(ASN1Integer.getInstance(sequence.getObjectAt(1)).getValue(),
                            ASN1Integer.getInstance(sequence.getObjectAt(2)).getValue(),
                            ASN1Integer.getInstance(sequence.getObjectAt(3)).getValue()));
        } else if (sequence.size() == 4) {
            // EC private key with explicit curve
            final X9ECParameters params = X9ECParameters
                    .getInstance(ASN1TaggedObject.getInstance(sequence.getObjectAt(2)).getObject());
            key = new ECPrivateKeyParameters(
                    new BigInteger(ASN1OctetString.getInstance(sequence.getObjectAt(1)).getOctets()),
                    new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH(),
                            params.getSeed()));
        } else {
            throw new IllegalArgumentException("Invalid OpenSSL traditional private key format.");
        }
    }
    return key;
}

From source file:org.cryptacular.util.KeyPairUtil.java

License:Open Source License

/**
 * Determines whether the given DSA public and private keys form a proper key
 * pair by computing and verifying a digital signature with the keys.
 *
 * @param  pubKey  DSA public key.//from ww w.ja  va2  s . c o m
 * @param  privKey  DSA private key.
 *
 * @return  True if the keys form a functioning keypair, false otherwise.
 *          Errors during signature verification are treated as false.
 */
public static boolean isKeyPair(final DSAPublicKey pubKey, final DSAPrivateKey privKey) {
    final DSASigner signer = new DSASigner();
    final DSAParameters params = new DSAParameters(privKey.getParams().getP(), privKey.getParams().getQ(),
            privKey.getParams().getG());
    signer.init(true, new DSAPrivateKeyParameters(privKey.getX(), params));

    final BigInteger[] sig = signer.generateSignature(SIGN_BYTES);
    signer.init(false, new DSAPublicKeyParameters(pubKey.getY(), params));
    try {
        return signer.verifySignature(SIGN_BYTES, sig[0], sig[1]);
    } catch (Exception e) {
        return false;
    }
}