Java Code Examples for java.security.GeneralSecurityException

The following are top voted examples for showing how to use java.security.GeneralSecurityException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: CrashCoin   File: Main.java   View source code 7 votes vote down vote up
public static void main(final String[] argv) throws IOException, InvalidKeySpecException, NoSuchPaddingException, 
        InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException,
        InvalidAlgorithmParameterException, ClassNotFoundException, GeneralSecurityException {
    
    if(argv.length >= 2) {
        ip = argv[0];
        port = Integer.parseInt(argv[1]);
    } else {
        Logger.getLogger(Main.class.getName()).log(Level.INFO, "Default ip and port were applied.");
        ip = Parameters.RELAY_IP;
        port = Parameters.RELAY_PORT_WALLET_LISTENER;
    }
    
    // Init connection with relay
    try {
        RelayConnection.getInstance();
    } catch(IOException ex) {
        Logger.getLogger(Main.class.getName()).severe(ex.getMessage());
        return;
    }
    
    new ClientApplication();

}
 
Example 2
Project: hadoop-oss   File: AbstractReEncryptionKeyProvider.java   View source code 6 votes vote down vote up
public EncryptedKeyVersion transformEncryptedKey(EncryptedKeyVersion encryptedKeyVersion, ReEncryptionKeyInstance reKey)
    throws IOException, GeneralSecurityException
{
    CryptoCodec reCC = CryptoCodec.getInstance(conf, suite);
    Encryptor encryptor = reCC.createEncryptor();
    encryptor.init(reKey.getMaterial(), null);
    int keyLen = encryptedKeyVersion.getEncryptedKeyVersion().getMaterial().length;
    ByteBuffer bbIn = ByteBuffer.allocateDirect(keyLen);
    ByteBuffer bbOut = ByteBuffer.allocateDirect(keyLen);
    bbIn.put(encryptedKeyVersion.getEncryptedKeyVersion().getMaterial());
    bbIn.flip();
    encryptor.encrypt(bbIn, bbOut);
    byte[] encryptedKey = new byte[bbOut.limit()];
    bbOut.get(encryptedKey);
    final String dstKeyNameVersion = reKey.getDstNameVersion();
    return EncryptedKeyVersion.createForDecryption(KeyPairProvider.getBaseName(dstKeyNameVersion),
        dstKeyNameVersion,
        encryptedKeyVersion.getEncryptedKeyIv(), encryptedKey);
}
 
Example 3
Project: ipack   File: EnvelopedDataHelper.java   View source code 6 votes vote down vote up
Cipher createRFC3211Wrapper(ASN1ObjectIdentifier algorithm)
    throws CMSException
{
    String cipherName = (String)BASE_CIPHER_NAMES.get(algorithm);

    if (cipherName == null)
    {
        throw new CMSException("no name for " + algorithm);
    }

    cipherName += "RFC3211Wrap";

    try
    {
         return helper.createCipher(cipherName);
    }
    catch (GeneralSecurityException e)
    {
        throw new CMSException("cannot create cipher: " + e.getMessage(), e);
    }
}
 
Example 4
Project: openjdk-jdk10   File: AesDkCrypto.java   View source code 6 votes vote down vote up
private byte[] stringToKey(char[] secret, byte[] salt, byte[] params)
    throws GeneralSecurityException {

    int iter_count = DEFAULT_ITERATION_COUNT;
    if (params != null) {
        if (params.length != 4) {
            throw new RuntimeException("Invalid parameter to stringToKey");
        }
        iter_count = readBigEndian(params, 0, 4);
    }

    byte[] tmpKey = randomToKey(PBKDF2(secret, salt, iter_count,
                                    getKeySeedLength()));
    byte[] result = dk(tmpKey, KERBEROS_CONSTANT);
    return result;
}
 
Example 5
Project: Nird2   File: BlogPostFactoryImpl.java   View source code 6 votes vote down vote up
@Override
public Message createBlogComment(GroupId groupId, LocalAuthor author,
		@Nullable String comment, MessageId parentOriginalId,
		MessageId parentCurrentId)
		throws FormatException, GeneralSecurityException {

	if (comment != null) {
		int commentLength = StringUtils.toUtf8(comment).length;
		if (commentLength == 0) throw new IllegalArgumentException();
		if (commentLength > MAX_BLOG_COMMENT_LENGTH)
			throw new IllegalArgumentException();
	}

	long timestamp = clock.currentTimeMillis();

	// Generate the signature
	BdfList signed = BdfList.of(groupId, timestamp, comment,
			parentOriginalId, parentCurrentId);
	byte[] sig = clientHelper
			.sign(SIGNING_LABEL_COMMENT, signed, author.getPrivateKey());

	// Serialise the signed message
	BdfList message = BdfList.of(COMMENT.getInt(), comment,
			parentOriginalId, parentCurrentId, sig);
	return clientHelper.createMessage(groupId, timestamp, message);
}
 
