public static SigningPrivateKey createPrivateKey(BigInteger x, BigInteger p, BigInteger q, BigInteger g) throws NoSuchAlgorithmException, InvalidKeySpecException { if (x == null) { throw new IllegalArgumentException("x must not be null"); } if (p == null) { throw new IllegalArgumentException("p must not be null"); } if (q == null) { throw new IllegalArgumentException("q must not be null"); } if (g == null) { throw new IllegalArgumentException("g must not be null"); } KeySpec keySpec = new DSAPrivateKeySpec(x, p, q, g); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); DSAPrivateKey privateKey = (DSAPrivateKey) keyFactory.generatePrivate(keySpec); return new DSASigningPrivateKey(privateKey); }
/** Extract the k that was used to sign the signature. Validates the k if check == true. */ BigInteger extractK(byte[] signature, BigInteger h, DSAPrivateKey priv, boolean check) throws Exception { BigInteger x = priv.getX(); BigInteger q = priv.getParams().getQ(); BigInteger r = extractR(signature); BigInteger s = extractS(signature); BigInteger k = x.multiply(r).add(h).multiply(s.modInverse(q)).mod(q); if (check) { BigInteger p = priv.getParams().getP(); BigInteger g = priv.getParams().getG(); BigInteger r2 = g.modPow(k, p).mod(q); assertEquals(r.toString(), r2.toString()); } return k; }
private BigInteger[] computeRS(final byte[] digestBytes) { final BigInteger p = ((DSAPrivateKey) privateKey).getParams().getP(); final BigInteger q = ((DSAPrivateKey) privateKey).getParams().getQ(); final BigInteger g = ((DSAPrivateKey) privateKey).getParams().getG(); final BigInteger x = ((DSAPrivateKey) privateKey).getX(); final BigInteger m = new BigInteger(1, digestBytes); BigInteger k, r, s; final byte[] kb = new byte[20]; // we'll use 159 bits only while (true) { this.nextRandomBytes(kb); k = new BigInteger(1, kb); k.clearBit(159); r = g.modPow(k, p).mod(q); if (r.equals(BigInteger.ZERO)) continue; s = m.add(x.multiply(r)).multiply(k.modInverse(q)).mod(q); if (s.equals(BigInteger.ZERO)) continue; break; } return new BigInteger[] { r, s }; }
@Test public void shouldParseAPKCS1DSAPrivateKey() throws Exception { String keyString = "" + "-----BEGIN DSA PRIVATE KEY-----\n" + "MIH5AgEAAkEA/8/aIwYwD4TUzee5AQvz4Bk24nAozkCJOOK/WEtLmlfdK3pWeZ7W\n" + "ttD65kJFgFZE1hDi0D0ipuXwFIJhqzoMcQIVAORLzKnx1wfBs3Mngrh3XfyqOmUl\n" + "AkEAvjDa+zB5mfAfIaYOgpuJzEGnLnj9VGLZEGVC/w3l5ML3PblMCLMniHzIT3UQ\n" + "jQtTwOfiWa7RdAFrmjU7OQxJCQJBALhjbXYy4uG3yMV+h/Sd6SgxqgDr17n1dk2Q\n" + "H2r/4sMppgtMgCLNvb/3kuvK8novAEaHDEojWUkwtsSrsgXFLacCFARPJrGexYk7\n" + "b3cNk+Qay5BqrbF3\n" + "-----END DSA PRIVATE KEY-----"; Key key = CryptoParser.parseKey(keyString); assertThat(((DSAPrivateKey) key).getX(), hasToString(startsWith("2460109266"))); }
private byte[] getPvkEncodedPrivateKey(PrivateKey privateKey, int keyType, Password password, boolean strongEncryption) throws CryptoException, IOException { byte[] encoded = null; if (password != null) { if (privateKey instanceof RSAPrivateCrtKey) { encoded = MsPvkUtil.getEncrypted((RSAPrivateCrtKey) privateKey, keyType, password, strongEncryption); } else { encoded = MsPvkUtil.getEncrypted((DSAPrivateKey) privateKey, password, strongEncryption); } } else { if (privateKey instanceof RSAPrivateCrtKey) { encoded = MsPvkUtil.get((RSAPrivateCrtKey) privateKey, keyType); } else { encoded = MsPvkUtil.get((DSAPrivateKey) privateKey); } } return encoded; }
private void populateDialog() throws CryptoException { KeyInfo keyInfo = KeyPairUtil.getKeyInfo(privateKey); jtfAlgorithm.setText(keyInfo.getAlgorithm()); Integer keyLength = keyInfo.getSize(); if (keyLength != null) { jtfKeySize.setText(MessageFormat.format(res.getString("DViewPrivateKey.jtfKeySize.text"), "" + keyLength)); } else { jtfKeySize.setText(MessageFormat.format(res.getString("DViewPrivateKey.jtfKeySize.text"), "?")); } jtfFormat.setText(privateKey.getFormat()); jtfEncoded.setText("0x" + new BigInteger(1, privateKey.getEncoded()).toString(16).toUpperCase()); jtfEncoded.setCaretPosition(0); if ((privateKey instanceof RSAPrivateKey) || (privateKey instanceof DSAPrivateKey)) { jbFields.setEnabled(true); } else { jbFields.setEnabled(false); } }
protected boolean isEntryPrivateKeyEqual(KeyStoreState targetState, String alias, Password password) throws GeneralSecurityException { Key currentKey = keyStore.getKey(alias, password.toCharArray()); Key targetKey = targetState.getKeyStore().getKey(alias, password.toCharArray()); // JDKDSAPrivateKey has no equals method defined if ((currentKey instanceof JDKDSAPrivateKey) || (targetKey instanceof JDKDSAPrivateKey)) { DSAPrivateKey currentDsaKey = (DSAPrivateKey) currentKey; DSAPrivateKey targetDsaKey = (DSAPrivateKey) targetKey; return currentDsaKey.getX().equals(targetDsaKey.getX()) && currentDsaKey.getParams().getG().equals(targetDsaKey.getParams().getG()) && currentDsaKey.getParams().getP().equals(targetDsaKey.getParams().getP()) && currentDsaKey.getParams().getQ().equals(targetDsaKey.getParams().getQ()); } else { return currentKey.equals(targetKey); } }
private DsaPrivateKey initFromJson() throws KeyczarException { this.publicKey.initFromJson(); BigInteger localBigInteger1 = new BigInteger(Base64Coder.decodeWebSafe(this.x)); BigInteger localBigInteger2 = new BigInteger(Base64Coder.decodeWebSafe(this.publicKey.p)); BigInteger localBigInteger3 = new BigInteger(Base64Coder.decodeWebSafe(this.publicKey.q)); BigInteger localBigInteger4 = new BigInteger(Base64Coder.decodeWebSafe(this.publicKey.g)); try { this.jcePrivateKey = ((DSAPrivateKey)KeyFactory.getInstance("DSA").generatePrivate(new DSAPrivateKeySpec(localBigInteger1, localBigInteger2, localBigInteger3, localBigInteger4))); return this; } catch (GeneralSecurityException localGeneralSecurityException) { throw new KeyczarException(localGeneralSecurityException); } }
static void checkAlgorithm(PrivateKey key, int alg) throws UnsupportedAlgorithmException { switch (alg) { case Algorithm.RSAMD5: case Algorithm.RSASHA1: case Algorithm.RSA_NSEC3_SHA1: case Algorithm.RSASHA256: case Algorithm.RSASHA512: if (! (key instanceof RSAPrivateKey)) throw new IncompatibleKeyException(); break; case Algorithm.DSA: case Algorithm.DSA_NSEC3_SHA1: if (! (key instanceof DSAPrivateKey)) throw new IncompatibleKeyException(); break; default: throw new UnsupportedAlgorithmException(alg); } }
public void regenerateLocalPublicKey(KeyFactory factory, String fullUserId, DSAPrivateKey privKey) { String userId = Address.stripResource(fullUserId); BigInteger x = privKey.getX(); DSAParams params = privKey.getParams(); BigInteger y = params.getG().modPow(x, params.getP()); DSAPublicKeySpec keySpec = new DSAPublicKeySpec(y, params.getP(), params.getQ(), params.getG()); PublicKey pubKey; try { pubKey = factory.generatePublic(keySpec); storeLocalPublicKey(userId, pubKey); } catch (Exception e) { throw new RuntimeException(e); } }
public PublicKey getPublicKey() throws GeneralSecurityException { if (privateKey instanceof DSAPrivateKey) { DSAPrivateKey dsa = (DSAPrivateKey) privateKey; DSAParams params = dsa.getParams(); BigInteger g = params.getG(); BigInteger p = params.getP(); BigInteger q = params.getQ(); BigInteger x = dsa.getX(); BigInteger y = q.modPow( x, p ); DSAPublicKeySpec dsaKeySpec = new DSAPublicKeySpec(y, p, q, g); return KeyFactory.getInstance("DSA").generatePublic(dsaKeySpec); } else if (privateKey instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey rsa = (RSAPrivateCrtKey) privateKey; RSAPublicKeySpec rsaKeySpec = new RSAPublicKeySpec( rsa.getModulus(), rsa.getPublicExponent() ); return KeyFactory.getInstance("RSA").generatePublic(rsaKeySpec); } else { throw new GeneralSecurityException("Not an RSA or DSA key"); } }
/** * @tests java.security.interfaces.DSAPrivateKey * #getX() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "getX", args = {} ) public void test_getX() throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(new DSAParameterSpec(Util.P, Util.Q, Util.G), new SecureRandom(new MySecureRandomSpi(), null) { }); KeyPair keyPair = keyGen.generateKeyPair(); DSAPrivateKey key = (DSAPrivateKey) keyPair.getPrivate(); assertNotNull("Invalid X value", key.getX()); }
public Ssh2DsaPrivateKey(BigInteger p, BigInteger q, BigInteger g, BigInteger x, BigInteger y) throws SshException { try { KeyFactory kf = JCEProvider .getProviderForAlgorithm(JCEAlgorithms.JCE_DSA) == null ? KeyFactory .getInstance(JCEAlgorithms.JCE_DSA) : KeyFactory .getInstance(JCEAlgorithms.JCE_DSA, JCEProvider .getProviderForAlgorithm(JCEAlgorithms.JCE_DSA)); DSAPrivateKeySpec spec = new DSAPrivateKeySpec(x, p, q, g); prv = (DSAPrivateKey) kf.generatePrivate(spec); pub = new Ssh2DsaPublicKey(p, q, g, y); } catch (Throwable e) { throw new SshException(e); } }
public SshKeyPair generateDsaKeyPair(int bits) throws SshException { try { KeyPairGenerator keyGen = JCEProvider .getProviderForAlgorithm(JCE_DSA) == null ? KeyPairGenerator .getInstance(JCE_DSA) : KeyPairGenerator.getInstance( JCE_DSA, JCEProvider.getProviderForAlgorithm(JCE_DSA)); keyGen.initialize(bits); KeyPair keypair = keyGen.genKeyPair(); PrivateKey privateKey = keypair.getPrivate(); PublicKey publicKey = keypair.getPublic(); SshKeyPair pair = new SshKeyPair(); pair.setPrivateKey(new Ssh2DsaPrivateKey( (DSAPrivateKey) privateKey, (DSAPublicKey) publicKey)); pair.setPublicKey(new Ssh2DsaPublicKey((DSAPublicKey) publicKey)); return pair; } catch (java.security.NoSuchAlgorithmException e) { throw new SshException(e); } }
private void checkPrivateKey(DSAPrivateKey k2, PrivateKey sKey) { if (!k2.getX().equals(((DSAPrivateKey)sKey).getX())) { fail("private number not decoded properly"); } if (!k2.getParams().getG().equals(((DSAPrivateKey)sKey).getParams().getG())) { fail("private generator not decoded properly"); } if (!k2.getParams().getP().equals(((DSAPrivateKey)sKey).getParams().getP())) { fail("private p value not decoded properly"); } if (!k2.getParams().getQ().equals(((DSAPrivateKey)sKey).getParams().getQ())) { fail("private q value not decoded properly"); } }
/** * Use if SigType is known. * * @param pk JAVA key! */ public static SigningPrivateKey fromJavaKey(PrivateKey pk, SigType type) throws GeneralSecurityException { switch (type.getBaseAlgorithm()) { case DSA: return fromJavaKey((DSAPrivateKey) pk); case EC: return fromJavaKey((ECPrivateKey) pk, type); case EdDSA: return fromJavaKey((EdDSAPrivateKey) pk, type); case RSA: return fromJavaKey((RSAPrivateKey) pk, type); default: throw new IllegalArgumentException(); } }
/** * 生成密钥 * * @param seed * 种子 * @return 密钥对象 * @throws Exception */ public static Map<String, Object> initKey(String seed) throws Exception { KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM); // 初始化随机产生器 SecureRandom secureRandom = new SecureRandom(); secureRandom.setSeed(seed.getBytes()); keygen.initialize(KEY_SIZE, secureRandom); KeyPair keys = keygen.genKeyPair(); DSAPublicKey publicKey = (DSAPublicKey) keys.getPublic(); DSAPrivateKey privateKey = (DSAPrivateKey) keys.getPrivate(); Map<String, Object> map = new HashMap<String, Object>(2); map.put(PUBLIC_KEY, publicKey); map.put(PRIVATE_KEY, privateKey); return map; }
/** * 生成密钥 * * @param seed 种子 * @return 密钥对象 * @throws Exception */ public static Map<String, Object> initKey(String seed) throws Exception { KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM); // 初始化随机产生器 SecureRandom secureRandom = new SecureRandom(); secureRandom.setSeed(seed.getBytes()); keygen.initialize(KEY_SIZE, secureRandom); KeyPair keys = keygen.genKeyPair(); DSAPublicKey publicKey = (DSAPublicKey) keys.getPublic(); DSAPrivateKey privateKey = (DSAPrivateKey) keys.getPrivate(); Map<String, Object> map = new HashMap<String, Object>(2); map.put(PUBLIC_KEY, publicKey); map.put(PRIVATE_KEY, privateKey); return map; }
public void regenerateLocalPublicKey(KeyFactory factory, String fullUserId, DSAPrivateKey privKey) { String userId = Address.stripResource(fullUserId); BigInteger x = privKey.getX(); DSAParams params = privKey.getParams(); BigInteger y = params.getG().modPow(x, params.getP()); DSAPublicKeySpec keySpec = new DSAPublicKeySpec(y, params.getP(), params.getQ(), params.getG()); PublicKey pubKey; try { pubKey = factory.generatePublic(keySpec); } catch (InvalidKeySpecException e) { throw new RuntimeException(e); } storeLocalPublicKey(userId, pubKey); }
/** * * * @param bits */ public void generate(int bits) { try { // Initialize the generator KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(bits, ConfigurationLoader.getRND()); KeyPair pair = keyGen.generateKeyPair(); // Get the keys DSAPrivateKey prvKey = (DSAPrivateKey) pair.getPrivate(); DSAPublicKey pubKey = (DSAPublicKey) pair.getPublic(); // Set the private key (the public is automatically generated) setPrivateKey(new SshDssPrivateKey(prvKey)); } catch (NoSuchAlgorithmException nsae) { } }
public static GoogleAccountsService getGoogleAccountsService() throws Exception { final PublicKeyFactoryBean pubKeyFactoryBean = new PublicKeyFactoryBean(); pubKeyFactoryBean.setAlgorithm("DSA"); final PrivateKeyFactoryBean privKeyFactoryBean = new PrivateKeyFactoryBean(); privKeyFactoryBean.setAlgorithm("DSA"); final ClassPathResource pubKeyResource = new ClassPathResource("DSAPublicKey01.key"); final ClassPathResource privKeyResource = new ClassPathResource("DSAPrivateKey01.key"); pubKeyFactoryBean.setLocation(pubKeyResource); privKeyFactoryBean.setLocation(privKeyResource); pubKeyFactoryBean.afterPropertiesSet(); privKeyFactoryBean.afterPropertiesSet(); final DSAPrivateKey privateKey = (DSAPrivateKey) privKeyFactoryBean.getObject(); final DSAPublicKey publicKey = (DSAPublicKey) pubKeyFactoryBean.getObject(); final MockHttpServletRequest request = new MockHttpServletRequest(); final String samlRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<samlp:AuthnRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" " + "ID=\"5545454455\" Version=\"2.0\" IssueInstant=\"Value\" " + "ProtocolBinding=\"urn:oasis:names.tc:SAML:2.0:bindings:HTTP-Redirect\" " + "ProviderName=\"https://localhost:8443/myRutgers\" AssertionConsumerServiceURL=\"https://localhost:8443/myRutgers\"/>"; request.setParameter(SamlProtocolConstants.PARAMETER_SAML_REQUEST, encodeMessage(samlRequest)); request.setParameter(SamlProtocolConstants.PARAMETER_SAML_RELAY_STATE, "RelayStateAddedHere"); final RegisteredService regSvc = mock(RegisteredService.class); when(regSvc.getUsernameAttributeProvider()).thenReturn(new DefaultRegisteredServiceUsernameProvider()); final ServicesManager servicesManager = mock(ServicesManager.class); when(servicesManager.findServiceBy(any(Service.class))).thenReturn(regSvc); return GoogleAccountsService.createServiceFrom(request, privateKey, publicKey, servicesManager); }
public boolean equals( Object o) { if (!(o instanceof DSAPrivateKey)) { return false; } DSAPrivateKey other = (DSAPrivateKey)o; return this.getX().equals(other.getX()) && this.getParams().getG().equals(other.getParams().getG()) && this.getParams().getP().equals(other.getParams().getP()) && this.getParams().getQ().equals(other.getParams().getQ()); }
protected Key engineTranslateKey( Key key) throws InvalidKeyException { if (key instanceof DSAPublicKey) { return new BCDSAPublicKey((DSAPublicKey)key); } else if (key instanceof DSAPrivateKey) { return new BCDSAPrivateKey((DSAPrivateKey)key); } throw new InvalidKeyException("key type unknown"); }
static public AsymmetricKeyParameter generatePrivateKeyParameter( PrivateKey key) throws InvalidKeyException { if (key instanceof DSAPrivateKey) { DSAPrivateKey k = (DSAPrivateKey)key; return new DSAPrivateKeyParameters(k.getX(), new DSAParameters(k.getParams().getP(), k.getParams().getQ(), k.getParams().getG())); } throw new InvalidKeyException("can't identify DSA private key."); }
protected String getEncOID( PrivateKey key, String digestOID) { String encOID = null; if (key instanceof RSAPrivateKey || "RSA".equalsIgnoreCase(key.getAlgorithm())) { encOID = ENCRYPTION_RSA; } else if (key instanceof DSAPrivateKey || "DSA".equalsIgnoreCase(key.getAlgorithm())) { encOID = ENCRYPTION_DSA; if (!digestOID.equals(DIGEST_SHA1)) { throw new IllegalArgumentException("can't mix DSA with anything but SHA1"); } } else if ("ECDSA".equalsIgnoreCase(key.getAlgorithm()) || "EC".equalsIgnoreCase(key.getAlgorithm())) { encOID = (String)EC_ALGORITHMS.get(digestOID); if (encOID == null) { throw new IllegalArgumentException("can't mix ECDSA with anything but SHA family digests"); } } else if (key instanceof GOST3410PrivateKey || "GOST3410".equalsIgnoreCase(key.getAlgorithm())) { encOID = ENCRYPTION_GOST3410; } else if ("ECGOST3410".equalsIgnoreCase(key.getAlgorithm())) { encOID = ENCRYPTION_ECGOST3410; } return encOID; }
private String getSigAlgorithm( PrivateKey key, String digestOID) { String enc = null; if (key instanceof RSAPrivateKey || "RSA".equalsIgnoreCase(key.getAlgorithm())) { enc = "RSA"; } else if (key instanceof DSAPrivateKey || "DSA".equalsIgnoreCase(key.getAlgorithm())) { enc = "DSA"; } else if ("ECDSA".equalsIgnoreCase(key.getAlgorithm()) || "EC".equalsIgnoreCase(key.getAlgorithm())) { enc = "ECDSA"; } else if (key instanceof GOST3410PrivateKey || "GOST3410".equalsIgnoreCase(key.getAlgorithm())) { enc = "GOST3410"; } else if ("ECGOST3410".equalsIgnoreCase(key.getAlgorithm())) { enc = CMSSignedGenerator.ENCRYPTION_ECGOST3410; } return TSPUtil.getDigestAlgName(digestOID) + "with" + enc; }
public static GoogleAccountsService getGoogleAccountsService() throws Exception { final PublicKeyFactoryBean pubKeyFactoryBean = new PublicKeyFactoryBean(); pubKeyFactoryBean.setAlgorithm("DSA"); final PrivateKeyFactoryBean privKeyFactoryBean = new PrivateKeyFactoryBean(); privKeyFactoryBean.setAlgorithm("DSA"); final ClassPathResource pubKeyResource = new ClassPathResource("DSAPublicKey01.key"); final ClassPathResource privKeyResource = new ClassPathResource("DSAPrivateKey01.key"); pubKeyFactoryBean.setLocation(pubKeyResource); privKeyFactoryBean.setLocation(privKeyResource); pubKeyFactoryBean.afterPropertiesSet(); privKeyFactoryBean.afterPropertiesSet(); final DSAPrivateKey privateKey = (DSAPrivateKey) privKeyFactoryBean.getObject(); final DSAPublicKey publicKey = (DSAPublicKey) pubKeyFactoryBean.getObject(); final MockHttpServletRequest request = new MockHttpServletRequest(); final String SAMLRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<samlp:AuthnRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" " + "ID=\"5545454455\" Version=\"2.0\" IssueInstant=\"Value\" " + "ProtocolBinding=\"urn:oasis:names.tc:SAML:2.0:bindings:HTTP-Redirect\" " + "ProviderName=\"https://localhost:8443/myRutgers\" AssertionConsumerServiceURL=\"https://localhost:8443/myRutgers\"/>"; request.setParameter("SAMLRequest", encodeMessage(SAMLRequest)); return GoogleAccountsService.createServiceFrom(request, privateKey, publicKey, "username"); }
/** * Build Java DSA private key from base64 encoding. * * @param base64EncodedKey base64-encoded DSA private key * @return a native Java DSAPrivateKey * @throws KeyException thrown if there is an error constructing key */ public static DSAPrivateKey buildJavaDSAPrivateKey(String base64EncodedKey) throws KeyException { PrivateKey key = buildJavaPrivateKey(base64EncodedKey); if (! (key instanceof DSAPrivateKey)) { throw new KeyException("Generated key was not a DSAPrivateKey instance"); } return (DSAPrivateKey) key; }
public static BrowserIDKeyPair generateKeyPair(int keysize) throws NoSuchAlgorithmException { final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); keyPairGenerator.initialize(keysize); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); DSAPrivateKey privateKey = (DSAPrivateKey) keyPair.getPrivate(); DSAPublicKey publicKey = (DSAPublicKey) keyPair.getPublic(); return new BrowserIDKeyPair(new DSASigningPrivateKey(privateKey), new DSAVerifyingPublicKey(publicKey)); }
@SuppressWarnings("InsecureCryptoUsage") public void testKeyGeneration(int keysize) throws Exception { KeyPairGenerator generator = KeyPairGenerator.getInstance("DSA"); generator.initialize(keysize); KeyPair keyPair = generator.generateKeyPair(); DSAPrivateKey priv = (DSAPrivateKey) keyPair.getPrivate(); DSAParams params = priv.getParams(); assertEquals(keysize, params.getP().bitLength()); // The NIST standard does not fully specify the size of q that // must be used for a given key size. Hence there are differences. // For example if keysize = 2048, then OpenSSL uses 256 bit q's by default, // but the SUN provider uses 224 bits. Both are acceptable sizes. // The tests below simply asserts that the size of q does not decrease the // overall security of the DSA. int qsize = params.getQ().bitLength(); switch (keysize) { case 1024: assertTrue("Invalid qsize for 1024 bit key:" + qsize, qsize >= 160); break; case 2048: assertTrue("Invalid qsize for 2048 bit key:" + qsize, qsize >= 224); break; case 3072: assertTrue("Invalid qsize for 3072 bit key:" + qsize, qsize >= 256); break; default: fail("Invalid key size:" + keysize); } // Check the length of the private key. // For example GPG4Browsers or the KJUR library derived from it use // q.bitCount() instead of q.bitLength() to determine the size of the private key // and hence would generate keys that are much too small. assertTrue(priv.getX().bitLength() >= qsize - 32); }
/** * Checks whether CVE-2016-0695 has been fixed. Before the April 2016 security update, the SUN * provider had a serious flaw that leaked the private key with about 3-5 signatures. In * particular, "Sha1WithDSA" always generated 160 bit k's independently of q. Unfortunately, it is * easily possible to use 2048 and 3072 bit DSA keys together with SHA1WithDSA. All a user has to * do is to use the algorithm name "DSA" instead of "SHA256WithDSA" rsp. "SHA224WithDSA". * * <p>An algorithm to extract the key from the signatures has been described for example in the * paper <a href="http://www.hpl.hp.com/techreports/1999/HPL-1999-90.pdf">Lattice Attacks on * Digital Signature Schemes</a> by N.A. Howgrave-Graham, N.P. Smart. * * <p>This bug is the same as US-CERT: VU # 940388: GnuPG generated ElGamal signatures that leaked * the private key. */ @SlowTest(providers = {ProviderType.BOUNCY_CASTLE, ProviderType.SPONGY_CASTLE}) @SuppressWarnings("InsecureCryptoUsage") @Test public void testBiasSha1WithDSA() throws Exception { 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); KeyPairGenerator generator = java.security.KeyPairGenerator.getInstance("DSA"); generator.initialize(2048); KeyPair keyPair = generator.generateKeyPair(); DSAPrivateKey priv = (DSAPrivateKey) keyPair.getPrivate(); Signature signer = Signature.getInstance("DSA"); try { // Private key and selected algorithm by signer do not match. // Hence throwing an exception at this point would be the reasonable. signer.initSign(priv); signer.update(messageBytes); byte[] signature = signer.sign(); BigInteger q = priv.getParams().getQ(); BigInteger k = extractK(signature, h, priv, true); // Now check if k is heavily biased. int lengthDiff = q.bitLength() - k.bitLength(); if (lengthDiff > 32) { fail( "Severly biased DSA signature:" + " len(q)=" + q.bitLength() + " len(k)=" + k.bitLength()); } } catch (GeneralSecurityException ex) { // The key is invalid, hence getting here is reasonable. return; } }