Search in sources :

Example 46 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 47 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 48 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 49 with DSAPrivateKey

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

the class DSAKeyValueType method convertToPrivateKey.

/**
 * Convert to the JDK representation of a DSA Private Key
 *
 * @return
 *
 * @throws ProcessingException
 */
public DSAPrivateKey convertToPrivateKey() throws ProcessingException {
    try {
        BigInteger BigY = new BigInteger(1, massage(Base64.decode(new String(y))));
        BigInteger BigP = new BigInteger(1, massage(Base64.decode(new String(p))));
        BigInteger BigQ = new BigInteger(1, massage(Base64.decode(new String(q))));
        BigInteger BigG = new BigInteger(1, massage(Base64.decode(new String(g))));
        KeyFactory dsaKeyFactory = KeyFactory.getInstance("dsa");
        DSAPrivateKeySpec kspec = new DSAPrivateKeySpec(BigY, BigP, BigQ, BigG);
        return (DSAPrivateKey) dsaKeyFactory.generatePrivate(kspec);
    } catch (Exception e) {
        throw new ProcessingException(e);
    }
}
Also used : DSAPrivateKeySpec(java.security.spec.DSAPrivateKeySpec) BigInteger(java.math.BigInteger) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) KeyFactory(java.security.KeyFactory) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException)

Example 50 with DSAPrivateKey

use of java.security.interfaces.DSAPrivateKey in project keystore-explorer by kaikramer.

the class DProperties method createPrivateKeyNodes.