Example 6
Project: oscm   File: AESEncrypter.java   View source code 6 votes vote down vote up
/**
 * Encrypts a given byte array based on a shared secret.
 *
 * @param bytes
 * @return the encrypted bytes as Base64
 * @throws GeneralSecurityException
 *             on any problem during encryption
 */
public static byte[] encrypt(byte[] bytes) throws GeneralSecurityException {

    SecretKeySpec skeySpec = new SecretKeySpec(
            Base64.decodeBase64(ENCRYPTION_KEY), "AES");

    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

    byte[] encrypted = cipher.doFinal(bytes);
    return Base64.encodeBase64(encrypted);
}
 
Example 7
Project: cas-5.1.0   File: AbstractPac4jAuthenticationHandler.java   View source code 6 votes vote down vote up
/**
 * Build the handler result.
 *
 * @param credentials the provided credentials
 * @param profile     the retrieved user profile
 * @return the built handler result
 * @throws GeneralSecurityException On authentication failure.
 * @throws PreventedException       On the indeterminate case when authentication is prevented.
 */
protected HandlerResult createResult(final ClientCredential credentials, final UserProfile profile)
        throws GeneralSecurityException, PreventedException {

    if (profile != null) {
        final String id;
        if (isTypedIdUsed) {
            id = profile.getTypedId();
        } else {
            id = profile.getId();
        }
        if (StringUtils.isNotBlank(id)) {
            credentials.setUserProfile(profile);
            credentials.setTypedIdUsed(isTypedIdUsed);
            return new DefaultHandlerResult(
                    this,
                    new BasicCredentialMetaData(credentials),
                    this.principalFactory.createPrincipal(id, profile.getAttributes()));
        }

        throw new FailedLoginException("No identifier found for this user profile: " + profile);
    }

    throw new FailedLoginException("Authentication did not produce a user profile for: " + credentials);
}
 
Example 8
Project: alfresco-core   File: EncryptingOutputStream.java   View source code 6 votes vote down vote up
@Override
public void close() throws IOException
{
    try
    {
        // Write the last block
        writeBlock(this.outputCipher.doFinal());
    }
    catch (final GeneralSecurityException e)
    {
        throw new RuntimeException(e);
    }
    // Write the MAC code
    writeBlock(this.mac.doFinal());
    this.wrapped.close();
    this.dataStr.close();
}
 
Example 9
Project: Wurst-MC-1.12   File: Encryption.java   View source code 6 votes vote down vote up
private SecretKey getAesKey(Path path, KeyPair pair)
{
	if(Files.notExists(path))
		return createAesKey(path, pair);
	
	try
	{
		return loadAesKey(path, pair);
	}catch(GeneralSecurityException | IOException e)
	{
		System.err.println("Couldn't load AES key!");
		e.printStackTrace();
		
		return createAesKey(path, pair);
	}
}
 
Example 10
Project: oneops   File: CMSClientTest.java   View source code 6 votes vote down vote up
@Test(priority=10)
public void commitAndDeployTest() throws GeneralSecurityException{
	
	DelegateExecution delegateExecution = mock(DelegateExecution.class);
	CmsRelease cmsRelease = mock(CmsRelease.class);
	when(cmsRelease.getReleaseId()).thenReturn(TEST_CI_ID / 2);
	
	CmsCISimple cmsCISimpleEnv = mock(CmsCISimple.class);
	when(cmsCISimpleEnv.getCiId()).thenReturn(TEST_CI_ID);
	
	when(delegateExecution.getVariable("release")).thenReturn(cmsRelease);
	when(delegateExecution.getVariable("env")).thenReturn(cmsCISimpleEnv);
		
	cc.setRestTemplate(mockHttpClientPostCommitAndDeploy);
	try {
		cc.commitAndDeployRelease(delegateExecution);
	} catch (GeneralSecurityException e) {
		throw e;
	}
}
 
