java.security.PrivateKey Java Examples

The following examples show how to use java.security.PrivateKey. 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: SampleUtil.java    From aws-iot-device-sdk-java with Apache License 2.0 8 votes vote down vote up
private static PrivateKey loadPrivateKeyFromFile(final String filename, final String algorithm) {
    PrivateKey privateKey = null;

    File file = new File(filename);
    if (!file.exists()) {
        System.out.println("Private key file not found: " + filename);
        return null;
    }
    try (DataInputStream stream = new DataInputStream(new FileInputStream(file))) {
        privateKey = PrivateKeyReader.getPrivateKey(stream, algorithm);
    } catch (IOException | GeneralSecurityException e) {
        System.out.println("Failed to load private key from file " + filename);
    }

    return privateKey;
}
 
Example #2
Source File: RsaEncryptor.java    From spring-boot-vue-admin with Apache License 2.0 6 votes vote down vote up
/** 加载公私钥pem格式文件测试 */
@Test
public void test1() throws Exception {
  final PublicKey publicKey =
      this.rsaUtil.loadPublicKey(
          Base64.decodeBase64(
              "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANl43G/i7U86D2pWh6UQ7whrddH9QDqTBoZjbySk3sIS2W/AoZnCwJAhYYfQtY6qZ4p9oWwH9OQC7Z/8S3W6M58CAwEAAQ=="));
  final PrivateKey privateKey =
      this.rsaUtil.loadPrivateKey(
          Base64.decodeBase64(
              "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEA2Xjcb+LtTzoPalaHpRDvCGt10f1AOpMGhmNvJKTewhLZb8ChmcLAkCFhh9C1jqpnin2hbAf05ALtn/xLdboznwIDAQABAkEAhc3iO4kxH9UGVRQmY352xARyOqCKWz/I/PjDEpXKZTdWs1oqTM2lpYBlpnV/fJ3Sf2es6Sv6reLCLP7MZP1KGQIhAP0+wZ0c1YBVJvkkHHmhnGyaU1Bsb1alPY4A2sM97Q0lAiEA29Z7rVhw4Fgx201uhnwb0dqiuXfCZM1+fVDyTSg0XHMCIBZencGgE2fjna6yNuWzldquAx/+hBM2Q2qwvqIybScVAiEAlFhnnNHRWZIqEpJtwtJ8819V71GhG+SPNoEpAGfg7YECIHPReHdJdfBehhD1o63xH+gTZqliK4n6XvBhkcyWNYdS"));
  Assert.assertNotNull(publicKey);
  Assert.assertNotNull(privateKey);
  System.out.println("公钥:" + publicKey);
  System.out.println("私钥:" + privateKey);

  final String data = "zoctan";
  // 公钥加密
  final byte[] encrypted = this.rsaUtil.encrypt(data.getBytes());
  System.out.println("加密后:" + Base64.encodeBase64String(encrypted));

  // 私钥解密
  final byte[] decrypted = this.rsaUtil.decrypt(encrypted);
  System.out.println("解密后:" + new String(decrypted));
}
 
Example #3
Source File: SignatureDSA.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @inheritDoc
 */
protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
    throws XMLSignatureException {
    if (!(privateKey instanceof PrivateKey)) {
        String supplied = privateKey.getClass().getName();
        String needed = PrivateKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
    } catch (InvalidKeyException ex) {
        throw new XMLSignatureException("empty", ex);
    }
    size = ((DSAKey)privateKey).getParams().getQ().bitLength();
}
 
Example #4
Source File: VpnProfile.java    From SimpleOpenVpn-Android with Apache License 2.0 6 votes vote down vote up
private String processSignJellyBeans(PrivateKey privkey, byte[] data) {
    try {
        Method getKey = privkey.getClass().getSuperclass().getDeclaredMethod("getOpenSSLKey");
        getKey.setAccessible(true);

        // Real object type is OpenSSLKey
        Object opensslkey = getKey.invoke(privkey);
        getKey.setAccessible(false);
        Method getPkeyContext = opensslkey.getClass().getDeclaredMethod("getPkeyContext");

        // integer pointer to EVP_pkey
        getPkeyContext.setAccessible(true);
        int pkey = (Integer) getPkeyContext.invoke(opensslkey);
        getPkeyContext.setAccessible(false);

        // 112 with TLS 1.2 (172 back with 4.3), 36 with TLS 1.0
        byte[] signed_bytes = NativeUtils.rsasign(data, pkey);
        return Base64.encodeToString(signed_bytes, Base64.NO_WRAP);

    } catch (NoSuchMethodException | InvalidKeyException | InvocationTargetException | IllegalAccessException | IllegalArgumentException e) {
        VpnStatus.logError(R.string.error_rsa_sign, e.getClass().toString(), e.getLocalizedMessage());
        return null;
    }
}
 
