java.security.interfaces.DSAPrivateKey Java Examples

The following examples show how to use java.security.interfaces.DSAPrivateKey. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OtrAndroidKeyManagerImpl.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
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);
            storePublicKey(userId, pubKey);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
 
Example #2
Source File: KeyStoreState.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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);
	}
}
 
Example #3
Source File: DViewPrivateKey.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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());

	jtaEncoded.setText(new BigInteger(1, privateKey.getEncoded()).toString(16).toUpperCase());
	jtaEncoded.setCaretPosition(0);

	if ((privateKey instanceof RSAPrivateKey) || (privateKey instanceof DSAPrivateKey)) {
		jbFields.setEnabled(true);
	} else {
		jbFields.setEnabled(false);
	}
}
 
Example #4
Source File: ToolDSA.java    From protools with Apache License 2.0 6 votes vote down vote up
/**
 * 生成密钥
 *
 * @return 密钥对象
 *
 * @throws Exception
 */
public static Map<String, Object> initKey() throws NoSuchAlgorithmException {
    // 初始化密钥对儿生成器
    KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM);

    // 实例化密钥对儿生成器
    keygen.initialize(KEY_SIZE, new SecureRandom());

    // 实例化密钥对儿
    KeyPair keys = keygen.genKeyPair();

    DSAPublicKey publicKey = (DSAPublicKey) keys.getPublic();

    DSAPrivateKey privateKey = (DSAPrivateKey) keys.getPrivate();

    // 封装密钥
    Map<String, Object> map = Maps.newHashMapWithExpectedSize(2);

    map.put(PUBLIC_KEY, publicKey);
    map.put(PRIVATE_KEY, privateKey);

    return map;
}
 
Example #5
Source File: ExportKeyPairPrivateKeyAction.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: Ssh2DsaPrivateKey.java    From j2ssh-maverick with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
	}

}
 
Example #7
Source File: DsaTest.java    From wycheproof with Apache License 2.0 6 votes vote down vote up
/** 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;
}
 
Example #8
Source File: DsaTest.java    From wycheproof with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example #9
Source File: JCEComponentManager.java    From j2ssh-maverick with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
		}
	}
 
Example #10
Source File: DSAUtil.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
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.");
}
 
Example #11
Source File: DSATest.java    From java_security with MIT License 5 votes vote down vote up
/**
 * 
 * @author timliu
 * 说明: 用java的jdk里面相关方法实现dsa的签名及签名验证
 */
public static void jdkDSA()
{
	try {
		// 1.初始化密钥
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
		keyPairGenerator.initialize(512);
		KeyPair keyPair = keyPairGenerator.generateKeyPair();
		DSAPublicKey dsaPublicKey = (DSAPublicKey)keyPair.getPublic();
		DSAPrivateKey dsaPrivateKey = (DSAPrivateKey)keyPair.getPrivate();
		
		// 2.进行签名
		PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(dsaPrivateKey.getEncoded());
		KeyFactory keyFactory = KeyFactory.getInstance("DSA");
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
		Signature signature = Signature.getInstance("SHA1withDSA");
		signature.initSign(privateKey);
		signature.update(src.getBytes());
		byte[] result = signature.sign();
		System.out.println("jdk dsa sign:" + Hex.encodeHexString(result) );
		
		// 3.验证签名
		X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(dsaPublicKey.getEncoded());
		keyFactory = KeyFactory.getInstance("DSA");
		PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
		signature = Signature.getInstance("SHA1withDSA");
		signature.initVerify(publicKey);
		signature.update(src.getBytes());
		boolean bool = signature.verify(result);
		System.out.println("jdk dsa verify:" + bool);
	} catch (Exception e) {
		System.out.println(e.toString());
	}
	
}
 