Example 11
Project: boohee_v5.6   File: bu.java   View source code 6 votes vote down vote up
private void a(boolean z, String str, String str2, Map<String, Object> map, cw cwVar,
               OnFailureCallBack onFailureCallBack) {
    try {
        RequestBody create;
        Builder c = c(str);
        if (z) {
            create = RequestBody.create(a, a((Map) map));
        } else {
            create = RequestBody.create(a, c.a((Map) map).toString());
            c.removeHeader("Authorization");
        }
        c.url(str2).post(create);
        a(c.build(), cwVar, onFailureCallBack);
    } catch (GeneralSecurityException e) {
        if (onFailureCallBack != null) {
            this.d.post(new bv(this, onFailureCallBack));
        }
    }
}
 
Example 12
Project: cas4.0.x-server-wechat   File: X509CredentialsAuthenticationHandler.java   View source code 6 votes vote down vote up
private void validate(final X509Certificate cert) throws GeneralSecurityException {
    cert.checkValidity();
    this.revocationChecker.check(cert);

    int pathLength = cert.getBasicConstraints();
    if (pathLength < 0) {
        if (!isCertificateAllowed(cert)) {
            throw new FailedLoginException(
                    "Certificate subject does not match pattern " + this.regExSubjectDnPattern.pattern());
        }
        if (this.checkKeyUsage && !isValidKeyUsage(cert)) {
            throw new FailedLoginException(
                    "Certificate keyUsage constraint forbids SSL client authentication.");
        }
    } else {
        // Check pathLength for CA cert
        if (pathLength == Integer.MAX_VALUE && this.maxPathLengthAllowUnspecified != true) {
            throw new FailedLoginException("Unlimited certificate path length not allowed by configuration.");
        } else if (pathLength > this.maxPathLength && pathLength < Integer.MAX_VALUE) {
            throw new FailedLoginException(String.format(
                    "Certificate path length %s exceeds maximum value %s.", pathLength, this.maxPathLength));
        }
    }
}
 
Example 13
Project: springboot-shiro-cas-mybatis   File: AbstractCRLRevocationCheckerTests.java   View source code 6 votes vote down vote up
/**
 * Test method for {@link AbstractCRLRevocationChecker#check(X509Certificate)}.
 */
