Java Code Examples for java.security.GeneralSecurityException#printStackTrace()

The following examples show how to use java.security.GeneralSecurityException#printStackTrace() . 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: AbstractCRLRevocationCheckerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link AbstractCRLRevocationChecker#check(X509Certificate)}.
 */
@Test
public void testCheck() {
    try {
        for (X509Certificate cert : this.certificates) {
            getChecker().check(cert);
        }
        if (this.expected != null) {
            Assert.fail("Expected exception of type " + this.expected.getClass());
        }
    } catch (final GeneralSecurityException e) {
        if (this.expected == null) {
            e.printStackTrace();
            Assert.fail("Revocation check failed unexpectedly with exception: " + e);
        } else {
            final Class<?> expectedClass = this.expected.getClass();
            final Class<?> actualClass = e.getClass();
            Assert.assertTrue(
                    String.format("Expected exception of type %s but got %s", expectedClass, actualClass),
                    expectedClass.isAssignableFrom(actualClass));
        }
    }
}
 
Example 2
Source File: EncryptionTests.java    From jsondb-core with MIT License 6 votes vote down vote up
@Test
public void changeEncryptionTest() {
  ICipher newCipher = null;
  try {
    newCipher = new DefaultAESCBCCipher("jCt039xT0eUwkIqAWACw/w==");
  } catch (GeneralSecurityException e) {
    e.printStackTrace();
  }

  jsonDBTemplate.changeEncryption(newCipher);

  String[] expectedLastLineAtEnd = {
      "{\"id\":\"06\",\"hostname\":\"ec2-54-191-06\","
      + "\"privateKey\":\"J5CnDOTBe4OwePT43esS7vDb5DVqi+VGtRoICipcTdtyyh5N1gxbUdtvx8N9sCpZ\","
      + "\"publicKey\":\"\"}"};

  TestUtils.checkLastLines(instancesJson, expectedLastLineAtEnd);

  Instance i = jsonDBTemplate.findById("01", "instances");
  assertEquals("b87eb02f5dd7e5232d7b0fc30a5015e4", i.getPrivateKey());
}
 
Example 3
Source File: ThresholdExpiredCRLRevocationPolicyTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link ThresholdExpiredCRLRevocationPolicy#apply(java.security.cert.X509CRL)}.
 */
@Test
public void testApply() {
    try {
        this.policy.apply(this.crl);
        if (this.expected != null) {
            Assert.fail("Expected exception of type " + this.expected.getClass());
        }
    } catch (final GeneralSecurityException e) {
        if (this.expected == null) {
            e.printStackTrace();
            Assert.fail("Revocation check failed unexpectedly with exception: " + e);
        } else {
            final Class<?> expectedClass = this.expected.getClass();
            final Class<?> actualClass = e.getClass();
            Assert.assertTrue(
                    String.format("Expected exception of type %s but got %s", expectedClass, actualClass),
                    expectedClass.isAssignableFrom(actualClass));
        }
    }
}
 
Example 4
Source File: NtlmPasswordAuthentication.java    From jcifs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static byte[] getNTLM2Response(byte[] nTOWFv1,
                byte[] serverChallenge,
                byte[] clientChallenge)
{
    byte[] sessionHash = new byte[8];

    try {
        MessageDigest md5;
        md5 = MessageDigest.getInstance("MD5");
        md5.update(serverChallenge);
        md5.update(clientChallenge, 0, 8);
        System.arraycopy(md5.digest(), 0, sessionHash, 0, 8);
    } catch (GeneralSecurityException gse) {
        if (log.level > 0)
            gse.printStackTrace(log);
        throw new RuntimeException("MD5", gse);
    }

    byte[] key = new byte[21];
    System.arraycopy(nTOWFv1, 0, key, 0, 16);
    byte[] ntResponse = new byte[24];
    E(key, sessionHash, ntResponse);

    return ntResponse;
}
 
Example 5
Source File: ContentWorkflowSample.java    From googleads-shopping-samples with Apache License 2.0 6 votes vote down vote up
protected static ShoppingContent.Builder createStandardBuilder(
    CommandLine parsedArgs, ContentConfig config) throws IOException {
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpTransport httpTransport = null;
  try {
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  } catch (GeneralSecurityException e) {
    e.printStackTrace();
    System.exit(1);
  }
  Authenticator authenticator =
      new Authenticator(httpTransport, jsonFactory, ShoppingContentScopes.all(), config);
  Credential credential = authenticator.authenticate();

  return new ShoppingContent.Builder(
          httpTransport, jsonFactory, BaseOption.installLogging(credential, parsedArgs))
      .setApplicationName("Content API for Shopping Samples");
}
 