Example #12
Source File: Main.java    From keystore-decryptor with Apache License 2.0 5 votes vote down vote up
private static void showJcaPrivateKey(PrivateKey pk) throws Exception {
    if (pk instanceof RSAPrivateKey) {
        RSAPrivateKey rsaPrivKey = (RSAPrivateKey) pk;
        PemObject rsaPem = new PemObject("RSA PRIVATE KEY", rsaPrivKey.getEncoded());
        StringWriter sw = new StringWriter();
        PemWriter pemWriter = new PemWriter(sw);
        try {
            pemWriter.writeObject(rsaPem);
        } finally {
            pemWriter.close();
        }
        System.out.println(sw.toString());
    } else if (pk instanceof java.security.interfaces.ECPrivateKey) {
        java.security.interfaces.ECPrivateKey ecPrivKey = (java.security.interfaces.ECPrivateKey) pk;
        System.out.printf("EC S: %s... (%d)\n",
                ecPrivKey.getS().toString(16).substring(0, 32),
                ecPrivKey.getS().bitLength());
        if (ecPrivKey.getParams() instanceof ECNamedCurveSpec) {
            ECNamedCurveSpec namedCurveSpec = (ECNamedCurveSpec) ecPrivKey.getParams();
            System.out.println("curve name: " + namedCurveSpec.getName());
        } else {
            System.out.println("EC params: " + ecPrivKey.getParams());
        }
    } else if (pk instanceof DSAPrivateKey) {
        DSAPrivateKey dsaPrivKey = (DSAPrivateKey) pk;
        System.out.printf("DSA X: %s... (%d)\n",
                dsaPrivKey.getX().toString(16).substring(0, 32), dsaPrivKey.getX()
                        .bitLength());
        System.out.println("DSA params: " + dsaPrivKey.getParams());
    } else {
        System.out.println("Unknown private key type: " + pk.getClass().getName());
    }
}
 
Example #13
Source File: BaseTestSupport.java    From termd with Apache License 2.0 5 votes vote down vote up
public static void assertDSAPrivateKeyEquals(String message, DSAPrivateKey expected, DSAPrivateKey actual) {
    if (expected == actual) {
        return;
    }

    assertEquals(message + "[x]", expected.getX(), actual.getX());
    assertDSAParamsEquals(message + "[params]", expected.getParams(), actual.getParams());
}
 
Example #14
Source File: JDKDSAPrivateKey.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #15
Source File: KeyFactorySpi.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
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");
}
 
Example #16
Source File: KeyTestUtilTest.java    From httpsig-java with The Unlicense 5 votes vote down vote up
@Test
public void testGetPrivateKeyAsKeyPair() {
    KeyPair b1024_dsa = KeyTestUtil.getPrivateKeyAsKeyPair("b1024", "id_dsa", null);
    assertNotNull("b1024_dsa should not be null", b1024_dsa);
    assertTrue("b1024_dsa should have a DSAPublicKey", b1024_dsa.getPublic() instanceof DSAPublicKey);
    assertTrue("b1024_dsa should have a DSAPrivateKey", b1024_dsa.getPrivate() instanceof DSAPrivateKey);

    KeyPair b1024_rsa = KeyTestUtil.getPrivateKeyAsKeyPair("b1024", "id_rsa", null);
    assertNotNull("b1024_rsa should not be null", b1024_rsa);
    assertTrue("b1024_rsa should have a RSAPublicKey", b1024_rsa.getPublic() instanceof RSAPublicKey);
    assertTrue("b1024_rsa should have a RSAPrivateKey", b1024_rsa.getPrivate() instanceof RSAPrivateKey);

    KeyPair b2048_rsa = KeyTestUtil.getPrivateKeyAsKeyPair("b2048", "id_rsa", null);
    assertNotNull("b2048_rsa should not be null", b2048_rsa);
    assertTrue("b2048_rsa should have a RSAPublicKey", b2048_rsa.getPublic() instanceof RSAPublicKey);
    assertTrue("b2048_rsa should have a RSAPrivateKey", b2048_rsa.getPrivate() instanceof RSAPrivateKey);

    KeyPair b4096_rsa = KeyTestUtil.getPrivateKeyAsKeyPair("b4096", "id_rsa", null);
    assertNotNull("b4096_rsa should not be null", b4096_rsa);
    assertTrue("b4096_rsa should have a RSAPublicKey", b4096_rsa.getPublic() instanceof RSAPublicKey);
    assertTrue("b4096_rsa should have a RSAPrivateKey", b4096_rsa.getPrivate() instanceof RSAPrivateKey);

    KeyPair withpass_dsa = KeyTestUtil.getPrivateKeyAsKeyPair("withpass", "id_dsa", "dummydummy");
    assertNotNull("withpass_dsa should not be null", withpass_dsa);
    assertTrue("withpass_dsa should have a DSAPublicKey", withpass_dsa.getPublic() instanceof DSAPublicKey);
    assertTrue("withpass_dsa should have a DSAPrivateKey", withpass_dsa.getPrivate() instanceof DSAPrivateKey);

    KeyPair withpass_rsa = KeyTestUtil.getPrivateKeyAsKeyPair("withpass", "id_rsa", "dummydummy");
    assertNotNull("withpass_rsa should not be null", withpass_rsa);
    assertTrue("withpass_rsa should have a RSAPublicKey", withpass_rsa.getPublic() instanceof RSAPublicKey);
    assertTrue("withpass_rsa should have a RSAPrivateKey", withpass_rsa.getPrivate() instanceof RSAPrivateKey);
}
 
