Java Code Examples for

The following examples show how to use 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: DeviceConnect-Android   Author: DeviceConnect   File:    License: MIT License 7 votes vote down vote up
private X509Certificate generateX509V3Certificate(final KeyPair keyPair,
                                                  final X500Principal subject,
                                                  final X500Principal issuer,
                                                  final Date notBefore,
                                                  final Date notAfter,
                                                  final BigInteger serialNumber,
                                                  final GeneralNames generalNames,
                                                  final boolean isCA) throws GeneralSecurityException {
    X509V3CertificateGenerator generator = new X509V3CertificateGenerator();
    generator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isCA));
    generator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(160));
    generator.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
    if (generalNames != null) {
        generator.addExtension(X509Extensions.SubjectAlternativeName, false, generalNames);
    return generator.generateX509Certificate(keyPair.getPrivate(), SecurityUtil.getSecurityProvider());
Example #2
Source Project: cloudbreak   Author: hortonworks   File:    License: Apache License 2.0 6 votes vote down vote up
public static GoogleCredential buildCredential(CloudCredential gcpCredential, HttpTransport httpTransport) throws IOException, GeneralSecurityException {
    String credentialJson = getServiceAccountCredentialJson(gcpCredential);
    if (isNotEmpty(credentialJson)) {
        return GoogleCredential.fromStream(new ByteArrayInputStream(Base64.decodeBase64(credentialJson)), httpTransport, JSON_FACTORY)
    } else {
        try {
            PrivateKey pk = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(),
                    new ByteArrayInputStream(Base64.decodeBase64(getServiceAccountPrivateKey(gcpCredential))), "notasecret", "privatekey", "notasecret");
            return new GoogleCredential.Builder().setTransport(httpTransport)
        } catch (IOException e) {
            throw new CredentialVerificationException("Can not read private key", e);
Example #3
Source Project: Encryptor4j   Author: martinwithaar   File:    License: MIT License 6 votes vote down vote up
 * <p>Tests Diffie-Hellman key exchange.</p>
 * <p>Use at least a <code>p</code> of 2048 bits. Better pre-determined values for <code>p</code> can be found at the link below.</p>
 * @see
 * @throws GeneralSecurityException
@Test public void testDH() throws GeneralSecurityException {

	// Create primes p & g
	// Tip: You don't need to regenerate p; Use a fixed value in your application
	int bits = 2048;
    BigInteger p = BigInteger.probablePrime(bits, new SecureRandom());
    BigInteger g = new BigInteger("2");

	// Create two peers
	KeyAgreementPeer peerA = new DHPeer(p, g);
	KeyAgreementPeer peerB = new DHPeer(p, g);

	// Exchange public keys and compute shared secret
	byte[] sharedSecretA = peerA.computeSharedSecret(peerB.getPublicKey());
	byte[] sharedSecretB = peerB.computeSharedSecret(peerA.getPublicKey());

	assertArrayEquals(sharedSecretA, sharedSecretB);
Example #4
Source Project: aws-dynamodb-encryption-java   Author: aws   File:    License: Apache License 2.0 6 votes vote down vote up
public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) {
    CurrentMaterials materials = currMaterials.get();
    if (context.getMaterialDescription().entrySet().containsAll(description.entrySet())) {
        if (materials.encryptionEntry instanceof SecretKeyEntry) {
            return materials.symRawMaterials;
        } else {
            try {
                return makeAsymMaterials(materials, context.getMaterialDescription());
            } catch (GeneralSecurityException ex) {
                throw new DynamoDBMappingException("Unable to decrypt envelope key", ex);
    } else {
        return null;
Example #5
Source Project: openjdk-8   Author: bpupadhyaya   File:    License: GNU General Public License v2.0 6 votes vote down vote up
private void buildForward(List<List<Vertex>> adjacencyList,
                          LinkedList<X509Certificate> certPathList,
                          boolean searchAllCertStores)
    throws GeneralSecurityException, IOException
    if (debug != null) {

    /* Initialize current state */
    ForwardState currentState = new ForwardState();

    /* Initialize adjacency list */
    adjacencyList.add(new LinkedList<Vertex>());

    currentState.untrustedChecker = new UntrustedChecker();

    depthFirstSearchForward(buildParams.targetSubject(), currentState,
                            new ForwardBuilder(buildParams,
                            adjacencyList, certPathList);
Example #6
Source Project: capillary   Author: google   File:    License: Apache License 2.0 6 votes vote down vote up
public void testMissingKey()
    throws NoSuchKeyException, GeneralSecurityException, AuthModeUnavailableException {
  when(keyManager.getDecrypter(anyString(), anyInt(), anyBoolean()))
      .thenThrow(new NoSuchKeyException("no such key"));

  byte[] ciphertextBytes =;

  // New key pair generated.
  when(keyManager.generateKeyPair(anyInt(), anyBoolean())).thenReturn(true);
  decrypterManager.decrypt(ciphertextBytes, handler, extra);
      ciphertextBuilder.getIsAuthKey(), PUBLIC_KEY.getBytes(), ciphertextBytes, extra);

  // New key pair not generated.
  when(keyManager.generateKeyPair(anyInt(), anyBoolean())).thenReturn(false);
  decrypterManager.decrypt(ciphertextBytes, handler, extra);
  verify(handler).error(CapillaryHandlerErrorCode.STALE_CIPHERTEXT, ciphertextBytes, extra);

  // Key pair generation failed.
  when(keyManager.generateKeyPair(anyInt(), anyBoolean()))
      .thenThrow(new GeneralSecurityException("unknown exception"));
  decrypterManager.decrypt(ciphertextBytes, handler, extra);
  verify(handler).error(CapillaryHandlerErrorCode.UNKNOWN_ERROR, ciphertextBytes, extra);
Example #7
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File:    License: Apache License 2.0 6 votes vote down vote up
public void testConfigTurnOn() throws GeneralSecurityException, IOException, JSONException {
  int maxTemp = 11;
  JSONObject data = new JSONObject();

  // Set up
  CloudiotPubsubExampleServer.createRegistry(CLOUD_REGION, PROJECT_ID, REGISTRY_ID, TOPIC_ID);
  CloudiotPubsubExampleServer.createDevice(PROJECT_ID, CLOUD_REGION, REGISTRY_ID, DEVICE_ID);

  data.put("temperature", maxTemp);
  CloudiotPubsubExampleServer server = new CloudiotPubsubExampleServer();
  server.updateDeviceConfig(PROJECT_ID, CLOUD_REGION, REGISTRY_ID, DEVICE_ID, data);
  String got = bout.toString();

  // Clean up
  CloudiotPubsubExampleServer.deleteDevice(DEVICE_ID, PROJECT_ID, CLOUD_REGION, REGISTRY_ID);
  CloudiotPubsubExampleServer.deleteRegistry(CLOUD_REGION, PROJECT_ID, REGISTRY_ID);
Example #8
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File:    License: GNU General Public License v2.0 6 votes vote down vote up
private void checkAttrs() throws UnrecoverableEntryException,
        GeneralSecurityException, NoSuchAlgorithmException,
        KeyStoreException, IOException {
    KeyStore ks = Utils.loadKeyStore(WORKING_DIRECTORY
            + File.separator
            + KESTORE_NEW, Utils.KeyStoreType.pkcs12, PASSWORD);
    KeyStore.Entry keyStoreEntry = ks.getEntry(ALIAS,
            new KeyStore.PasswordProtection(KEY_PASSWORD));
    out.println("Attributes after store:");
    //print attribute values
    keyStoreEntry.getAttributes().stream().forEach((attr) -> {
        out.println(attr.getName() + ", '" + attr.getValue() + "'");
    }); -> {
        if (!keyStoreEntry.getAttributes().contains(attr)) {
            throw new RuntimeException("Entry doesn't contain attribute: ("
                    + attr.getName() + ", '" + attr.getValue() + "')");
Example #9
Source Project: lams   Author: lamsfoundation   File:    License: GNU General Public License v2.0 6 votes vote down vote up
 * Get the Keystore given the URL to the keystore
 * @param keyStoreType or null for default
 * @param url
 * @param storePass
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
public static KeyStore getKeyStore(String keyStoreType, URL url, char[] storePass) throws GeneralSecurityException, IOException
   if (url == null)
      throw PicketBoxMessages.MESSAGES.invalidNullArgument("url");

   InputStream is = null;
      is = url.openStream();
      return getKeyStore(keyStoreType, is, storePass);
Example #10
Source Project: axelor-open-suite   Author: axelor   File:    License: GNU Affero General Public License v3.0 6 votes vote down vote up
 * Returns the digest value of a given public key.
 * <p>In Version “H003” of the EBICS protocol the ES of the financial:
 * <p>The SHA-256 hash values of the financial institution's public keys for X002 and E002 are
 * composed by concatenating the exponent with a blank character and the modulus in hexadecimal
 * representation (using lower case letters) without leading zero (as to the hexadecimal
 * representation). The resulting string has to be converted into a byte array based on US ASCII
 * code.
 * @param publicKey the public key
 * @return the digest value
 * @throws EbicsException
public static byte[] getKeyDigest(RSAPublicKey publicKey) throws AxelorException {
  String modulus;
  String exponent;
  String hash;
  byte[] digest;

  exponent = Hex.encodeHexString(publicKey.getPublicExponent().toByteArray());
  modulus = Hex.encodeHexString(removeFirstByte(publicKey.getModulus().toByteArray()));
  hash = exponent + " " + modulus;

  if (hash.charAt(0) == '0') {
    hash = hash.substring(1);

  try {
    digest = MessageDigest.getInstance("SHA-256", "BC").digest(hash.getBytes("US-ASCII"));
  } catch (GeneralSecurityException | UnsupportedEncodingException e) {
    throw new AxelorException(
        e.getCause(), TraceBackRepository.CATEGORY_CONFIGURATION_ERROR, e.getMessage());

  return new String(Hex.encodeHex(digest, false)).getBytes();
Example #11
Source Project: nifi   Author: apache   File:    License: Apache License 2.0 5 votes vote down vote up
public TlsClientManager(TlsClientConfig tlsClientConfig, PasswordUtil passwordUtil, InputStreamFactory inputStreamFactory) throws GeneralSecurityException, IOException {
    super(tlsClientConfig, passwordUtil, inputStreamFactory);
    this.trustStore = loadKeystore(tlsClientConfig.getTrustStore(), tlsClientConfig.getTrustStoreType(), tlsClientConfig.getTrustStorePassword());
    this.tlsClientConfig = tlsClientConfig;
    this.configurationWriters = new ArrayList<>();
    this.certificateAliases = new HashSet<>();
Example #12
Source Project: grpc-java   Author: grpc   File:    License: Apache License 2.0 5 votes vote down vote up
public void setup() throws Exception {
  ChannelHandler uncaughtExceptionHandler =
      new ChannelDuplexHandler() {
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
          caughtException = cause;
          super.exceptionCaught(ctx, cause);

  TsiHandshakerFactory handshakerFactory =
      new DelegatingTsiHandshakerFactory(FakeTsiHandshaker.clientHandshakerFactory()) {
        public TsiHandshaker newHandshaker(String authority) {
          return new DelegatingTsiHandshaker(super.newHandshaker(authority)) {
            public TsiPeer extractPeer() throws GeneralSecurityException {
              return mockedTsiPeer;

            public Object extractPeerObject() throws GeneralSecurityException {
              return mockedAltsContext;
  ManagedChannel fakeChannel = NettyChannelBuilder.forTarget("localhost:8080").build();
  ObjectPool<Channel> fakeChannelPool = new FixedObjectPool<Channel>(fakeChannel);
  LazyChannel lazyFakeChannel = new LazyChannel(fakeChannelPool);
  ChannelHandler altsServerHandler = new ServerAltsProtocolNegotiator(
      handshakerFactory, lazyFakeChannel)
  // On real server, WBAEH fires default ProtocolNegotiationEvent. KickNH provides this behavior.
  ChannelHandler handler = new KickNegotiationHandler(altsServerHandler);
  channel = new EmbeddedChannel(uncaughtExceptionHandler, handler);
Example #13
Source Project: Bytecoder   Author: mirkosertic   File:    License: Apache License 2.0 5 votes vote down vote up
public SSLWriteCipher createCipher(SSLCipher sslCipher,
        Authenticator authenticator,
        ProtocolVersion protocolVersion, String algorithm,
        Key key, AlgorithmParameterSpec params,
        SecureRandom random) throws GeneralSecurityException {
    return new NullWriteCipher(authenticator, protocolVersion);
Example #14
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File:    License: Apache License 2.0 5 votes vote down vote up
public void verifyAsymmetricRsa() throws IOException, GeneralSecurityException {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "your-project-id";
  String locationId = "us-east1";
  String keyRingId = "my-key-ring";
  String keyId = "my-key";
  String keyVersionId = "123";
  String message = "my message";
  byte[] signature = null;
  verifyAsymmetricRsa(projectId, locationId, keyRingId, keyId, keyVersionId, message, signature);
Example #15
Source Project: jrpip   Author: goldmansachs   File:    License: Apache License 2.0 5 votes vote down vote up
public AuthGenerator createAuthGenerator()
    if (this.token != null)
            return new AuthGenerator(token);
        catch (GeneralSecurityException e)
            throw new RuntimeException("Never happens", e);
    return null;
Example #16
Source Project: chvote-1-0   Author: republique-et-canton-de-geneve   File:    License: GNU Affero General Public License v3.0 5 votes vote down vote up
 * @param input an byte array to encrypt
 * @return the concatenation of the IV followed by the cipher text
 * @see #decrypt(byte[]) the reverse operation
public static byte[] encrypt(byte[] input) {
    try {
        Cipher cipher = config.getCipher();
        SecretKey secretKey = config.getSecretKey();
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, SecureRandomFactory.createPRNG()); // init generates the IV
        byte[] iv = cipher.getIV();
        byte[] cipherText = cipher.doFinal(input);
        return Bytes.concat(iv, cipherText);
    } catch (GeneralSecurityException e) {
        throw new CryptoOperationRuntimeException(e);
Example #17
Source Project: azure-keyvault-java   Author: Azure   File:    License: MIT License 5 votes vote down vote up
 * Get the RSA public key value.
 * @param provider
 *            the Java security provider.
 * @return the RSA public key value
private PublicKey getRSAPublicKey(Provider provider) {

    try {
        RSAPublicKeySpec publicKeySpec = getRSAPublicKeySpec();
        KeyFactory factory = provider != null ? KeyFactory.getInstance("RSA", provider)
                : KeyFactory.getInstance("RSA");

        return factory.generatePublic(publicKeySpec);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
Example #18
Source Project: vjtools   Author: DarLiner   File:    License: Apache License 2.0 5 votes vote down vote up
 * 使用HMAC-SHA1进行消息签名, 返回字节数组,长度为20字节.
 * @param input 原始输入字符数组
 * @param key HMAC-SHA1密钥
public static byte[] hmacSha1(byte[] input, byte[] key) {
	try {
		SecretKey secretKey = new SecretKeySpec(key, HMACSHA1_ALG);
		Mac mac = Mac.getInstance(HMACSHA1_ALG);
		return mac.doFinal(input);
	} catch (GeneralSecurityException e) {
		throw ExceptionUtil.unchecked(e);
Example #19
Source Project: hono   Author: eclipse   File:    License: Eclipse Public License 2.0 5 votes vote down vote up
 * {@inheritDoc}
public Future<Void> validate(final List<X509Certificate> chain, final Set<TrustAnchor> trustAnchors) {


    if (chain.isEmpty()) {
        throw new IllegalArgumentException("certificate chain must not be empty");
    } else if (trustAnchors.isEmpty()) {
        throw new IllegalArgumentException("trust anchor list must not be empty");

    final Promise<Void> result = Promise.promise();

    try {
        final PKIXParameters params = new PKIXParameters(trustAnchors);
        // TODO do we need to check for revocation?
        final CertificateFactory factory = CertificateFactory.getInstance("X.509");
        final CertPath path = factory.generateCertPath(chain);
        final CertPathValidator validator = CertPathValidator.getInstance("PKIX");
        validator.validate(path, params);
        LOG.debug("validation of device certificate [subject DN: {}] succeeded",
    } catch (GeneralSecurityException e) {
        LOG.debug("validation of device certificate [subject DN: {}] failed",
                chain.get(0).getSubjectX500Principal().getName(), e);
        if (e instanceof CertificateException) {
        } else {
   CertificateException("validation of device certificate failed", e));
    return result.future();
Example #20
Source Project: openjsse   Author: openjsse   File:    License: GNU General Public License v2.0 5 votes vote down vote up
static final SSLReadCipher nullTlsReadCipher() {
    try {
        return B_NULL.createReadCipher(
                ProtocolVersion.NONE, null, null, null);
    } catch (GeneralSecurityException gse) {
        // unlikely
        throw new RuntimeException("Cannot create NULL SSLCipher", gse);
Example #21
Source Project: ha-bridge   Author: bwssytems   File:    License: Apache License 2.0 5 votes vote down vote up
static String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey key = keyFactory.generateSecret(new PBEKeySpec(habridgeKey));
    Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
    pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
    return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
Example #22
Source Project: cloudbreak   Author: hortonworks   File:    License: Apache License 2.0 5 votes vote down vote up
private TrustManagerFactory createTrustManagerFactory(KeyStoreConfiguration keyStoreConfiguration) throws GeneralSecurityException, IOException {
    KeyStore trustStore = KeyStore.getInstance(StringUtils
            .hasText(keyStoreConfiguration.getStoreType()) ? keyStoreConfiguration.getStoreType() : KeyStore.getDefaultType());

    loadKeyStore(keyStoreConfiguration, trustStore);

    TrustManagerFactory trustManagerFactory = TrustManagerFactory

    return trustManagerFactory;
Example #23
Source Project: samples-android   Author: okta   File:    License: Apache License 2.0 5 votes vote down vote up
public Token createToken(Uri uri) throws IllegalArgumentException, GeneralSecurityException {
    String name = "";
    String issuer = "Not Set";
    if (uri.getPath() == null) {
        throw new IllegalArgumentException("Missed name or issuer");
    String[] nameAndIssuer = uri.getPath().split(":");
    if (nameAndIssuer.length == 2) {
        issuer = nameAndIssuer[0].replaceAll("/","");
        name = nameAndIssuer[1].replaceAll("/","");;
    } else {
        name = nameAndIssuer[0].replaceAll("/","");;

    Set<String> params = uri.getQueryParameterNames();
    if (!params.contains("secret")
            || !params.contains("period")
            || !params.contains("digits")
            || !params.contains("algorithm")) {
        throw new IllegalArgumentException("Missed one of the following parameters secret, period, digits, algorithm");
    String secretKey = uri.getQueryParameter("secret");
    int period = Integer.parseInt(uri.getQueryParameter("period"));
    int digits = Integer.parseInt(uri.getQueryParameter("digits"));
    String algorithm = uri.getQueryParameter("algorithm");

    String encryptedSecretKey = this.defaultEncryptionManager.encrypt(secretKey);
    PersistableToken persistableToken = new PersistableToken(name, issuer, encryptedSecretKey, period, digits, algorithm);
    return new Token(persistableToken, createTotpGenerator(period, digits, algorithm, secretKey));
Example #24
Source Project: reinvent2013-mobile-photo-share   Author: aws-samples   File:    License: Apache License 2.0 5 votes vote down vote up
private static byte[] decrypt(byte[] cipherBytes, String key, byte[] iv) {
    try {
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        cipher.init(Cipher.DECRYPT_MODE, getKey(key), params);
        return cipher.doFinal(cipherBytes);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException("Failed to decrypt.", e);
Example #25
Source Project: jdk8u60   Author: chenghanpeng   File:    License: GNU General Public License v2.0 5 votes vote down vote up
public void failTest() throws GeneralSecurityException {
    Throwable caughtException = null;
    Collection<? extends CRL> crls = null;

    System.out.println("generateCRLs(): " + testName);
    if (expectedException == null) {
        throw new RuntimeException("failTest requires non-null " +

    try {
        crls =
            cf.generateCRLs(new ByteArrayInputStream(testData));
    } catch (CRLException e) {
        caughtException = e;

    if (caughtException != null) {
        // It has to be the right kind of exception though...
        if (!caughtException.getClass().equals(
                expectedException.getClass())) {
            System.err.println("Unexpected exception thrown. " +
                    "Received: " + caughtException + ", Expected: " +
            throw new RuntimeException(caughtException);
    } else {
        // For a failure test, we'd expect some kind of exception
        // to be thrown.
        throw new RuntimeException("Failed to catch expected " +
                "exception " + expectedException.getClass());
Example #26
Source Project: jdk8u-jdk   Author: frohoff   File:    License: GNU General Public License v2.0 5 votes vote down vote up
 * Verifies keyed checksum.
 * @param data the data.
 * @param size the length of data.
 * @param key the key used to encrypt the checksum.
 * @param checksum
 * @return true if verification is successful.
public boolean verifyKeyedChecksum(byte[] data, int size,
    byte[] key, byte[] checksum, int usage) throws KrbCryptoException {

     try {
        byte[] newCksum = Aes256.calculateChecksum(key, usage, data,
                                                    0, size);
        return isChecksumEqual(checksum, newCksum);
     } catch (GeneralSecurityException e) {
        KrbCryptoException ke = new KrbCryptoException(e.getMessage());
        throw ke;
Example #27
Source Project: jdk8u-dev-jdk   Author: frohoff   File:    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        KeyPairGenerator generator =
            KeyPairGenerator.getInstance("RSA", "SunMSCAPI");

        KeyPair keyPair = generator.generateKeyPair();
        Key publicKey = keyPair.getPublic();
        Key privateKey = keyPair.getPrivate();

        Cipher cipher = null;

        try {
            cipher = Cipher.getInstance("RSA", "SunMSCAPI");

        } catch (GeneralSecurityException e) {
            System.out.println("Cipher not supported by provider, skipping...");

        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        displayBytes("Plaintext data:", PLAINTEXT);
        byte[] data = cipher.doFinal(PLAINTEXT);
        displayBytes("Encrypted data:", data);

        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        data = cipher.doFinal(data);
        displayBytes("Decrypted data:", data);
Example #28
Source Project: ResearchStack   Author: ResearchStack   File:    License: Apache License 2.0 5 votes vote down vote up
public byte[] readData(Context context, String path) {
    try {
        File localFile = findLocalFile(context, path);
        return encrypter.decrypt(FileUtils.readAll(localFile));
    } catch (IOException | GeneralSecurityException e) {
        throw new StorageAccessException(e);
Example #29
Source Project: tomee   Author: apache   File:    License: Apache License 2.0 5 votes vote down vote up
public static void setupTLS(final Object port) throws GeneralSecurityException, IOException {

        final HTTPConduit httpConduit = (HTTPConduit) ClientProxy.getClient(port).getConduit();

        final TLSClientParameters tlsCP = new TLSClientParameters();
        final String storePassword = "keystorePass";
        final String keyPassword = "clientPassword";
        final KeyStore keyStore = KeyStore.getInstance("jks");
        final String keyStoreLoc = "META-INF/clientStore.jks";
        keyStore.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(keyStoreLoc), storePassword.toCharArray());

        // set the key managers from the Java KeyStore we just loaded
        final KeyManager[] myKeyManagers = getKeyManagers(keyStore, keyPassword);
        tlsCP.setCertAlias("clientalias"); // in case there is multiple certs in the keystore, make sure we pick the one we want

        // Create a trust manager that does not validate certificate chains
        // this should not be done in production. It's recommended to create a cacerts with the certificate chain or
        // to rely on a well known CA such as Verisign which is already available in the JVM
        TrustManager[] trustAllCerts = getTrustManagers();

        // don't check the host name of the certificate to match the server (running locally)
        // this should not be done on a real production system
        tlsCP.setHostnameVerifier((s, sslSession) -> true);

Example #30
Source Project: development   Author: servicecatalog   File:    License: Apache License 2.0 5 votes vote down vote up
 * @return OUTCOME_SUCCESS if successfully update selected Uda;
 *         OUTCOME_ERROR if encounter some error when updating
 * @throws SaaSApplicationException
public String update()
        throws SaaSApplicationException, GeneralSecurityException {
    // delegate to controller
    try {
        addMessage(null, FacesMessage.SEVERITY_INFO,
    } catch (ObjectNotFoundException e) {
        onfe = e;
    // evaluate result