Example 6
Source File: Encryptor.java    From kaif with Apache License 2.0 5 votes vote down vote up
/**
 * both key and iv are 16 bytes
 *
 * @param key
 * @param iv
 *     16 bytes initial vector
 */
public static Encryptor create(final byte[] key, final byte[] iv) {
  try {
    final IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

    return new Encryptor(key, "AES/CBC/PKCS5Padding", ivParameterSpec);
  } catch (final GeneralSecurityException e) {
    e.printStackTrace();
    throw new RuntimeException("unsupported type of encryption: AES");
  }
}
 
Example 7
Source File: SignatureFileVerifier.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check if algorithm is permitted using the permittedAlgs Map.
 * If the algorithm is not in the map, check against disabled algorithms and
 * store the result. If the algorithm is in the map use that result.
 * False is returned for weak algorithm, true for good algorithms.
 */
boolean permittedCheck(String key, String algorithm) {
    Boolean permitted = permittedAlgs.get(algorithm);
    if (permitted == null) {
        try {
            JAR_DISABLED_CHECK.permits(algorithm,
                    new ConstraintsParameters(timestamp));
        } catch(GeneralSecurityException e) {
            permittedAlgs.put(algorithm, Boolean.FALSE);
            permittedAlgs.put(key.toUpperCase(), Boolean.FALSE);
            if (debug != null) {
                if (e.getMessage() != null) {
                    debug.println(key + ":  " + e.getMessage());
                } else {
                    debug.println(key + ":  " + algorithm +
                            " was disabled, no exception msg given.");
                    e.printStackTrace();
                }
            }
            return false;
        }

        permittedAlgs.put(algorithm, Boolean.TRUE);
        return true;
    }

    // Algorithm has already been checked, return the value from map.
    return permitted.booleanValue();
}
 
Example 8
Source File: PluggableParameterOperatorBinary.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
private static void getCipherStream(Cipher aesCipher, byte[] out, int length, byte[] iv)
{
	final int BLKLEN = 16;
    
    byte[] in  = new byte[BLKLEN];
    byte[] tmp = new byte[BLKLEN];

    System.arraycopy(iv, 0, in, 0, 14);

    try 
    {
        
        int ctr;
        for (ctr = 0; ctr < length / BLKLEN; ctr++)
        {
            // compute the cipher stream
            in[14] = (byte) ((ctr & 0xFF00) >> 8);
            in[15] = (byte) ((ctr & 0x00FF));

            aesCipher.update(in, 0, BLKLEN, out, ctr * BLKLEN);
        }

        // Treat the last bytes:
        in[14] = (byte) ((ctr & 0xFF00) >> 8);
        in[15] = (byte) ((ctr & 0x00FF));

        aesCipher.doFinal(in, 0, BLKLEN, tmp, 0);
        System.arraycopy(tmp, 0, out, ctr * BLKLEN, length % BLKLEN);
    }
    catch (GeneralSecurityException e)
    {
        e.printStackTrace();
    }
}
 
Example 9
Source File: PluginSandboxPolicy.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates the public key based on the Base64 encoded key string.
 *
 * @param base64EncodedKey
 * 		the Base64 encoded public key
 * @return the key or {@code null} if creation failed
 */
private static PublicKey createPublicKey(final String base64EncodedKey) {
	try {
		KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
		X509EncodedKeySpec spec = new X509EncodedKeySpec(DatatypeConverter.parseBase64Binary(base64EncodedKey));
		return factory.generatePublic(spec);
	} catch (GeneralSecurityException e) {
		// no log service available yet, so use syserr
		System.err.println("Failed to initialize public key to verify extension certificates!");
		e.printStackTrace();
		return null;
	}
}
 
Example 10
Source File: BlowFishKey.java    From L2jBrasil with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param decrypt
 */
public BlowFishKey(byte[] decrypt, RSAPrivateKey privateKey)
{
	super(decrypt);
	int size = readD();
	byte[] tempKey = readB(size);
	try
	{
		byte [] tempDecryptKey;
		Cipher rsaCipher = Cipher.getInstance("RSA/ECB/nopadding");
        rsaCipher.init(Cipher.DECRYPT_MODE, privateKey);
        tempDecryptKey = rsaCipher.doFinal(tempKey);
        // there are nulls before the key we must remove them
        int i = 0;
        int len = tempDecryptKey.length;
        for(; i < len; i++)
        {
        	if(tempDecryptKey[i] != 0)
        		break;
        }
        _key = new byte[len-i];
        System.arraycopy(tempDecryptKey,i,_key,0,len-i);
	}
	catch(GeneralSecurityException e)
	{
		_log.severe("Error While decrypting blowfish key (RSA)");
		e.printStackTrace();
	}
	/*catch(IOException ioe)
	{
		//TODO: manage
	}*/

}
 