Example #5
Source File: GenericWsSenderImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public Node sendCertificateSecured(String url, Document payload, X509Certificate certificate, PrivateKey privateKey, String soapAction) throws TechnicalConnectorException {
   GenericRequest request = new GenericRequest();
   request.setPayload(payload);
   request.setEndpoint(url);
   if (soapAction != null && soapAction.isEmpty()) {
      request.setSoapAction(soapAction);
   }

   request.setCertificateSecured(certificate, privateKey);
   request.setHandlerChain((new HandlerChain()).register(HandlerPosition.SECURITY, new CertificateCallback(certificate, privateKey)).register(HandlerPosition.SECURITY, new SoapActionHandler()));
   request.setDefaultHandlerChain();

   try {
      return this.send(request).asNode();
   } catch (SOAPException var8) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_WS, var8, new Object[]{var8.getMessage()});
   }
}
 
Example #6
Source File: SecurityTestUtils.java    From cava with Apache License 2.0 6 votes vote down vote up
static void configureJDKTrustStore(Path workDir, SelfSignedCertificate clientCert) throws Exception {
  KeyStore ks = KeyStore.getInstance("JKS");
  ks.load(null, null);

  KeyFactory kf = KeyFactory.getInstance("RSA");
  PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(readPemFile(new File(clientCert.privateKeyPath()).toPath()));
  PrivateKey clientPrivateKey = kf.generatePrivate(keysp);
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  Certificate certificate = cf.generateCertificate(
      new ByteArrayInputStream(Files.readAllBytes(new File(clientCert.certificatePath()).toPath())));
  ks.setCertificateEntry("clientCert", certificate);
  ks.setKeyEntry("client", clientPrivateKey, "changeit".toCharArray(), new Certificate[] {certificate});
  Path tempKeystore = Files.createTempFile(workDir, "keystore", ".jks");
  try (FileOutputStream output = new FileOutputStream(tempKeystore.toFile());) {
    ks.store(output, "changeit".toCharArray());
  }
  System.setProperty("javax.net.ssl.trustStore", tempKeystore.toString());
  System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
}
 
Example #7
Source File: DHKeyFactory.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a private key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the private key
 *
 * @return the private key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a private key.
 */
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
    throws InvalidKeySpecException
{
    try {
        if (keySpec instanceof DHPrivateKeySpec) {
            DHPrivateKeySpec dhPrivKeySpec = (DHPrivateKeySpec)keySpec;
            return new DHPrivateKey(dhPrivKeySpec.getX(),
                                    dhPrivKeySpec.getP(),
                                    dhPrivKeySpec.getG());

        } else if (keySpec instanceof PKCS8EncodedKeySpec) {
            return new DHPrivateKey
                (((PKCS8EncodedKeySpec)keySpec).getEncoded());

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification", e);
    }
}
 
Example #8
Source File: SignatureDSA.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @inheritDoc
 */
protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
    throws XMLSignatureException {
    if (!(privateKey instanceof PrivateKey)) {
        String supplied = privateKey.getClass().getName();
        String needed = PrivateKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
    } catch (InvalidKeyException ex) {
        throw new XMLSignatureException("empty", ex);
    }
    size = ((DSAKey)privateKey).getParams().getQ().bitLength();
}
 
Example #9
Source File: GoogleApiClientSignerTest.java    From oauth1-signer-java with MIT License 6 votes vote down vote up
@Test
public void testSign_ShouldAddOAuth1HeaderToPostRequest() throws Exception {

    // GIVEN
    PrivateKey signingKey = TestUtils.getTestSigningKey();
    String consumerKey = "Some key";
    HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
    HttpContent httpContent = new ByteArrayContent("application/json; charset=" + UTF8_CHARSET.name(), "{\"foo\":\"bår\"}".getBytes());
    HttpRequest request = requestFactory.buildPostRequest(new GenericUrl("https://api.mastercard.com/service"), httpContent);
    request.setRequestMethod("POST");

    // WHEN
    GoogleApiClientSigner instanceUnderTest = new GoogleApiClientSigner(consumerKey, signingKey);
    instanceUnderTest.sign(request);

    // THEN
    String authorizationHeaderValue = request.getHeaders().getAuthorization();
    Assert.assertNotNull(authorizationHeaderValue);
}
 
Example #10
Source File: GenericWsSenderImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public String sendCertificateSecured(String url, String payload, X509Certificate certificate, PrivateKey privateKey, String soapAction) throws TechnicalConnectorException {
   GenericRequest request = new GenericRequest();
   request.setPayload(payload);
   request.setEndpoint(url);
   if (soapAction != null && soapAction.isEmpty()) {
      request.setSoapAction(soapAction);
   }

   request.setHandlerChain((new HandlerChain()).register(HandlerPosition.SECURITY, new CertificateCallback(certificate, privateKey)).register(HandlerPosition.SECURITY, new SoapActionHandler()));
   request.setDefaultHandlerChain();

   try {
      return this.send(request).asString();
   } catch (SOAPException var8) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_WS, var8, new Object[]{var8.getMessage()});
   }
}
 