@Test
public void checkCertificate() {
    try {
        for (final 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) {
            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 14
Project: lams   File: HMAC_SHA1.java   View source code 6 votes vote down vote up
private byte[] computeSignature(String baseString)
        throws GeneralSecurityException, UnsupportedEncodingException {
    SecretKey key = null;
    synchronized (this) {
        if (this.key == null) {
            String keyString = OAuth.percentEncode(getConsumerSecret())
                    + '&' + OAuth.percentEncode(getTokenSecret());
            byte[] keyBytes = keyString.getBytes(ENCODING);
            this.key = new SecretKeySpec(keyBytes, MAC_NAME);
        }
        key = this.key;
    }
    Mac mac = Mac.getInstance(MAC_NAME);
    mac.init(key);
    byte[] text = baseString.getBytes(ENCODING);
    return mac.doFinal(text);
}
 
Example 15
Project: springboot-shiro-cas-mybatis   File: ThresholdExpiredCRLRevocationPolicyTests.java   View source code 6 votes vote down vote up
/**
 * Test method for {@link ThresholdExpiredCRLRevocationPolicy#apply(java.security.cert.X509CRL)}.
 */
@Test
public void verifyApply() {
    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 16
Project: TARA-Server   File: TaraAuthenticationHandler.java   View source code 6 votes vote down vote up
@Override
protected HandlerResult doAuthentication(Credential credential) throws GeneralSecurityException, PreventedException {
    final Map<String, Object> map = new LinkedHashMap<>();
    if (credential instanceof TaraCredential) {
        TaraCredential taraCredential = (TaraCredential) credential;
        this.putIfNotEmpty(map, "principalCode", taraCredential.getPrincipalCode());
        this.putIfNotEmpty(map, "firstName", taraCredential.getFirstName());
        this.putIfNotEmpty(map, "lastName", taraCredential.getLastName());
        if (AuthenticationType.MobileID.equals(taraCredential.getType())) {
            this.putIfNotEmpty(map, "mobileNumber", taraCredential.getMobileNumber());
        }
        return this.createHandlerResult(credential, this.principalFactory
            .createPrincipal(taraCredential.getId(), map), new ArrayList<>());
    }
    return null;
}
 
Example 17
Project: aos-FileCoreLibrary   File: NtlmPasswordAuthentication.java   View source code 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 18
Project: hadoop-oss   File: KMSClientProvider.java   View source code 6 votes vote down vote up
private HttpURLConnection configureConnection(HttpURLConnection conn)
    throws IOException {
  if (sslFactory != null) {
    HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
    try {
      httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory());
    } catch (GeneralSecurityException ex) {
      throw new IOException(ex);
    }
    httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier());
  }
  return conn;
}
 
Example 19
Project: cas-server-4.2.1   File: PolicyBasedAuthenticationManager.java   View source code 6 votes vote down vote up
/**
 * Authenticate and resolve principal.
 *
 * @param builder the builder
 * @param credential the credential
 * @param resolver the resolver
 * @param handler the handler
 * @throws GeneralSecurityException the general security exception
 * @throws PreventedException the prevented exception
 */
private void authenticateAndResolvePrincipal(final AuthenticationBuilder builder, final Credential credential,
                                             final PrincipalResolver resolver, final AuthenticationHandler handler)
        throws GeneralSecurityException, PreventedException {

    final Principal principal;
    final HandlerResult result = handler.authenticate(credential);
    builder.addSuccess(handler.getName(), result);
    logger.info("{} successfully authenticated {}", handler.getName(), credential);
    if (resolver == null) {
        principal = result.getPrincipal();
        logger.debug(
                "No resolver configured for {}. Falling back to handler principal {}",
                handler.getName(),
                principal);
    } else {
        principal = resolvePrincipal(handler.getName(), resolver, credential);
    }
    // Must avoid null principal since AuthenticationBuilder/ImmutableAuthentication
    // require principal to be non-null
    if (principal != null) {
        builder.setPrincipal(principal);
    }
}
 
Example 20
Project: privacyidea-authenticator   File: SecretKeyWrapper.java   View source code 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static void generateKeyPair(Context context, String alias)
        throws GeneralSecurityException {
    final Calendar start = new GregorianCalendar();
    final Calendar end = new GregorianCalendar();
    end.add(Calendar.YEAR, 100);
    final KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
    final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
            .setAlias(alias)
            .setSubject(new X500Principal("CN=" + alias))
            .setSerialNumber(BigInteger.ONE)
            .setStartDate(start.getTime())
            .setEndDate(end.getTime())
            .build();
    gen.initialize(spec);
    gen.generateKeyPair();
}
 
Example 21
Project: Nird2   File: BlogPostValidatorTest.java   View source code 6 votes vote down vote up
@Test
public void testValidateProperBlogComment()
		throws IOException, GeneralSecurityException {
	// comment, parent_original_id, parent_id, signature
	String comment = "This is a blog comment";
	MessageId pOriginalId = new MessageId(TestUtils.getRandomId());
	MessageId currentId = new MessageId(TestUtils.getRandomId());
	final byte[] sigBytes = TestUtils.getRandomBytes(42);
	BdfList m = BdfList.of(COMMENT.getInt(), comment, pOriginalId,
			currentId, sigBytes);

	BdfList signed = BdfList.of(blog.getId(), message.getTimestamp(),
			comment, pOriginalId, currentId);
	expectCrypto(blog, SIGNING_LABEL_COMMENT, signed, sigBytes);
	final BdfDictionary result =
			validator.validateMessage(message, group, m).getDictionary();

	assertEquals(comment, result.getString(KEY_COMMENT));
	assertEquals(authorDict, result.getDictionary(KEY_AUTHOR));
	assertEquals(pOriginalId.getBytes(),
			result.getRaw(KEY_ORIGINAL_PARENT_MSG_ID));
	assertEquals(currentId.getBytes(), result.getRaw(KEY_PARENT_MSG_ID));
	assertFalse(result.getBoolean(KEY_READ));
	context.assertIsSatisfied();
}
 
Example 22
Project: incubator-netbeans   File: Installer.java   View source code 6 votes vote down vote up
@Override
protected void addMoreLogs(List<? super String> params, boolean openPasswd) {
    if ((reportPanel != null) && (report)){
        params.add(reportPanel.getSummary());
        params.add(reportPanel.getComment());
        try {
            char[] passwd = reportPanel.getPasswdChars();
            if ((openPasswd) && (passwd.length != 0) && (!reportPanel.asAGuest())){
                String pwd = new String(passwd);
                pwd = PasswdEncryption.encrypt(pwd);
                params.add(pwd);
            } else {
                params.add("*********");// NOI18N
            }
        } catch (GeneralSecurityException | IOException exc) {
            LOG.log(Level.WARNING, "PASSWORD ENCRYPTION ERROR", exc);// NOI18N
        }
    }
}
 
Example 23
Project: lams   File: RSA_SHA1.java   View source code 6 votes vote down vote up
private byte[] sign(byte[] message) throws GeneralSecurityException {
    if (privateKey == null) {
        throw new IllegalStateException("need to set private key with " +
                                        "OAuthConsumer.setProperty when " +
                                        "generating RSA-SHA1 signatures.");
    }
    Signature signer = Signature.getInstance("SHA1withRSA");
    signer.initSign(privateKey);
    signer.update(message);
    return signer.sign();
}
 
Example 24
Project: sample-acmegifts   File: JWTVerifier.java   View source code 6 votes vote down vote up
public String createJWT(String username, Set<String> groups)
    throws GeneralSecurityException, IOException {
  // Create and Base64 encode the header portion of the JWT
  JsonObject headerObj =
      Json.createObjectBuilder()
          .add("alg", "RS256") /* Algorithm used */
          .add("typ", "JWT") /* Type of token */
          // .add("kid", "default") /* Hint about which key to use to sign, but the signature is
          // invalid when I include this. */
          .build();
  String headerEnc = Base64Utility.encode(headerObj.toString().getBytes(), true);

  // Create and Base64 encode the claims portion of the JWT
  JsonObject claimsObj =
      Json.createObjectBuilder()
          .add("exp", (System.currentTimeMillis() / 1000) + 300) /* Expire time */
          .add("iat", (System.currentTimeMillis() / 1000)) /* Issued time */
          .add("aud", "acmeGifts") /* Audience */
          .add("jti", Long.toHexString(System.nanoTime())) /* Unique value */
          .add("sub", username) /* Subject */
          .add("upn", username) /* Subject again */
          .add("iss", JWT_ISSUER) /* Issuer */
          .add("groups", getGroupArray(groups)) /* Group list */
          .build();
  String claimsEnc = Base64Utility.encode(claimsObj.toString().getBytes(), true);
  String headerClaimsEnc = headerEnc + "." + claimsEnc;

  // Open the keystore that the server will use to validate the JWT
  KeyStore ks = KeyStore.getInstance("JCEKS");
  InputStream ksStream = this.getClass().getResourceAsStream("/keystore.jceks");
  char[] password = new String("secret").toCharArray();
  ks.load(ksStream, password);

  // Get the private key to use to sign the JWT.  Normally we would not do this but
  // we are pretending to be the user service here.
  KeyStore.ProtectionParameter keyPassword = new KeyStore.PasswordProtection(password);
  KeyStore.PrivateKeyEntry privateKeyEntry =
      (KeyStore.PrivateKeyEntry) ks.getEntry("default", keyPassword);
  PrivateKey privateKey = privateKeyEntry.getPrivateKey();

  // Sign the JWT
  Signature sig = Signature.getInstance(JWT_ALGORITHM);
  sig.initSign(privateKey);
  sig.update(headerClaimsEnc.getBytes());
  String sigEnc = Base64Utility.encode(sig.sign(), true);

  // Lets just check......
  String jwtEnc = headerClaimsEnc + "." + sigEnc;
  java.security.cert.Certificate cert = ks.getCertificate("default");
  PublicKey publicKey = cert.getPublicKey();
  validateJWT("Bearer " + jwtEnc, publicKey);

  // Return the complete JWT (header, claims, signature).
  return jwtEnc;
}
 
Example 25
Project: springboot-shiro-cas-mybatis   File: CRLDistributionPointRevocationCheckerTests.java   View source code 6 votes vote down vote up
/**
 * Creates a new test instance with given parameters.
 *
 * @param checker Revocation checker instance.
 * @param expiredCRLPolicy Policy instance for handling expired CRL data.
 * @param certFiles File names of certificates to check.
 * @param crlFile File name of CRL file to serve out.
 * @param expected Expected result of check; null to indicate expected success.
 */
public CRLDistributionPointRevocationCheckerTests(
        final CRLDistributionPointRevocationChecker checker,
        final RevocationPolicy<X509CRL> expiredCRLPolicy,
        final String[] certFiles,
        final String crlFile,
        final GeneralSecurityException expected) throws Exception {

    super(certFiles, expected);

    final File file = new File(System.getProperty("java.io.tmpdir"), "ca.crl");
    if (file.exists()) {
        file.delete();
    }
    final OutputStream out = new FileOutputStream(file);
    IOUtils.copy(new ClassPathResource(crlFile).getInputStream(), out);

    this.checker = checker;
    this.checker.setExpiredCRLPolicy(expiredCRLPolicy);
    this.checker.init();
    this.webServer = new MockWebServer(8085, new FileSystemResource(file), "text/plain");
    logger.debug("Web server listening on port 8085 serving file {}", crlFile);
}
 
Example 26
Project: format-preserving-encryption-java   File: DefaultPseudoRandomFunction.java   View source code 5 votes vote down vote up
public byte[] apply(byte[] plain) {
    try {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, KEY_ALGORITHM_NAME), new IvParameterSpec(initializationVector));
        byte[] result = cipher.doFinal(plain);
        return Arrays.copyOfRange(result, result.length - initializationVector.length, result.length);
    } catch (GeneralSecurityException e) {
        throw new SecurityException(e);
    }

}
 