private void createPrivateKeyNodes(DefaultMutableTreeNode parentNode, PrivateKey privateKey) throws CryptoException {
    DefaultMutableTreeNode privateKeyNode = new DefaultMutableTreeNode(res.getString("DProperties.properties.PrivateKey"));
    parentNode.add(privateKeyNode);
    currentState.getKeyStore();
    KeyInfo keyInfo = KeyPairUtil.getKeyInfo(privateKey);
    String keyAlg = keyInfo.getAlgorithm();
    privateKeyNode.add(new DefaultMutableTreeNode(MessageFormat.format(res.getString("DProperties.properties.Algorithm"), keyAlg)));
    Integer keySize = keyInfo.getSize();
    if (keySize != null) {
        privateKeyNode.add(new DefaultMutableTreeNode(MessageFormat.format(res.getString("DProperties.properties.KeySize"), "" + keyInfo.getSize())));
    } else {
        privateKeyNode.add(new DefaultMutableTreeNode(MessageFormat.format(res.getString("DProperties.properties.KeySize"), "?")));
    }
    String keyFormat = privateKey.getFormat();
    privateKeyNode.add(new DefaultMutableTreeNode(MessageFormat.format(res.getString("DProperties.properties.Format"), keyFormat)));
    String keyEncoded;
    byte[] encodedKey = privateKey.getEncoded();
    if (encodedKey != null) {
        keyEncoded = "0x" + new BigInteger(1, privateKey.getEncoded()).toString(16).toUpperCase();
    } else {
        keyEncoded = "*****";
    }
    privateKeyNode.add(new DefaultMutableTreeNode(MessageFormat.format(res.getString("DProperties.properties.Encoded"), keyEncoded)));
    if (privateKey instanceof RSAPrivateCrtKey) {
        RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey;
        String publicExponent = MessageFormat.format(res.getString("DProperties.properties.private.rsa.PublicExponent"), "0x" + rsaPrivateKey.getPublicExponent().toString(16).toUpperCase());
        privateKeyNode.add(new DefaultMutableTreeNode(publicExponent));
        String modulus = MessageFormat.format(res.getString("DProperties.properties.private.rsa.Modulus"), "0x" + rsaPrivateKey.getModulus().toString(16).toUpperCase());
        privateKeyNode.add(new DefaultMutableTreeNode(modulus));
        String primeP = MessageFormat.format(res.getString("DProperties.properties.private.rsa.PrimeP"), "0x" + rsaPrivateKey.getPrimeP().toString(16).toUpperCase());
        privateKeyNode.add(new DefaultMutableTreeNode(primeP));
        String primeQ = MessageFormat.format(res.getString("DProperties.properties.private.rsa.PrimeQ"), "0x" + rsaPrivateKey.getPrimeQ().toString(16).toUpperCase());
        privateKeyNode.add(new DefaultMutableTreeNode(primeQ));
        String primeExponentP = MessageFormat.format(res.getString("DProperties.properties.private.rsa.PrimeExponentP"), "0x" + rsaPrivateKey.getPrimeExponentP().toString(16).toUpperCase());
        privateKeyNode.add(new DefaultMutableTreeNode(primeExponentP));
        String primeExponentQ = MessageFormat.format(res.getString("DProperties.properties.private.rsa.PrimeExponentQ"), "0x" + rsaPrivateKey.getPrimeExponentQ().toString(16).toUpperCase());
        privateKeyNode.add(new DefaultMutableTreeNode(primeExponentQ));
        String crtCoefficient = MessageFormat.format(res.getString("DProperties.properties.private.rsa.CrtCoefficient"), "0x" + rsaPrivateKey.getCrtCoefficient().toString(16).toUpperCase());
        privateKeyNode.add(new DefaultMutableTreeNode(crtCoefficient));
        String privateExponent = MessageFormat.format(res.getString("DProperties.properties.private.rsa.PrivateExponent"), "0x" + rsaPrivateKey.getPrivateExponent().toString(16).toUpperCase());
        privateKeyNode.add(new DefaultMutableTreeNode(privateExponent));
    } else if (privateKey instanceof DSAPrivateKey) {
        DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) privateKey;
        DSAParams dsaParams = dsaPrivateKey.getParams();
        String primeModulusP = MessageFormat.format(res.getString("DProperties.properties.private.dsa.PrimeModulusP"), "0x" + dsaParams.getP().toString(16).toUpperCase());
        privateKeyNode.add(new DefaultMutableTreeNode(primeModulusP));
        String primeQ = MessageFormat.format(res.getString("DProperties.properties.private.dsa.PrimeQ"), "0x" + dsaParams.getQ().toString(16).toUpperCase());
        privateKeyNode.add(new DefaultMutableTreeNode(primeQ));
        String generatorG = MessageFormat.format(res.getString("DProperties.properties.private.dsa.GeneratorG"), "0x" + dsaParams.getG().toString(16).toUpperCase());
        privateKeyNode.add(new DefaultMutableTreeNode(generatorG));
        String secretExponentX = MessageFormat.format(res.getString("DProperties.properties.private.dsa.SecretExponentX"), "0x" + dsaPrivateKey.getX().toString(16).toUpperCase());
        privateKeyNode.add(new DefaultMutableTreeNode(secretExponentX));
    }
}
Also used : BigInteger(java.math.BigInteger) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) KeyInfo(org.kse.crypto.KeyInfo) BigInteger(java.math.BigInteger) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) DSAParams(java.security.interfaces.DSAParams)

Aggregations

DSAPrivateKey (java.security.interfaces.DSAPrivateKey)64 BigInteger (java.math.BigInteger)30 DSAParams (java.security.interfaces.DSAParams)22 DSAPublicKey (java.security.interfaces.DSAPublicKey)20 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)20 IOException (java.io.IOException)16 KeyPair (java.security.KeyPair)15 RSAPrivateCrtKey (java.security.interfaces.RSAPrivateCrtKey)15 DSAPrivateKeySpec (java.security.spec.DSAPrivateKeySpec)14 ECPrivateKey (java.security.interfaces.ECPrivateKey)13 DSAPublicKeySpec (java.security.spec.DSAPublicKeySpec)11 KeyFactory (java.security.KeyFactory)9 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)9 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)9 KeyPairGenerator (java.security.KeyPairGenerator)8 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)8 InvalidKeyException (java.security.InvalidKeyException)7 PrivateKey (java.security.PrivateKey)7 Signature (java.security.Signature)6 PublicKey (java.security.PublicKey)5