Example #11
Source File: RegAssertionBuilder.java    From UAF with Apache License 2.0 6 votes vote down vote up
private byte[] getSignature(byte[] dataForSigning) throws Exception {

		PublicKey pub = KeyCodec.getPubKey(Base64
				.decodeBase64(TestData.TEST_PUB_KEY));
		PrivateKey priv = KeyCodec.getPrivKey(Base64
				.decodeBase64(TestData.TEST_PRIV_KEY));

		logger.info(" : dataForSigning : "
				+ Base64.encodeBase64URLSafeString(dataForSigning));

		BigInteger[] signatureGen = NamedCurve.signAndFromatToRS(priv,
				dataForSigning);

		boolean verify = NamedCurve.verify(
				KeyCodec.getKeyAsRawBytes(TestData.TEST_PUB_KEY),
				dataForSigning,
				Asn1.decodeToBigIntegerArray(Asn1.getEncoded(signatureGen)));
		if (!verify) {
			throw new RuntimeException("Signatire match fail");
		}
		byte[] ret = Asn1.getEncoded(signatureGen);
		logger.info(" : signature : " + Base64.encodeBase64URLSafeString(ret));

		return ret;
	}
 
Example #12
Source File: DSAKeyFactory.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a private key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the private key
 *
 * @return the private key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a private key.
 */
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
throws InvalidKeySpecException {
    try {
        if (keySpec instanceof DSAPrivateKeySpec) {
            DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec)keySpec;
            return new DSAPrivateKey(dsaPrivKeySpec.getX(),
                                     dsaPrivKeySpec.getP(),
                                     dsaPrivKeySpec.getQ(),
                                     dsaPrivKeySpec.getG());

        } else if (keySpec instanceof PKCS8EncodedKeySpec) {
            return new DSAPrivateKey
                (((PKCS8EncodedKeySpec)keySpec).getEncoded());

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification: " + e.getMessage());
    }
}
 
Example #13
Source File: DefaultCertificateClient.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the private key of the specified  if it exists on the local
 * system.
 *
 * @return private key or Null if there is no data.
 */
@Override
public PrivateKey getPrivateKey() {
  if (privateKey != null) {
    return privateKey;
  }

  Path keyPath = securityConfig.getKeyLocation(component);
  if (OzoneSecurityUtil.checkIfFileExist(keyPath,
      securityConfig.getPrivateKeyFileName())) {
    try {
      privateKey = keyCodec.readPrivateKey();
    } catch (InvalidKeySpecException | NoSuchAlgorithmException
        | IOException e) {
      getLogger().error("Error while getting private key.", e);
    }
  }
  return privateKey;
}
 
Example #14
Source File: XMLTestWriter.java    From ECTester with MIT License 6 votes vote down vote up
private Element kgtElement(KeyGeneratorTestable kgt) {
    Element kgtElem = doc.createElement("key-pair-generator");
    kgtElem.setAttribute("algo", kgt.getKpg().getAlgorithm());

    Element keyPair = doc.createElement("key-pair");
    if (kgt.getKeyPair() != null) {
        PublicKey pkey = kgt.getKeyPair().getPublic();
        Element pubkey = pkeyElement(pkey);
        keyPair.appendChild(pubkey);

        PrivateKey skey = kgt.getKeyPair().getPrivate();
        Element privkey = skeyElement(skey);
        keyPair.appendChild(privkey);
    }

    kgtElem.appendChild(keyPair);
    return kgtElem;
}
 