Example 11
Source File: DataHelper.java    From SMS302 with Apache License 2.0 5 votes vote down vote up
String encode(String msg) {
    String data = EMPTY;
    try {
        data = AESCrypt.encrypt(KEY, msg);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }
    return data;
}
 
Example 12
Source File: IronEncryption.java    From Iron with Apache License 2.0 5 votes vote down vote up
@Override
public Cipher getCipher(int mode){
    try {
        byte[] iv = generateIv();
        Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
        cipher.init(mode, mKey.getConfidentialityKey(), new IvParameterSpec(iv));
        return cipher;
    }catch(GeneralSecurityException e){
        e.printStackTrace();
    }
    return null;
}
 
Example 13
Source File: MiniCrypter.java    From mdw with Apache License 2.0 5 votes vote down vote up
/**
 * Encrypt a string using a default key
 * @param input data to encrypt
 * @return encrypted string
 */
public static String encrypt(String input) {
    try {
        return encrypt(input, null);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 14
Source File: Decryptor.java    From kaif with Apache License 2.0 5 votes vote down vote up
/**
 * @see Encryptor#create(byte[], byte[])) for key algorithm
 */
public static Decryptor create(final byte[] key, final byte[] iv) {
  try {
    final IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
    return new Decryptor(key, "AES/CBC/PKCS5Padding", ivParameterSpec);
  } catch (final GeneralSecurityException e) {
    e.printStackTrace();
    throw new RuntimeException("unsupported type of encryption: AES");
  }
}
 
Example 15
Source File: FindQueryTests.java    From jsondb-core with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  dbFilesFolder.mkdir();
  Files.copy(new File("src/test/resources/dbfiles/instances.json"), instancesJson);
  ICipher cipher = null;
  try {
    cipher = new DefaultAESCBCCipher("1r8+24pibarAWgS85/Heeg==");
  } catch (GeneralSecurityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

  jsonDBTemplate = new JsonDBTemplate(dbFilesLocation, "io.jsondb.tests.model", cipher);
}
 
Example 16
Source File: Rc4.java    From butterfly with Apache License 2.0 5 votes vote down vote up
/**
 * Decrypts the given data using RC4.
 * @param data The data to decrypt
 * @param key The key to use for decryption
 * @return The decrypted data
 * @throws GeneralSecurityException
 */
public static byte[] decrypt(final byte[] data, final String key) {
    try {
        final byte[] keyBytes = getKeyFromEamuseHeader(key);
        final SecretKey sk = new SecretKeySpec(keyBytes, 0, keyBytes.length, "RC4");
        final Cipher cipher = Cipher.getInstance("RC4");
        cipher.init(Cipher.DECRYPT_MODE, sk);
        return cipher.doFinal(data);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 17
Source File: SSLSocketFactoryFactory.java    From PADListener with GNU General Public License v2.0 5 votes vote down vote up
private void saveKeystore(KeyStore keystore, String filename, char[] password) {
    if (filename == null)
        return;
    try {
        OutputStream out = new FileOutputStream(filename);
        keystore.store(out, password);
        out.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (GeneralSecurityException gse) {
        gse.printStackTrace();
    }
}
 
Example 18
Source File: ForwardBuilder.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Verifies whether the input certificate completes the path.
 * Checks the cert against each trust anchor that was specified, in order,
 * and returns true as soon as it finds a valid anchor.
 * Returns true if the cert matches a trust anchor specified as a
 * certificate or if the cert verifies with a trust anchor that
 * was specified as a trusted {pubkey, caname} pair. Returns false if none
 * of the trust anchors are valid for this cert.
 *
 * @param cert the certificate to test
 * @return a boolean value indicating whether the cert completes the path.
 */
@Override
boolean isPathCompleted(X509Certificate cert) {
    for (TrustAnchor anchor : trustAnchors) {
        if (anchor.getTrustedCert() != null) {
            if (cert.equals(anchor.getTrustedCert())) {
                this.trustAnchor = anchor;
                return true;
            } else {
                continue;
            }
        }
        X500Principal principal = anchor.getCA();
        PublicKey publicKey = anchor.getCAPublicKey();

        if (principal != null && publicKey != null &&
                principal.equals(cert.getSubjectX500Principal())) {
            if (publicKey.equals(cert.getPublicKey())) {
                // the cert itself is a trust anchor
                this.trustAnchor = anchor;
                return true;
            }
            // else, it is a self-issued certificate of the anchor
        }

        // Check subject/issuer name chaining
        if (principal == null ||
                !principal.equals(cert.getIssuerX500Principal())) {
            continue;
        }

        // skip anchor if it contains a DSA key with no DSA params
        if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) {
            continue;
        }

        /*
         * Check signature
         */
        try {
            cert.verify(publicKey, buildParams.sigProvider());
        } catch (InvalidKeyException ike) {
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() invalid "
                              + "DSA key found");
            }
            continue;
        } catch (GeneralSecurityException e){
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() " +
                              "unexpected exception");
                e.printStackTrace();
            }
            continue;
        }

        this.trustAnchor = anchor;
        return true;
    }

    return false;
}
 
