java.security.GeneralSecurityException Java Examples

The following examples show how to use java.security.GeneralSecurityException. 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: AbstractKeyStoreManager.java    From DeviceConnect-Android with 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.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 #2
Source File: GcpStackUtil.java    From cloudbreak with 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 #3
Source File: CloudiotPubsubExampleServerTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: SunCertPathBuilder.java    From openjdk-8 with 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 File: KeyStoreUtil.java    From lams with 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 #6
Source File: KeyUtil.java    From axelor-open-suite with 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 #7
Source File: KeyStoreMaterialsProvider.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: KeyAgreementTest.java    From Encryptor4j with 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 #9
Source File: MetadataStoreLoadTest.java    From jdk8u-jdk with 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() + "'");
    });
    Arrays.stream(ATTR_SET).forEach((attr) -> {
        if (!keyStoreEntry.getAttributes().contains(attr)) {
            throw new RuntimeException("Entry doesn't contain attribute: ("
                    + attr.getName() + ", '" + attr.getValue() + "')");
        }
    });
}
 
Example #10
Source File: DecrypterManagerTest.java    From capillary with 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 #11
Source File: SignatureUtils.java    From vespa with Apache License 2.0 5 votes vote down vote up
/** Returns a signature instance which computes a hash of its content, before verifying with the given public key. */
public static Signature createVerifier(PublicKey key, SignatureAlgorithm algorithm) {
    try {
        Signature signer = Signature.getInstance(algorithm.getAlgorithmName(), BouncyCastleProviderHolder.getInstance());
        signer.initVerify(key);
        return signer;
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #12
Source File: TripleDesCrypto.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
protected Key encryptKey(final byte[] key, final int blockSize) throws GeneralSecurityException {
    //实例化Des密钥
    KeySpec dks = new DESedeKeySpec(key);
    //实例化密钥工厂
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(name);
    //生成密钥
    return keyFactory.generateSecret(dks);
}
 
Example #13
Source File: DynamoDBSignerTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void sig() throws GeneralSecurityException {
    Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
    Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>();

    itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
    attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
    itemAttributes.put("Key2", new AttributeValue().withN("100"));
    attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
    itemAttributes.put("Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[]{0, 1, 2, 3})));
    attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
    byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyRsa);

    signerRsa.verifySignature(itemAttributes, attributeFlags, new byte[0], pubKeyRsa, ByteBuffer.wrap(signature));
}
 
Example #14
Source File: GcpIamAuthenticationUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldCreateNewGcpIamObjectInstance() throws GeneralSecurityException, IOException {

	PrivateKey privateKeyMock = mock(PrivateKey.class);
	GoogleCredential credential = new Builder().setServiceAccountId("hello@world")
			.setServiceAccountProjectId("foobar").setServiceAccountPrivateKey(privateKeyMock)
			.setServiceAccountPrivateKeyId("key-id").build();
	credential.setAccessToken("foobar");

	GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().role("dev-role")
			.credential(credential).build();

	new GcpIamAuthentication(options, this.restTemplate);
}
 
Example #15
Source File: CertPathPKIXTrustEvaluator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates the certificate store that will be used during validation.
 * 
 * @param validationInfo PKIX validation information
 * @param untrustedCredential credential to be validated
 * 
 * @return certificate store used during validation
 * 
 * @throws GeneralSecurityException thrown if the certificate store can not be created from the cert and CRL
 *             material
 */
protected CertStore buildCertStore(PKIXValidationInformation validationInfo, X509Credential untrustedCredential)
        throws GeneralSecurityException {

    log.trace("Creating cert store to use during path validation");

    log.trace("Adding entity certificate chain to cert store");
    List<Object> storeMaterial = new ArrayList<Object>(untrustedCredential.getEntityCertificateChain());
    if (log.isTraceEnabled()) {
        for (X509Certificate cert : untrustedCredential.getEntityCertificateChain()) {
            log.trace(String.format("Added X509Certificate from entity cert chain to cert store "
                    + "with subject name '%s' issued by '%s' with serial number '%s'",
                    x500DNHandler.getName(cert.getSubjectX500Principal()),
                    x500DNHandler.getName(cert.getIssuerX500Principal()),
                    cert.getSerialNumber().toString()));
        }
    }
    
    Date now = new Date();
    
    if (validationInfo.getCRLs() != null && !validationInfo.getCRLs().isEmpty()) {
        log.trace("Processing CRL's from PKIX info set");
        addCRLsToStoreMaterial(storeMaterial, validationInfo.getCRLs(), now);
    }        
    
    if (untrustedCredential.getCRLs() != null && !untrustedCredential.getCRLs().isEmpty() 
            && options.isProcessCredentialCRLs()) {
        log.trace("Processing CRL's from untrusted credential");
        addCRLsToStoreMaterial(storeMaterial, untrustedCredential.getCRLs(), now);
    }        
    
    return CertStore.getInstance("Collection", new CollectionCertStoreParameters(storeMaterial));
}
 
Example #16
Source File: CredentialProviderModule.java    From presto with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
@ForExtraCredentialProvider
public CredentialProvider getCredentialProvider(KeyStoreBasedCredentialProviderConfig config)
        throws IOException, GeneralSecurityException
{
    KeyStore keyStore = loadKeyStore(config.getKeyStoreType(), config.getKeyStoreFilePath(), config.getKeyStorePassword());
    String user = readEntity(keyStore, config.getUserCredentialName(), config.getPasswordForUserCredentialName());
    String password = readEntity(keyStore, config.getPasswordCredentialName(), config.getPasswordForPasswordCredentialName());
    return new StaticCredentialProvider(Optional.of(user), Optional.of(password));
}
 
Example #17
Source File: GCSFilesSource.java    From policyscanner with Apache License 2.0 5 votes vote down vote up
/**
 * Get more files to read.
 * @return True if there are more files to be read. False otherwise.
 */
boolean refreshCurrentFiles() {
  try {
    this.nextPageToken = this.source.getFilesPage(currentFiles, null);
  } catch (IOException | GeneralSecurityException e) {
    return false;
  }
  return !this.currentFiles.isEmpty();
}
 
Example #18
Source File: ManageUdaDefinitionBean.java    From development with 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;
}
 
Example #19
Source File: SlackSlashCommandTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void handlesPopulatedKgResultsTest() throws IOException, GeneralSecurityException {
  String jsonStr = gson.toJson(Map.of("text", "lion"));
  StringReader requestReadable = new StringReader(jsonStr);

  when(request.getReader()).thenReturn(new BufferedReader(requestReadable));
  when(request.getMethod()).thenReturn("POST");

  SlackSlashCommand functionInstance = new SlackSlashCommand(alwaysValidVerifier);

  functionInstance.service(request, response);

  writerOut.flush();
  assertThat(responseOut.toString()).contains("https://en.wikipedia.org/wiki/Lion");
}
 
Example #20
Source File: TokensFactory.java    From samples-android with 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 #21
Source File: DetectInvalidEncoding.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void failTest() throws GeneralSecurityException {
    Throwable caughtException = null;
    Collection<? extends Certificate> certs = null;

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

    try {
        certs =
            cf.generateCertificates(new ByteArrayInputStream(testData));
    } catch (CertificateException ce) {
        caughtException = ce;
    }

    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 #22
Source File: Cryptography.java    From island with Apache License 2.0 5 votes vote down vote up
public static boolean verify(final String data, final @Nullable String signature) throws GeneralSecurityException {
	final KeyStore keystore = getAndroidKeyStore();
	final Certificate certificate = keystore.getCertificate(KEYPAIR_ALIAS);
	if (certificate == null) {
		Log.w(TAG, "Cannot verify due to certificate not found.");
		return false;
	}
	final Signature verifier = Signature.getInstance("SHA512withRSA");
	verifier.initVerify(certificate);			// Even if signature is null, we init the verification first and throw GeneralSecurityException if failed.
	verifier.update(data.getBytes(ISO_8859_1));	// So we could skip the verification when initialization failed, but reject the null signature otherwise.
	return signature != null && verifier.verify(signature.getBytes(ISO_8859_1));
}
 
Example #23
Source File: SSLCipher.java    From openjsse with GNU General Public License v2.0 5 votes vote down vote up
BlockWriteCipher(Authenticator authenticator,
        ProtocolVersion protocolVersion, String algorithm,
        Key key, AlgorithmParameterSpec params,
        SecureRandom random) throws GeneralSecurityException {
    super(authenticator, protocolVersion);
    this.cipher = JsseJce.getCipher(algorithm);
    cipher.init(Cipher.ENCRYPT_MODE, key, params, random);
}
 
Example #24
Source File: CalculatorTest.java    From tomee with 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 #25
Source File: SimpleFileAccess.java    From ResearchStack with 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 #26
Source File: RSAEncryptDecrypt.java    From jdk8u-dev-jdk with 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...");
            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 #27
Source File: HmacSha1Aes256CksumType.java    From jdk8u-jdk with 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());
        ke.initCause(e);
        throw ke;
     }
}
 
Example #28
Source File: DetectInvalidEncoding.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@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 #29
Source File: AESEncryption.java    From reinvent2013-mobile-photo-share with 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 #30
Source File: NettyTsiHandshakerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
static void doHandshake(
    NettyTsiHandshaker clientHandshaker,
    NettyTsiHandshaker serverHandshaker,
    ByteBufAllocator alloc,
    Function<ByteBuf, ByteBuf> ref)
    throws GeneralSecurityException {
  // Get the server response handshake frames.
  for (int i = 0; i < 10; i++) {
    if (!(clientHandshaker.isInProgress() || serverHandshaker.isInProgress())) {
      return;
    }

    ByteBuf clientData = ref.apply(alloc.buffer());
    clientHandshaker.getBytesToSendToPeer(clientData);
    if (clientData.isReadable()) {
      serverHandshaker.processBytesFromPeer(clientData);
    }

    ByteBuf serverData = ref.apply(alloc.buffer());
    serverHandshaker.getBytesToSendToPeer(serverData);
    if (serverData.isReadable()) {
      clientHandshaker.processBytesFromPeer(serverData);
    }
  }

  throw new AssertionError("Failed to complete the handshake.");
}