Example #15
Source File: MetadataStoreLoadTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void storeAttrs() throws UnrecoverableEntryException,
        GeneralSecurityException, NoSuchAlgorithmException,
        KeyStoreException, IOException {
    KeyStore ksIn = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    KeyStore ksAttr = KeyStore
            .getInstance(Utils.KeyStoreType.pkcs12.name());
    ksAttr.load(null);
    Key key = ksIn.getKey(ALIAS, PASSWORD);
    Certificate cert = ksIn.getCertificate(ALIAS);
    Set<KeyStore.Entry.Attribute> attrs =
            new HashSet<>(Arrays.asList(ATTR_SET));
    KeyStore.Entry e = new KeyStore.PrivateKeyEntry((PrivateKey) key,
            new Certificate[]{cert}, attrs);
    ksAttr.setEntry(ALIAS, e, new KeyStore.PasswordProtection(
            KEY_PASSWORD));

    out.println("Attributes before store:");
    e.getAttributes().stream().forEach((attr) -> {
        out.println(attr.getName() + ", '" + attr.getValue() + "'");
    });
    Utils.saveKeyStore(ksAttr, WORKING_DIRECTORY + File.separator
            + KESTORE_NEW, PASSWORD);
}
 
Example #16
Source File: HTTPJwtAuthenticatorTest.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Test
public void testES512() throws Exception {

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
    keyGen.initialize(571);
    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();

    String jwsToken = Jwts.builder().setSubject("Leonard McCoy").signWith(SignatureAlgorithm.ES512, priv).compact();
    Settings settings = Settings.builder().put("signing_key", BaseEncoding.base64().encode(pub.getEncoded())).build();

    HTTPJwtAuthenticator jwtAuth = new HTTPJwtAuthenticator(settings, null);
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Authorization", "Bearer "+jwsToken);

    AuthCredentials creds = jwtAuth.extractCredentials(new FakeRestRequest(headers, new HashMap<String, String>()), null);
    Assert.assertNotNull(creds);
    Assert.assertEquals("Leonard McCoy", creds.getUsername());
    Assert.assertEquals(0, creds.getBackendRoles().size());
}
 
Example #17
Source File: MetadataEmptyTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void runTest() throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks
            .getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(
            (PrivateKey) key,
            new Certificate[]{cert});
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set "
                + "must be empty");
    }
    out.println("Test Passed");
}
 
Example #18
Source File: RSASignature.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
protected void engineInitSign(PrivateKey key) throws InvalidKeyException
{
    // This signature accepts only RSAPrivateKey
    if ((key instanceof sun.security.mscapi.RSAPrivateKey) == false) {
        throw new InvalidKeyException("Key type not supported");
    }
    privateKey = (sun.security.mscapi.RSAPrivateKey) key;

    // Check against the local and global values to make sure
    // the sizes are ok.  Round up to nearest byte.
    RSAKeyFactory.checkKeyLengths(((privateKey.length() + 7) & ~7),
        null, RSAKeyPairGenerator.KEY_SIZE_MIN,
        RSAKeyPairGenerator.KEY_SIZE_MAX);

    this.publicKey = null;
    resetDigest();
}
 