Example 19
Source File: ForwardBuilder.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Verifies whether the input certificate completes the path.
 * Checks the cert against each trust anchor that was specified, in order,
 * and returns true as soon as it finds a valid anchor.
 * Returns true if the cert matches a trust anchor specified as a
 * certificate or if the cert verifies with a trust anchor that
 * was specified as a trusted {pubkey, caname} pair. Returns false if none
 * of the trust anchors are valid for this cert.
 *
 * @param cert the certificate to test
 * @return a boolean value indicating whether the cert completes the path.
 */
@Override
boolean isPathCompleted(X509Certificate cert) {
    for (TrustAnchor anchor : trustAnchors) {
        if (anchor.getTrustedCert() != null) {
            if (cert.equals(anchor.getTrustedCert())) {
                this.trustAnchor = anchor;
                return true;
            } else {
                continue;
            }
        }
        X500Principal principal = anchor.getCA();
        PublicKey publicKey = anchor.getCAPublicKey();

        if (principal != null && publicKey != null &&
                principal.equals(cert.getSubjectX500Principal())) {
            if (publicKey.equals(cert.getPublicKey())) {
                // the cert itself is a trust anchor
                this.trustAnchor = anchor;
                return true;
            }
            // else, it is a self-issued certificate of the anchor
        }

        // Check subject/issuer name chaining
        if (principal == null ||
                !principal.equals(cert.getIssuerX500Principal())) {
            continue;
        }

        // skip anchor if it contains a DSA key with no DSA params
        if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) {
            continue;
        }

        /*
         * Check signature
         */
        try {
            cert.verify(publicKey, buildParams.sigProvider());
        } catch (InvalidKeyException ike) {
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() invalid "
                              + "DSA key found");
            }
            continue;
        } catch (GeneralSecurityException e){
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() " +
                              "unexpected exception");
                e.printStackTrace();
            }
            continue;
        }

        this.trustAnchor = anchor;
        return true;
    }

    return false;
}
 
Example 20
Source File: ForwardBuilder.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Verifies whether the input certificate completes the path.
 * Checks the cert against each trust anchor that was specified, in order,
 * and returns true as soon as it finds a valid anchor.
 * Returns true if the cert matches a trust anchor specified as a
 * certificate or if the cert verifies with a trust anchor that
 * was specified as a trusted {pubkey, caname} pair. Returns false if none
 * of the trust anchors are valid for this cert.
 *
 * @param cert the certificate to test
 * @return a boolean value indicating whether the cert completes the path.
 */
@Override
boolean isPathCompleted(X509Certificate cert) {
    for (TrustAnchor anchor : trustAnchors) {
        if (anchor.getTrustedCert() != null) {
            if (cert.equals(anchor.getTrustedCert())) {
                this.trustAnchor = anchor;
                return true;
            } else {
                continue;
            }
        }
        X500Principal principal = anchor.getCA();
        PublicKey publicKey = anchor.getCAPublicKey();

        if (principal != null && publicKey != null &&
                principal.equals(cert.getSubjectX500Principal())) {
            if (publicKey.equals(cert.getPublicKey())) {
                // the cert itself is a trust anchor
                this.trustAnchor = anchor;
                return true;
            }
            // else, it is a self-issued certificate of the anchor
        }

        // Check subject/issuer name chaining
        if (principal == null ||
                !principal.equals(cert.getIssuerX500Principal())) {
            continue;
        }

        // skip anchor if it contains a DSA key with no DSA params
        if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) {
            continue;
        }

        /*
         * Check signature
         */
        try {
            cert.verify(publicKey, buildParams.sigProvider());
        } catch (InvalidKeyException ike) {
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() invalid "
                              + "DSA key found");
            }
            continue;
        } catch (GeneralSecurityException e){
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() " +
                              "unexpected exception");
                e.printStackTrace();
            }
            continue;
        }

        this.trustAnchor = anchor;
        return true;
    }

    return false;
}