Example 27
Project: quickstart   File: AssertionGenerator.java   View source code 5 votes vote down vote up
/**
 * Extracts private key (predictive_services.pem) contents
 */
private static PrivateKey getPrivateKey(String privateKeyBase64) {
  String privKeyPEM = privateKeyBase64.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
  privKeyPEM = privKeyPEM.replace("\n-----END RSA PRIVATE KEY-----", "");

  // Base64 decode the data
  byte[] encoded = Base64.decodeBase64(privKeyPEM);

  try {
    DerInputStream derReader = new DerInputStream(encoded);
    DerValue[] seq = derReader.getSequence(0);

    if (seq.length < 9) {
      throw new GeneralSecurityException("Could not read private key");
    }

    // skip version seq[0];
    BigInteger modulus = seq[1].getBigInteger();
    BigInteger publicExp = seq[2].getBigInteger();
    BigInteger privateExp = seq[3].getBigInteger();
    BigInteger primeP = seq[4].getBigInteger();
    BigInteger primeQ = seq[5].getBigInteger();
    BigInteger expP = seq[6].getBigInteger();
    BigInteger expQ = seq[7].getBigInteger();
    BigInteger crtCoeff = seq[8].getBigInteger();

    RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp,
        primeP, primeQ, expP, expQ, crtCoeff);

    KeyFactory factory = KeyFactory.getInstance("RSA");
    return factory.generatePrivate(keySpec);
  } catch (IOException | GeneralSecurityException e) {
    Throwables.propagate(e);
  }
  return null;
}
 
