Search in sources :

Example 56 with DSAPrivateKey

use of java.security.interfaces.DSAPrivateKey in project robovm by robovm.

the class OpenSSLDSAKeyFactory method engineTranslateKey.

@Override
protected Key engineTranslateKey(Key key) throws InvalidKeyException {
    if (key == null) {
        throw new InvalidKeyException("key == null");
    }
    if ((key instanceof OpenSSLDSAPublicKey) || (key instanceof OpenSSLDSAPrivateKey)) {
        return key;
    } else if (key instanceof DSAPublicKey) {
        DSAPublicKey dsaKey = (DSAPublicKey) key;
        BigInteger y = dsaKey.getY();
        DSAParams params = dsaKey.getParams();
        BigInteger p = params.getP();
        BigInteger q = params.getQ();
        BigInteger g = params.getG();
        try {
            return engineGeneratePublic(new DSAPublicKeySpec(y, p, q, g));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if (key instanceof DSAPrivateKey) {
        DSAPrivateKey dsaKey = (DSAPrivateKey) key;
        BigInteger x = dsaKey.getX();
        DSAParams params = dsaKey.getParams();
        BigInteger p = params.getP();
        BigInteger q = params.getQ();
        BigInteger g = params.getG();
        try {
            return engineGeneratePrivate(new DSAPrivateKeySpec(x, p, q, g));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if ((key instanceof PrivateKey) && ("PKCS#8".equals(key.getFormat()))) {
        byte[] encoded = key.getEncoded();
        if (encoded == null) {
            throw new InvalidKeyException("Key does not support encoding");
        }
        try {
            return engineGeneratePrivate(new PKCS8EncodedKeySpec(encoded));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if ((key instanceof PublicKey) && ("X.509".equals(key.getFormat()))) {
        byte[] encoded = key.getEncoded();
        if (encoded == null) {
            throw new InvalidKeyException("Key does not support encoding");
        }
        try {
            return engineGeneratePublic(new X509EncodedKeySpec(encoded));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else {
        throw new InvalidKeyException("Key must be DSA public or private key; was " + key.getClass().getName());
    }
}
Also used : DSAPrivateKey(java.security.interfaces.DSAPrivateKey) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) DSAPublicKey(java.security.interfaces.DSAPublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) DSAParams(java.security.interfaces.DSAParams) InvalidKeyException(java.security.InvalidKeyException) DSAPublicKey(java.security.interfaces.DSAPublicKey) DSAPrivateKeySpec(java.security.spec.DSAPrivateKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) BigInteger(java.math.BigInteger) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) DSAPublicKeySpec(java.security.spec.DSAPublicKeySpec)

Example 57 with DSAPrivateKey

use of java.security.interfaces.DSAPrivateKey in project wycheproof by google.

the class DsaTest method testDsaBias.

/**
 * Checks whether the one time key k in DSA is biased. For example the SUN provider fell for this
 * test until April 2016.
 */
@SuppressWarnings("InsecureCryptoUsage")
@Test
public void testDsaBias() throws Exception {
    // q is close to 2/3 * 2^160.
    BigInteger q = new BigInteger("974317976835659416858874959372334979171063697271");
    BigInteger p = new BigInteger("1106803511314772711673172950296693567629309594518393175860816428" + "6658764043763662129010863568011543182924292444458455864283745070" + "9908516713302345161980412667892373845670780253725557376379049862" + "4062950082444499320797079243439689601679418602390654466821968220" + "32212146727497041502702331623782703855119908989712161");
    BigInteger g = new BigInteger("1057342118316953575810387190942009018497979302261477972033090351" + "7561815639397594841480480197745063606756857212792356354588585967" + "3837265237205154744016475608524531648654928648461175919672511710" + "4878976887505840764543501512668232945506391524642105449699321960" + "32410302985148400531470153936516167243072120845392903");
    BigInteger x = new BigInteger("13706102843888006547723575730792302382646994436");
    KeyFactory kf = KeyFactory.getInstance("DSA");
    DSAPrivateKey priv = (DSAPrivateKey) kf.generatePrivate(new DSAPrivateKeySpec(x, p, q, g));
    // If we make TESTS tests with a fair coin then the probability that
    // either heads or tails appears less than MINCOUNT times is less than
    // 2^{-32}.
    // I.e. 2*sum(binomial(tests,i) for i in range(mincount))*2**32 < 2**tests
    // Therefore the test below is not expected to fail unless the generation
    // of the one time keys is indeed biased.
    final int tests = 1024;
    final int mincount = 410;
    String hashAlgorithm = "SHA";
    String message = "Hello";
    byte[] messageBytes = message.getBytes("UTF-8");
    byte[] digest = MessageDigest.getInstance(hashAlgorithm).digest(messageBytes);
    BigInteger h = new BigInteger(1, digest);
    final BigInteger qHalf = q.shiftRight(1);
    Signature signer = Signature.getInstance("SHA1WithDSA");
    signer.initSign(priv);
    // count the number of k's with msb set
    int countLsb = 0;
    // count the number of k's with lsb set
    int countMsb = 0;
    for (int i = 0; i < tests; i++) {
        signer.update(messageBytes);
        byte[] signature = signer.sign();
        BigInteger k = extractK(signature, h, priv, i < 10);
        if (k.testBit(0)) {
            countLsb++;
        }
        if (k.compareTo(qHalf) == 1) {
            countMsb++;
        }
    }
    if (countLsb < mincount || countLsb > tests - mincount) {
        fail("Bias detected in the least significant bit of k:" + countLsb);
    }
    if (countMsb < mincount || countMsb > tests - mincount) {
        fail("Bias detected in the most significant bit of k:" + countMsb);
    }
}
Also used : DSAPrivateKeySpec(java.security.spec.DSAPrivateKeySpec) Signature(java.security.Signature) BigInteger(java.math.BigInteger) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) KeyFactory(java.security.KeyFactory) SlowTest(com.google.security.wycheproof.WycheproofRunner.SlowTest) Test(org.junit.Test)

Example 58 with DSAPrivateKey

use of java.security.interfaces.DSAPrivateKey in project wycheproof by google.

the class DsaTest method testBasic.

/**
 * This is just a test for basic functionality of DSA. The test generates a public and private
 * key, generates a signature and verifies it. This test is slow with some providers, since
 * some providers generate new DSA parameters (p and q) for each new key.
 */
@SlowTest(providers = { ProviderType.BOUNCY_CASTLE, ProviderType.SPONGY_CASTLE })
@SuppressWarnings("InsecureCryptoUsage")
@Test
public void testBasic() throws Exception {
    int keySize = 2048;
    String algorithm = "SHA256WithDSA";
    String message = "Hello";
    byte[] messageBytes = message.getBytes("UTF-8");
    KeyPairGenerator generator = java.security.KeyPairGenerator.getInstance("DSA");
    generator.initialize(keySize);
    KeyPair keyPair = generator.generateKeyPair();
    DSAPublicKey pub = (DSAPublicKey) keyPair.getPublic();
    DSAPrivateKey priv = (DSAPrivateKey) keyPair.getPrivate();
    Signature signer = Signature.getInstance(algorithm);
    Signature verifier = Signature.getInstance(algorithm);
    signer.initSign(priv);
    signer.update(messageBytes);
    byte[] signature = signer.sign();
    verifier.initVerify(pub);
    verifier.update(messageBytes);
    assertTrue(verifier.verify(signature));
}
Also used : KeyPair(java.security.KeyPair) Signature(java.security.Signature) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) KeyPairGenerator(java.security.KeyPairGenerator) DSAPublicKey(java.security.interfaces.DSAPublicKey) SlowTest(com.google.security.wycheproof.WycheproofRunner.SlowTest) SlowTest(com.google.security.wycheproof.WycheproofRunner.SlowTest) Test(org.junit.Test)

Example 59 with DSAPrivateKey

use of java.security.interfaces.DSAPrivateKey in project xipki by xipki.

the class SoftTokenContentSignerBuilder method createSigner.

public ConcurrentContentSigner createSigner(AlgorithmIdentifier signatureAlgId, int parallelism, SecureRandom random) throws XiSecurityException, NoSuchPaddingException {
    ParamUtil.requireNonNull("signatureAlgId", signatureAlgId);
    ParamUtil.requireMin("parallelism", parallelism, 1);
    List<XiContentSigner> signers = new ArrayList<>(parallelism);
    final String provName = "SunJCE";
    if (Security.getProvider(provName) != null) {
        String algoName;
        try {
            algoName = AlgorithmUtil.getSignatureAlgoName(signatureAlgId);
        } catch (NoSuchAlgorithmException ex) {
            throw new XiSecurityException(ex.getMessage());
        }
        try {
            for (int i = 0; i < parallelism; i++) {
                Signature signature = Signature.getInstance(algoName, provName);
                signature.initSign(key);
                if (i == 0) {
                    signature.update(new byte[] { 1, 2, 3, 4 });
                    signature.sign();
                }
                XiContentSigner signer = new SignatureSigner(signatureAlgId, signature, key);
                signers.add(signer);
            }
        } catch (Exception ex) {
            signers.clear();
        }
    }
    if (CollectionUtil.isEmpty(signers)) {
        BcContentSignerBuilder signerBuilder;
        AsymmetricKeyParameter keyparam;
        try {
            if (key instanceof RSAPrivateKey) {
                keyparam = SignerUtil.generateRSAPrivateKeyParameter((RSAPrivateKey) key);
                signerBuilder = new RSAContentSignerBuilder(signatureAlgId);
            } else if (key instanceof DSAPrivateKey) {
                keyparam = DSAUtil.generatePrivateKeyParameter(key);
                signerBuilder = new DSAContentSignerBuilder(signatureAlgId, AlgorithmUtil.isDSAPlainSigAlg(signatureAlgId));
            } else if (key instanceof ECPrivateKey) {
                keyparam = ECUtil.generatePrivateKeyParameter(key);
                EllipticCurve curve = ((ECPrivateKey) key).getParams().getCurve();
                if (GMUtil.isSm2primev2Curve(curve)) {
                    signerBuilder = new SM2ContentSignerBuilder();
                } else {
                    signerBuilder = new ECDSAContentSignerBuilder(signatureAlgId, AlgorithmUtil.isDSAPlainSigAlg(signatureAlgId));
                }
            } else {
                throw new XiSecurityException("unsupported key " + key.getClass().getName());
            }
        } catch (InvalidKeyException ex) {
            throw new XiSecurityException("invalid key", ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new XiSecurityException("no such algorithm", ex);
        }
        for (int i = 0; i < parallelism; i++) {
            if (random != null) {
                signerBuilder.setSecureRandom(random);
            }
            ContentSigner signer;
            try {
                signer = signerBuilder.build(keyparam);
            } catch (OperatorCreationException ex) {
                throw new XiSecurityException("operator creation error", ex);
            }
            signers.add(new XiWrappedContentSigner(signer, true));
        }
    }
    final boolean mac = false;
    ConcurrentContentSigner concurrentSigner;
    try {
        concurrentSigner = new DfltConcurrentContentSigner(mac, signers, key);
    } catch (NoSuchAlgorithmException ex) {
        throw new XiSecurityException(ex.getMessage(), ex);
    }
    if (certificateChain != null) {
        concurrentSigner.setCertificateChain(certificateChain);
    } else {
        concurrentSigner.setPublicKey(publicKey);
    }
    return concurrentSigner;
}
Also used : ArrayList(java.util.ArrayList) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) XiSecurityException(org.xipki.security.exception.XiSecurityException) XiWrappedContentSigner(org.xipki.security.XiWrappedContentSigner) DfltConcurrentContentSigner(org.xipki.security.DfltConcurrentContentSigner) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) XiContentSigner(org.xipki.security.XiContentSigner) BcContentSignerBuilder(org.bouncycastle.operator.bc.BcContentSignerBuilder) ECPrivateKey(java.security.interfaces.ECPrivateKey) DfltConcurrentContentSigner(org.xipki.security.DfltConcurrentContentSigner) ContentSigner(org.bouncycastle.operator.ContentSigner) XiContentSigner(org.xipki.security.XiContentSigner) XiWrappedContentSigner(org.xipki.security.XiWrappedContentSigner) ConcurrentContentSigner(org.xipki.security.ConcurrentContentSigner) InvalidKeyException(java.security.InvalidKeyException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) XiSecurityException(org.xipki.security.exception.XiSecurityException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) SignatureSigner(org.xipki.security.SignatureSigner) DfltConcurrentContentSigner(org.xipki.security.DfltConcurrentContentSigner) ConcurrentContentSigner(org.xipki.security.ConcurrentContentSigner) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) EllipticCurve(java.security.spec.EllipticCurve) Signature(java.security.Signature) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey)

Example 60 with DSAPrivateKey

use of java.security.interfaces.DSAPrivateKey in project chromeview by pwnall.

the class AndroidKeyStore method rawSignDigestWithPrivateKey.

/**
 * Sign a given message with a given PrivateKey object. This method
 * shall only be used to implement signing in the context of SSL
 * client certificate support.
 *
 * The message will actually be a hash, computed and padded by OpenSSL,
 * itself, depending on the type of the key. The result should match
 * exactly what the vanilla implementations of the following OpenSSL
 * function calls do:
 *
 *  - For a RSA private key, this should be equivalent to calling
 *    RSA_sign(NDI_md5_sha1,....), i.e. it must generate a raw RSA
 *    signature. The message must a combined, 36-byte MD5+SHA1 message
 *    digest padded to the length of the modulus using PKCS#1 padding.
 *
 *  - For a DSA and ECDSA private keys, this should be equivalent to
 *    calling DSA_sign(0,...) and ECDSA_sign(0,...) respectively. The
 *    message must be a 20-byte SHA1 hash and the function shall
 *    compute a direct DSA/ECDSA signature for it.
 *
 * @param privateKey The PrivateKey handle.
 * @param message The message to sign.
 * @return signature as a byte buffer.
 *
 * Important: Due to a platform bug, this function will always fail on
 *            Android < 4.2 for RSA PrivateKey objects. See the
 *            getOpenSSLHandleForPrivateKey() below for work-around.
 */
@CalledByNative
public static byte[] rawSignDigestWithPrivateKey(PrivateKey privateKey, byte[] message) {
    // Get the Signature for this key.
    Signature signature = null;
    // http://docs.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html
    try {
        if (privateKey instanceof RSAPrivateKey) {
            // IMPORTANT: Due to a platform bug, this will throw NoSuchAlgorithmException
            // on Android 4.0.x and 4.1.x. Fixed in 4.2 and higher.
            // See https://android-review.googlesource.com/#/c/40352/
            signature = Signature.getInstance("NONEwithRSA");
        } else if (privateKey instanceof DSAPrivateKey) {
            signature = Signature.getInstance("NONEwithDSA");
        } else if (privateKey instanceof ECPrivateKey) {
            signature = Signature.getInstance("NONEwithECDSA");
        }
    } catch (NoSuchAlgorithmException e) {
        ;
    }
    if (signature == null) {
        Log.e(TAG, "Unsupported private key algorithm: " + privateKey.getAlgorithm());
        return null;
    }
    // Sign the message.
    try {
        signature.initSign(privateKey);
        signature.update(message);
        return signature.sign();
    } catch (Exception e) {
        Log.e(TAG, "Exception while signing message with " + privateKey.getAlgorithm() + " private key: " + e);
        return null;
    }
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) Signature(java.security.Signature) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) InvocationTargetException(java.lang.reflect.InvocationTargetException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CalledByNative(org.chromium.base.CalledByNative)

Aggregations

DSAPrivateKey (java.security.interfaces.DSAPrivateKey)86 BigInteger (java.math.BigInteger)35 DSAPublicKey (java.security.interfaces.DSAPublicKey)31 DSAParams (java.security.interfaces.DSAParams)26 RSAPrivateCrtKey (java.security.interfaces.RSAPrivateCrtKey)25 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)25 ECPrivateKey (java.security.interfaces.ECPrivateKey)23 IOException (java.io.IOException)18 KeyPair (java.security.KeyPair)18 DSAPrivateKeySpec (java.security.spec.DSAPrivateKeySpec)15 PrivateKey (java.security.PrivateKey)14 DSAPublicKeySpec (java.security.spec.DSAPublicKeySpec)14 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)13 KeyFactory (java.security.KeyFactory)12 RSAPublicKey (java.security.interfaces.RSAPublicKey)12 PublicKey (java.security.PublicKey)11 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)10 InvalidKeyException (java.security.InvalidKeyException)9 KeyPairGenerator (java.security.KeyPairGenerator)9 ECPublicKey (java.security.interfaces.ECPublicKey)9