Java Code Examples for java.security.PrivateKey

The following examples show how to use java.security.PrivateKey. These examples are extracted from open source projects. 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 Project: aws-iot-device-sdk-java   Source File: SampleUtil.java    License: 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
/**
 * @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 3
Source Project: cava   Source File: SecurityTestUtils.java    License: 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 4
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 5
Source Project: SimpleOpenVpn-Android   Source File: VpnProfile.java    License: 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 6
Source Project: jdk8u-dev-jdk   Source File: DHKeyFactory.java    License: 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 7
Source Project: jdk8u-jdk   Source File: SignatureDSA.java    License: 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 8
Source Project: oauth1-signer-java   Source File: GoogleApiClientSignerTest.java    License: 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 9
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 10
Source Project: UAF   Source File: RegAssertionBuilder.java    License: 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 11
Source Project: jdk8u-jdk   Source File: DSAKeyFactory.java    License: 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 12
Source Project: hadoop-ozone   Source File: DefaultCertificateClient.java    License: 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 13
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 14
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 15
Source Project: ECTester   Source File: XMLTestWriter.java    License: 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 16
@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 17
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 18
Source Project: ripple-lib-java   Source File: McElieceKobaraImaiCipherSpi.java    License: 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 19
Source Project: heisenberg   Source File: KeyPairGen.java    License: 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 20
/** @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 21
Source Project: jdk8u-jdk   Source File: RSASignature.java    License: 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 22
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 23
@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 24
Source Project: spring-boot-vue-admin   Source File: RsaEncryptor.java    License: 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 25
Source Project: ripple-lib-java   Source File: DigestSignatureSpi.java    License: 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
/**
 * Do action.
 */
@Override
protected void doAction() {
	try {
		KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
		KeyStoreState currentState = history.getCurrentState();

		String alias = kseFrame.getSelectedEntryAlias();

		Password password = getEntryPassword(alias, currentState);

		if (password == null) {
			return;
		}

		KeyStore keyStore = currentState.getKeyStore();

		PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());

		DExportPrivateKeyType dExportPrivateKeyType = new DExportPrivateKeyType(frame);
		dExportPrivateKeyType.setLocationRelativeTo(frame);
		dExportPrivateKeyType.setVisible(true);

		if (!dExportPrivateKeyType.exportTypeSelected()) {
			return;
		}

		if (dExportPrivateKeyType.exportPkcs8()) {
			exportAsPkcs8(privateKey, alias);
		} else if (dExportPrivateKeyType.exportPvk()) {
			exportAsPvk(privateKey, alias);
		} else {
			exportAsOpenSsl(privateKey, alias);
		}
	} catch (Exception ex) {
		DError.displayError(frame, ex);
	}
}
 
Example 27
Source Project: RipplePower   Source File: DigestSignatureSpi.java    License: Apache License 2.0 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 28
Source Project: RipplePower   Source File: X509V3CertificateGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * generate an X509 certificate, based on the current issuer and subject,
 * using the passed in provider for the signing.
 */
public X509Certificate generate(
    PrivateKey      key,
    String          provider)
    throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException
{
    return generate(key, provider, null);
}
 
Example 29
Source Project: java-license-manager   Source File: KeyFileUtilities.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Encrypts and writes the private key to this file.
 *
 * @param privateKey The private key
 * @param file The file
 * @param passphrase The passphrase with which to protect the key
 *
 * @throws IOException if writing fails.
 */
public static void writeEncryptedPrivateKey(
    final PrivateKey privateKey,
    final File file,
    final char[] passphrase
)
    throws IOException
{

    FileUtils.writeByteArrayToFile(file, KeyFileUtilities.writeEncryptedPrivateKey(privateKey, passphrase));
}
 
Example 30
Source Project: j2objc   Source File: KSPrivateKeyEntryTest.java    License: 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()));
}