Example 28
Project: hadoop   File: EagerKeyGeneratorKeyProviderCryptoExtension.java   View source code 5 votes vote down vote up
@Override
public KeyVersion
decryptEncryptedKey(EncryptedKeyVersion encryptedKeyVersion)
    throws IOException, GeneralSecurityException {
  return keyProviderCryptoExtension.decryptEncryptedKey(
      encryptedKeyVersion);
}
 
Example 29
Project: javaide   File: ZipSigner.java   View source code 5 votes vote down vote up
/**
 * Write the signature file to the given output stream.
 */
private void generateSignatureFile(Manifest manifest, OutputStream out)
        throws IOException, GeneralSecurityException {
    out.write(("Signature-Version: 1.0\r\n").getBytes());
    out.write(("Created-By: 1.0 (Android SignApk)\r\n").getBytes());


    // BASE64Encoder base64 = new BASE64Encoder();
    MessageDigest md = MessageDigest.getInstance("SHA1");
    PrintStream print = new PrintStream(
            new DigestOutputStream(new ByteArrayOutputStream(), md),
            true, "UTF-8");

    // Digest of the entire manifest
    manifest.write(print);
    print.flush();

    out.write(("SHA1-Digest-Manifest: " + Base64.encode(md.digest()) + "\r\n\r\n").getBytes());

    Map<String, Attributes> entries = manifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
        if (canceled) break;
        progressHelper.progress(ProgressEvent.PRORITY_NORMAL, resourceAdapter.getString(ResourceAdapter.Item.GENERATING_SIGNATURE_FILE));
        // Digest of the manifest stanza for this entry.
        String nameEntry = "Name: " + entry.getKey() + "\r\n";
        print.print(nameEntry);
        for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
            print.print(att.getKey() + ": " + att.getValue() + "\r\n");
        }
        print.print("\r\n");
        print.flush();

        out.write(nameEntry.getBytes());
        out.write(("SHA1-Digest: " + Base64.encode(md.digest()) + "\r\n\r\n").getBytes());
    }

}
 
Example 30
Project: DWSurvey   File: CryptoUtils.java   View source code 5 votes vote down vote up
/**
 * 生成HMAC-SHA1密钥,返回字节数组,长度为160位(20字节).
 * HMAC-SHA1算法对密钥无特殊要求, RFC2401建议最少长度为160位(20字节).
 */
public static byte[] generateMacSha1Key() {
	try {
		KeyGenerator keyGenerator = KeyGenerator.getInstance(HMACSHA1);
		keyGenerator.init(DEFAULT_HMACSHA1_KEYSIZE);
		SecretKey secretKey = keyGenerator.generateKey();
		return secretKey.getEncoded();
	} catch (GeneralSecurityException e) {
		throw ExceptionUtils.unchecked(e);
	}
}
 