Example #19
Source File: SignatureECDSA.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/** @inheritDoc */
protected void engineInitSign(Key privateKey) throws XMLSignatureException {
    if (!(privateKey instanceof PrivateKey)) {
        String supplied = privateKey.getClass().getName();
        String needed = PrivateKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.signatureAlgorithm.initSign((PrivateKey) privateKey);
    } catch (InvalidKeyException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
 
Example #20
Source File: KeyPairGen.java    From heisenberg with Apache License 2.0 6 votes vote down vote up
public static String encrypt(byte[] keyBytes, String plainText) throws Exception {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory factory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = factory.generatePrivate(spec);
    Cipher cipher = Cipher.getInstance("RSA");
    try {
        cipher.init(1, privateKey);
    } catch (InvalidKeyException e) {
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
        RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rsaPrivateKey.getModulus(),
            rsaPrivateKey.getPrivateExponent());
        Key fakePublicKey = KeyFactory.getInstance("RSA").generatePublic(publicKeySpec);
        cipher = Cipher.getInstance("RSA");
        cipher.init(1, fakePublicKey);
    }

    byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
    return Base64.encodeBase64String(encryptedBytes);

}
 
Example #21
Source File: McElieceKobaraImaiCipherSpi.java    From ripple-lib-java with ISC License 6 votes vote down vote up
public int getKeySize(Key key)
    throws InvalidKeyException
{
    McElieceCCA2KeyParameters mcElieceCCA2KeyParameters;
    if (key instanceof PublicKey)
    {
        mcElieceCCA2KeyParameters = (McElieceCCA2KeyParameters)McElieceCCA2KeysToParams.generatePublicKeyParameter((PublicKey)key);
        return cipher.getKeySize(mcElieceCCA2KeyParameters);
    }
    else if (key instanceof PrivateKey)
    {
        mcElieceCCA2KeyParameters = (McElieceCCA2KeyParameters)McElieceCCA2KeysToParams.generatePrivateKeyParameter((PrivateKey)key);
        return cipher.getKeySize(mcElieceCCA2KeyParameters);
    }
    else
    {
        throw new InvalidKeyException();
    }


}
 
Example #22
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signRequest(Element requestElement, PrivateKey privateKey, Object keyInfoValue) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, KeyException {
   DOMSignContext domSignContext = new DOMSignContext(privateKey, requestElement, requestElement.getFirstChild());
   String requestId = requestElement.getAttribute("RequestID");
   requestElement.setIdAttribute("RequestID", true);
   List<Transform> transforms = new LinkedList();
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature", (TransformParameterSpec)null));
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null));
   Reference reference = xmlSignatureFactory.newReference("#" + requestId, xmlSignatureFactory.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", (DigestMethodParameterSpec)null), transforms, (String)null, (String)null);
   CanonicalizationMethod canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null);
   SignatureMethod signatureMethod = xmlSignatureFactory.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", (SignatureMethodParameterSpec)null);
   SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference));
   KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
   KeyInfo keyInfo = null;
   if (keyInfoValue instanceof PublicKey) {
      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newKeyValue((PublicKey)keyInfoValue)));
   } else {
      if (!(keyInfoValue instanceof X509Certificate)) {
         throw new IllegalArgumentException("Unsupported keyinfo type [" + keyInfoValue.getClass() + "]");
      }

      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newX509Data(Collections.singletonList(keyInfoValue))));
   }

   XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
   xmlSignature.sign(domSignContext);
}
 
Example #23
Source File: KeyPairUtilTest.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testValidKeyPairWithDifferentAlgorithmNames() throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException, CryptoException, InvalidKeySpecException {

	KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDSA", BC);
	keyPairGenerator.initialize(new ECGenParameterSpec("prime256v1"), SecureRandom.getInstance("SHA1PRNG"));
	KeyPair keyPair = keyPairGenerator.generateKeyPair();

	// private key has algorithm "ECDSA" (because it was generated by BC)
	PrivateKey privateKey = keyPair.getPrivate();

	// now convert public key to standard JCE object (so it has algorithm name "EC" instead of "ECDSA")
	PublicKey publicKey = KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(keyPair.getPublic().getEncoded()));

	assertTrue(KeyPairUtil.validKeyPair(privateKey, publicKey));
}
 
Example #24
Source File: AbstractConsultationServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
protected B obtainTimestamp(X509Certificate certificate, PrivateKey privateKey, A consultRequest) throws TechnicalConnectorException {
   if (certificate != null && privateKey != null) {
      GenericRequest request = ServiceFactory.getTSConsultService(certificate, privateKey);
      request.setPayload(consultRequest);

      try {
         return org.taktik.connector.technical.ws.ServiceFactory.getGenericWsSender().send(request).asObject(this.clazzB);
      } catch (SOAPException var6) {
         throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_WS, new Object[]{var6.getMessage(), var6});
      }
   } else {
      TechnicalConnectorExceptionValues errorValue = TechnicalConnectorExceptionValues.SECURITY_NO_CERTIFICATE;
      LOG.debug("\t## " + errorValue.getMessage());
      throw new TechnicalConnectorException(errorValue, (Throwable)null, new Object[0]);
   }
}
 
Example #25
Source File: DigestSignatureSpi.java    From ripple-lib-java with ISC License 5 votes vote down vote up
protected void engineInitSign(
    PrivateKey privateKey)
    throws InvalidKeyException
{
    if (!(privateKey instanceof RSAPrivateKey))
    {
        throw new InvalidKeyException("Supplied key (" + getType(privateKey) + ") is not a RSAPrivateKey instance");
    }

    CipherParameters param = RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)privateKey);

    digest.reset();

    cipher.init(true, param);
}
 