Example #17
Source File: BCDSAPrivateKey.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #18
Source File: AndroidKeyStore.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Return the type of a given PrivateKey object. This is an integer
 * that maps to one of the values defined by org.chromium.net.PrivateKeyType,
 * which is itself auto-generated from net/android/private_key_type_list.h
 * @param privateKey The PrivateKey handle
 * @return key type, or PrivateKeyType.INVALID if unknown.
 */
@CalledByNative
public static int getPrivateKeyType(PrivateKey privateKey) {
    if (privateKey instanceof RSAPrivateKey)
        return PrivateKeyType.RSA;
    if (privateKey instanceof DSAPrivateKey)
        return PrivateKeyType.DSA;
    if (privateKey instanceof ECPrivateKey)
        return PrivateKeyType.ECDSA;
    else
        return PrivateKeyType.INVALID;
}
 
Example #19
Source File: AndroidKeyStore.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Return the type of a given PrivateKey object. This is an integer
 * that maps to one of the values defined by org.chromium.net.PrivateKeyType,
 * which is itself auto-generated from net/android/private_key_type_list.h
 * @param privateKey The PrivateKey handle
 * @return key type, or PrivateKeyType.INVALID if unknown.
 */
@CalledByNative
public static int getPrivateKeyType(PrivateKey privateKey) {
    if (privateKey instanceof RSAPrivateKey)
        return PrivateKeyType.RSA;
    if (privateKey instanceof DSAPrivateKey)
        return PrivateKeyType.DSA;
    if (privateKey instanceof ECPrivateKey)
        return PrivateKeyType.ECDSA;
    else
        return PrivateKeyType.INVALID;
}
 
Example #20
Source File: JDKDSAPrivateKey.java    From ripple-lib-java with ISC License 5 votes vote down vote up
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());
}
 
Example #21
Source File: KeyFactorySpi.java    From ripple-lib-java with ISC License 5 votes vote down vote up
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");
}
 
Example #22
Source File: DSAUtil.java    From ripple-lib-java with ISC License 5 votes vote down vote up
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.");
}
 
Example #23
Source File: BCDSAPrivateKey.java    From ripple-lib-java with ISC License 5 votes vote down vote up
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());
}
 
Example #24
Source File: BaseTestSupport.java    From termd with Apache License 2.0 5 votes vote down vote up
public static void assertDSAPrivateKeyEquals(String message, DSAPrivateKey expected, DSAPrivateKey actual) {
    if (expected == actual) {
        return;
    }

    assertEquals(message + "[x]", expected.getX(), actual.getX());
    assertDSAParamsEquals(message + "[params]", expected.getParams(), actual.getParams());
}
 
Example #25
Source File: DsaTest.java    From wycheproof with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #26
Source File: GoogleAccountsServiceTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
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);
}
 
Example #27
Source File: GoogleAccountsServiceTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
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");
}
 
Example #28
Source File: SecurityHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #29
Source File: DSAUtil.java    From BiglyBT with GNU General Public License v2.0 5 votes vote down vote up
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.");
}
 
Example #30
Source File: DSAUtil.java    From TorrentEngine with GNU General Public License v3.0 5 votes vote down vote up
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.");
}