Example 31
Project: OpenJSharp   File: AesDkCrypto.java   View source code 5 votes vote down vote up
/**
 * Decrypts data using specified key and initial vector.
 * @param baseKey encryption key to use
 * @param ciphertext  encrypted data to be decrypted
 * @param usage ignored
 */
public byte[] decryptRaw(byte[] baseKey, int usage, byte[] ivec,
    byte[] ciphertext, int start, int len)
    throws GeneralSecurityException {

    if (!KeyUsage.isValid(usage)) {
        throw new GeneralSecurityException("Invalid key usage number: "
                                            + usage);
    }
    byte[] output = decryptCTS(baseKey, usage, ivec, ciphertext,
                                    start, len, false);
    return output;
}
 
Example 32
Project: springboot-shiro-cas-mybatis   File: TestOneTimePasswordAuthenticationHandler.java   View source code 5 votes vote down vote up
@Override
public HandlerResult authenticate(final Credential credential)
        throws GeneralSecurityException, PreventedException {
    final OneTimePasswordCredential otp = (OneTimePasswordCredential) credential;
    final String valueOnRecord = credentialMap.get(otp.getId());
    if (otp.getPassword().equals(credentialMap.get(otp.getId()))) {
        return new DefaultHandlerResult(this, new BasicCredentialMetaData(otp),
                new DefaultPrincipalFactory().createPrincipal(otp.getId()));
    }
    throw new FailedLoginException();
}
 
Example 33
Project: OpenJSharp   File: HmacSha1Des3KdCksumType.java   View source code 5 votes vote down vote up
/**
 * Calculates keyed checksum.
 * @param data the data used to generate the checksum.
 * @param size length of the data.
 * @param key the key used to encrypt the checksum.
 * @return keyed checksum.
 */
public byte[] calculateKeyedChecksum(byte[] data, int size, byte[] key,
    int usage) throws KrbCryptoException {

     try {
         return Des3.calculateChecksum(key, usage, data, 0, size);
     } catch (GeneralSecurityException e) {
         KrbCryptoException ke = new KrbCryptoException(e.getMessage());
         ke.initCause(e);
         throw ke;
     }
}
 
Example 34
Project: Nird2   File: GroupInvitationValidator.java   View source code 5 votes vote down vote up
private BdfMessageContext validateInviteMessage(Message m, BdfList body)
		throws FormatException {
	checkSize(body, 7);
	String groupName = body.getString(1);
	checkLength(groupName, 1, MAX_GROUP_NAME_LENGTH);
	String creatorName = body.getString(2);
	checkLength(creatorName, 1, MAX_AUTHOR_NAME_LENGTH);
	byte[] creatorPublicKey = body.getRaw(3);
	checkLength(creatorPublicKey, 1, MAX_PUBLIC_KEY_LENGTH);
	byte[] salt = body.getRaw(4);
	checkLength(salt, GROUP_SALT_LENGTH);
	String message = body.getOptionalString(5);
	checkLength(message, 1, MAX_GROUP_INVITATION_MSG_LENGTH);
	byte[] signature = body.getRaw(6);
	checkLength(signature, 1, MAX_SIGNATURE_LENGTH);
	// Create the private group
	Author creator = authorFactory.createAuthor(creatorName,
			creatorPublicKey);
	PrivateGroup privateGroup = privateGroupFactory.createPrivateGroup(
			groupName, creator, salt);
	// Verify the signature
	BdfList signed = BdfList.of(
			m.getTimestamp(),
			m.getGroupId(),
			privateGroup.getId()
	);
	try {
		clientHelper.verifySignature(SIGNING_LABEL_INVITE, signature,
				creatorPublicKey, signed);
	} catch (GeneralSecurityException e) {
		throw new FormatException();
	}
	// Create the metadata
	BdfDictionary meta = messageEncoder.encodeMetadata(INVITE,
			privateGroup.getId(), m.getTimestamp(), false, false, false,
			false, false);
	return new BdfMessageContext(meta);
}
 
Example 35
Project: oneops   File: CMSClient.java   View source code 5 votes vote down vote up
/**
 * Gets the action orders.
 *
 * @param exec the exec
 * @return the action orders
 * @throws GeneralSecurityException the general security exception
 */

