Java Code Examples for java.security.GeneralSecurityException

The following examples show how to use java.security.GeneralSecurityException. 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: cloudbreak   Source File: GcpStackUtil.java    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)
                .createScoped(SCOPES);
    } else {
        try {
            PrivateKey pk = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(),
                    new ByteArrayInputStream(Base64.decodeBase64(getServiceAccountPrivateKey(gcpCredential))), "notasecret", "privatekey", "notasecret");
            return new GoogleCredential.Builder().setTransport(httpTransport)
                    .setJsonFactory(JSON_FACTORY)
                    .setServiceAccountId(getServiceAccountId(gcpCredential))
                    .setServiceAccountScopes(SCOPES)
                    .setServiceAccountPrivateKey(pk)
                    .build();
        } catch (IOException e) {
            throw new CredentialVerificationException("Can not read private key", e);
        }
    }
}
 
Example 2
Source Project: Encryptor4j   Source File: KeyAgreementTest.java    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 https://tools.ietf.org/html/rfc3526
 * @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 3
@Override
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 4
Source Project: openjdk-8   Source File: SunCertPathBuilder.java    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) {
        debug.println("SunCertPathBuilder.buildForward()...");
    }

    /* Initialize current state */
    ForwardState currentState = new ForwardState();
    currentState.initState(buildParams.certPathCheckers());

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

    currentState.untrustedChecker = new UntrustedChecker();

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

  byte[] ciphertextBytes = ciphertextBuilder.build().toByteArray();

  // New key pair generated.
  when(keyManager.generateKeyPair(anyInt(), anyBoolean())).thenReturn(true);
  decrypterManager.decrypt(ciphertextBytes, handler, extra);
  verify(handler).handlePublicKey(
      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);
  verifyNoMoreInteractions(handler);
}
 
Example 6
@Test
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();
  Assert.assertTrue(got.contains("on"));
  Assert.assertTrue(got.contains("11"));
  Assert.assertTrue(got.contains("test-device-"));

  // Clean up
  CloudiotPubsubExampleServer.deleteDevice(DEVICE_ID, PROJECT_ID, CLOUD_REGION, REGISTRY_ID);
  CloudiotPubsubExampleServer.deleteRegistry(CLOUD_REGION, PROJECT_ID, REGISTRY_ID);
}
 
Example 7
Source Project: DeviceConnect-Android   Source File: AbstractKeyStoreManager.java    License: MIT License 6 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.setSerialNumber(serialNumber);
    generator.setIssuerDN(issuer);
    generator.setSubjectDN(subject);
    generator.setNotBefore(notBefore);
    generator.setNotAfter(notAfter);
    generator.setPublicKey(keyPair.getPublic());
    generator.setSignatureAlgorithm("SHA256WithRSAEncryption");
    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 8
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() + "'");
    });
    Arrays.stream(ATTR_SET).forEach((attr) -> {
        if (!keyStoreEntry.getAttributes().contains(attr)) {
            throw new RuntimeException("Entry doesn't contain attribute: ("
                    + attr.getName() + ", '" + attr.getValue() + "')");
        }
    });
}
 
Example 9
Source Project: lams   Source File: KeyStoreUtil.java    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;
   try
   {
      is = url.openStream();
      return getKeyStore(keyStoreType, is, storePass);
   }
   finally
   {
      safeClose(is);
   }      
}
 
Example 10
/**
 * 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   Source File: TlsClientManager.java    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   Source File: AltsProtocolNegotiatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  ChannelHandler uncaughtExceptionHandler =
      new ChannelDuplexHandler() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
          caughtException = cause;
          super.exceptionCaught(ctx, cause);
          ctx.close();
        }
      };

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

            @Override
            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)
      .newHandler(grpcHandler);
  // 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   Source File: SSLCipher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
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   Source File: VerifyAsymmetricRsa.java    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   Source File: SocketMessageTransportData.java    License: Apache License 2.0 5 votes vote down vote up
public AuthGenerator createAuthGenerator()
{
    if (this.token != null)
    {
        try
        {
            return new AuthGenerator(token);
        }
        catch (GeneralSecurityException e)
        {
            throw new RuntimeException("Never happens", e);
        }
    }
    return null;
}
 
Example 16
/**
 * @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   Source File: JsonWebKey.java    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   Source File: CryptoUtil.java    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);
		mac.init(secretKey);
		return mac.doFinal(input);
	} catch (GeneralSecurityException e) {
		throw ExceptionUtil.unchecked(e);
	}
}
 
Example 19
Source Project: hono   Source File: DeviceCertificateValidator.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Future<Void> validate(final List<X509Certificate> chain, final Set<TrustAnchor> trustAnchors) {

    Objects.requireNonNull(chain);
    Objects.requireNonNull(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?
        params.setRevocationEnabled(false);
        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",
                chain.get(0).getSubjectX500Principal().getName());
        result.complete();
    } catch (GeneralSecurityException e) {
        LOG.debug("validation of device certificate [subject DN: {}] failed",
                chain.get(0).getSubjectX500Principal().getName(), e);
        if (e instanceof CertificateException) {
            result.fail(e);
        } else {
            result.fail(new CertificateException("validation of device certificate failed", e));
        }
    }
    return result.future();
}
 
Example 20
Source Project: openjsse   Source File: SSLCipher.java    License: GNU General Public License v2.0 5 votes vote down vote up
static final SSLReadCipher nullTlsReadCipher() {
    try {
        return B_NULL.createReadCipher(
                Authenticator.nullTlsMac(),
                ProtocolVersion.NONE, null, null, null);
    } catch (GeneralSecurityException gse) {
        // unlikely
        throw new RuntimeException("Cannot create NULL SSLCipher", gse);
    }
}
 
Example 21
Source Project: ha-bridge   Source File: BridgeSecurity.java    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   Source File: VaultConfig.java    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
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    return trustManagerFactory;
}
 
Example 23
Source Project: samples-android   Source File: TokensFactory.java    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
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
@Override
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 " +
                "expectedException");
    }

    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: " +
                    expectedException.getClass());
            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
/**
 * 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());
        ke.initCause(e);
        throw ke;
     }
}
 
Example 27
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...");
            return;
        }

        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   Source File: SimpleFileAccess.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@WorkerThread
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   Source File: CalculatorTest.java    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.setKeyManagers(myKeyManagers);
        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();
        tlsCP.setTrustManagers(trustAllCerts);

        // 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);

        httpConduit.setTlsClientParameters(tlsCP);
    }
 
Example 30
Source Project: development   Source File: ManageUdaDefinitionBean.java    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 {
        controller.updateUdaDefinition();
        addMessage(null, FacesMessage.SEVERITY_INFO,
                BaseBean.INFO_UDADEFINITIONS_SAVED);
    } catch (ObjectNotFoundException e) {
        onfe = e;
    }
    // evaluate result
    return OUTCOME_SUCCESS;
}