Example #26
Source File: MSExcelOOXMLSignUtil.java    From hadoopoffice with Apache License 2.0 5 votes vote down vote up
/** 
 * Signs the Excel OOXML file and writes it to the final outputstream
 * 
 * @param privateKey private Key for signing
 * @param x509List List of certificates for signing. First item must be the private key for signing.
 * @param password optional password for encryption, if used
 * @param hashAlgorithm hash algorithm to be used
 * 
 * @throws MarshalException 
 * @throws XMLSignatureException 
 * @throws IOException 
 * @throws FormatNotUnderstoodException 
 */
public void sign(Key privateKey, List<X509Certificate> x509List, String password, HashAlgorithm hashAlgorithm) throws XMLSignatureException, MarshalException, IOException, FormatNotUnderstoodException {
	if (this.tempSignFileOS!=null) { // close it we sign only a closed temporary file
		this.tempSignFileOS.close();
	}
	SignatureConfig sc = new SignatureConfig();
       sc.addSignatureFacet(new OOXMLSignatureFacet());
       sc.addSignatureFacet(new KeyInfoSignatureFacet());
       sc.addSignatureFacet(new XAdESSignatureFacet());
       sc.addSignatureFacet(new Office2010SignatureFacet());
	sc.setKey((PrivateKey)privateKey);
	sc.setSigningCertificateChain(x509List);
	sc.setDigestAlgo(hashAlgorithm);
	FileInputStream tempSignFileIS = null;
	try {
		
		InputStream tmpFileInputStream = new FileInputStream(this.tempSignFile);
		if (password==null) {
			this.signUnencryptedOpcPackage(tmpFileInputStream, sc);
		} else {
			this.signEncryptedPackage(tmpFileInputStream, sc, password);
		}
		
	} catch (InvalidFormatException | IOException e) {
		LOG.error(e);
	} finally {
		if (this.finalOutputStream!=null) {
			this.finalOutputStream.close();
		}
		if (tempSignFileIS!=null) {
			tempSignFileIS.close();
		}
	}
}
 
Example #27
Source File: KSPrivateKeyEntryTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void createParams(boolean diffCerts, boolean diffKeys) {
    byte[] encoded = {(byte)0, (byte)1, (byte)2, (byte)3};
    testChain = new Certificate[5];
    for (int i = 0; i < testChain.length; i++) {
        String s = (diffCerts ? Integer.toString(i) : "NEW");
        testChain[i] = new MyCertificate("MY_TEST_CERTIFICATE_"
                .concat(s), encoded);
    }
    testPrivateKey = (diffKeys ? (PrivateKey)new tmpPrivateKey() :
        (PrivateKey)new tmpPrivateKey(testChain[0].getPublicKey().getAlgorithm()));
}
 
Example #28
Source File: KeyStore.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Fetch a key from the store.
 *
 * @param path fully qualified path to the key
 * @return private key for decryption
 * @throws KeyNotFoundException if key is not found
 */
public PrivateKey getKeyOrThrow(String path) throws KeyNotFoundException {
  PrivateKey key = getKey(path);
  if (key == null) {
    throw new KeyNotFoundException("No such entry in this KeyStore: " + path);
  }
  return key;
}
 
Example #29
Source File: KeyManagementUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static PrivateKey loadPrivateKey(Message m, Properties props,
                                        X509Certificate inCert,
                                        KeyOperation keyOper) {
    KeyStore ks = loadPersistKeyStore(m, props);

    try {
        String alias = ks.getCertificateAlias(inCert);
        return loadPrivateKey(ks, m, props, keyOper, alias);

    } catch (Exception ex) {
        LOG.warning("Private key can not be loaded");
        throw new JoseException(ex);
    }
}
 
Example #30
Source File: RSAHelper.java    From EasyEE with MIT License 5 votes vote down vote up
/** 
 * 得到私钥 
 * @param key 密钥字符串(经过base64编码) 
 * @throws Exception 
 */  
public static PrivateKey getPrivateKey(String key) throws Exception {  
      byte[] keyBytes;  
      keyBytes = new Base64Encoder().decode(key);  
   
      PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);  
      KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
      PrivateKey privateKey = keyFactory.generatePrivate(keySpec);  
      return privateKey;  
}