public void getActionOrders(DelegateExecution exec) throws GeneralSecurityException {
    CmsOpsProcedure proc = (CmsOpsProcedure) exec.getVariable("proc");
    Integer execOrder = (Integer) exec.getVariable(CmsConstants.EXEC_ORDER);
    logger.info("Geting action orders for procedure id = " + proc.getProcedureId());
    long startTime = System.currentTimeMillis();
    try {
        //CmsActionOrderSimple[] aos = retryTemplate.execute(retryContext -> restTemplate.getForObject(serviceUrl + "/cm/ops/procedures/{procedureId}/actionorders?execorder={execOrder}&state=pending", CmsActionOrderSimple[].class, proc.getProcedureId(), execOrder));
    	List<CmsActionOrderSimple> aoList = cmsWoProvider.getActionOrdersSimple(proc.getProcedureId(), OpsProcedureState.pending, execOrder);
    	logger.info("Got " + aoList.size() + " action orders for procedure id = " + proc.getProcedureId() + "; Time taken: " + (System.currentTimeMillis() - startTime) + "ms"  );
    	for (CmsActionOrderSimple ao : aoList) {
          logger.info("Testing ao  " + ao.getCiId() + " bytes length : " + gson.toJson(ao).getBytes().length);
            decryptAo(ao);
        }
        exec.setVariable("cmsaos", aoList);
        if (exec.getVariable("procanchor") == null) {
            CmsCI procAnchorCI = cmsCmProcessor.getCiById(proc.getCiId());
            		//retryTemplate.execute(retryContext -> restTemplate.getForObject(serviceUrl + "/cm/cis/{ciId}", CmsCI.class, proc.getCiId()));
            exec.setVariable("procanchor", procAnchorCI);
        }
    } catch (CmsBaseException rce) {
        logger.error(rce);
        rce.printStackTrace();
        proc.setProcedureState(OpsProcedureState.failed);
        exec.setVariable("proc", proc);
    }
}
 
Example 36
Project: openjdk-jdk10   File: Des3DkCrypto.java   View source code 5 votes vote down vote up
public byte[] stringToKey(char[] salt) throws GeneralSecurityException {
    byte[] saltUtf8 = null;
    try {
        saltUtf8 = charToUtf8(salt);
        return stringToKey(saltUtf8, null);
    } finally {
        if (saltUtf8 != null) {
            Arrays.fill(saltUtf8, (byte)0);
        }
        // Caller responsible for clearing its own salt
    }
}
 
Example 37
Project: Nird2   File: KeyAgreementProtocol.java   View source code 5 votes vote down vote up
private SecretKey deriveSharedSecret(byte[] theirPublicKey)
		throws AbortException {
	try {
		return crypto.deriveSharedSecret(theirPublicKey, ourKeyPair, alice);
	} catch (GeneralSecurityException e) {
		throw new AbortException(e);
	}
}
 
Example 38
Project: TIIEHenry-Android-SDK   File: AESUtils.java   View source code 5 votes vote down vote up
/**
 * Decrypt and decode ciphertext using 256-bit AES with key generated from password
 *
 * @param password used to generated key
 * @param base64EncodedCipherText the encrpyted message encoded with base64
 * @return message in Plain text (String UTF-8)
 * @throws GeneralSecurityException if there's an issue decrypting
 */
public static String decrypt(final String password, String base64EncodedCipherText)
        throws GeneralSecurityException {

    try {
        final SecretKeySpec key = generateKey(password);
        byte[] decodedCipherText = Base64.decode(base64EncodedCipherText, Base64.NO_WRAP);
        byte[] decryptedBytes = decrypt(key, ivBytes, decodedCipherText);
        String message = new String(decryptedBytes, CHARSET);
        return message;
    } catch (UnsupportedEncodingException e) {
        throw new GeneralSecurityException(e);
    }
}
 
Example 39
Project: OpenJSharp   File: ArcFourHmacEType.java   View source code 5 votes vote down vote up
public byte[] decrypt(byte[] cipher, byte[] key, byte[] ivec, int usage)
    throws KrbApErrException, KrbCryptoException {
    try {
        return ArcFourHmac.decrypt(key, usage, ivec, cipher, 0, cipher.length);
    } catch (GeneralSecurityException e) {
        KrbCryptoException ke = new KrbCryptoException(e.getMessage());
        ke.initCause(e);
        throw ke;
    }
}
 
Example 40
Project: GitHub   File: CustomTrust.java   View source code 5 votes vote down vote up
private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
  try {
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream in = null; // By convention, 'null' creates an empty key store.
    keyStore.load(in, password);
    return keyStore;
  } catch (IOException e) {
    throw new AssertionError(e);
  }
}