微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java.security.GeneralSecurityException的实例源码

项目:hadoop-oss    文件AbstractReEncryptionKeyProvider.java   
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);
}
项目:ipack    文件EnvelopedDataHelper.java   
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);
    }
}
项目:openjdk-jdk10    文件AesDkCrypto.java   
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,4);
    }

    byte[] tmpKey = randomToKey(PBKDF2(secret,salt,iter_count,getKeySeedLength()));
    byte[] result = dk(tmpKey,KERBEROS_CONSTANT);
    return result;
}
项目:Nird2    文件BlogPostFactoryImpl.java   
@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(),parentCurrentId,sig);
    return clientHelper.createMessage(groupId,message);
}
项目:oscm    文件AESEncrypter.java   
/**
 * 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);
}
项目:cas-5.1.0    文件AbstractPac4jAuthenticationHandler.java   
/**
 * 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);
}
项目:alfresco-core    文件EncryptingOutputStream.java   
@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();
}
项目:Wurst-MC-1.12    文件Encryption.java   
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);
    }
}
项目:oneops    文件CMSClientTest.java   
@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;
    }
}
项目:boohee_v5.6    文件bu.java   
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));
        }
    }
}
项目:cas4.0.x-server-wechat    文件X509CredentialsAuthenticationHandler.java   
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));
        }
    }
}
项目:springboot-shiro-cas-mybatis    文件AbstractCRLRevocationCheckerTests.java   
/**
 * 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));
        }
    }
}
项目:lams    文件HMAC_SHA1.java   
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);
}
项目:springboot-shiro-cas-mybatis    文件ThresholdExpiredCRLRevocationPolicyTests.java   
/**
 * 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.isAssignableFrom(actualClass));
        }
    }
}
项目:Tara-Server    文件TaraAuthenticationHandler.java   
@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;
}
项目:aos-FileCoreLibrary    文件NtlmPasswordAuthentication.java   
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,8);
        System.arraycopy(md5.digest(),sessionHash,8);
    } catch (GeneralSecurityException gse) {
        if (log.level > 0)
            gse.printstacktrace(log);
        throw new RuntimeException("MD5",gse);
    }

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

    return ntResponse;
}
项目:CrashCoin    文件Main.java   
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();

}
项目:hadoop-oss    文件KMSClientProvider.java   
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;
}
项目:cas-server-4.2.1    文件PolicyBasedAuthenticationManager.java   
/**
 * 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 {}",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);
    }
}
项目:privacyidea-authenticator    文件SecretKeyWrapper.java   
@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();
}
项目:Nird2    文件BlogPostValidatorTest.java   
@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(),pOriginalId,currentId,sigBytes);

    BdfList signed = BdfList.of(blog.getId(),message.getTimestamp(),currentId);
    expectCrypto(blog,SIGNING_LABEL_COMMENT,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();
}
项目:incubator-netbeans    文件Installer.java   
@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
        }
    }
}
项目:lams    文件RSA_SHA1.java   
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();
}
项目:sample-acmegifts    文件JWTVerifier.java   
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;
}
项目:springboot-shiro-cas-mybatis    文件CRLdistributionPointRevocationCheckerTests.java   
/**
 * 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);
}
项目:format-preserving-encryption-java    文件DefaultPseudoRandomFunction.java   
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);
    }

}
项目:quickstart    文件AssertionGenerator.java   
/**
 * 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;
}
项目:hadoop    文件EagerKeyGeneratorKeyProviderCryptoExtension.java   
@Override
public keyversion
decryptEncryptedKey(Encryptedkeyversion encryptedkeyversion)
    throws IOException,GeneralSecurityException {
  return keyProviderCryptoExtension.decryptEncryptedKey(
      encryptedkeyversion);
}
项目:javaide    文件ZipSigner.java   
/**
 * 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());
    }

}
项目:DWSurvey    文件CryptoUtils.java   
/**
 * 生成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);
    }
}
项目:Openjsharp    文件AesDkCrypto.java   
/**
 * 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;
}
项目:springboot-shiro-cas-mybatis    文件TestOneTimePasswordAuthenticationHandler.java   
@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();
}
项目:Openjsharp    文件HmacSha1Des3KdCksumType.java   
/**
 * 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,data,size);
     } catch (GeneralSecurityException e) {
         KrbCryptoException ke = new KrbCryptoException(e.getMessage());
         ke.initCause(e);
         throw ke;
     }
}
项目:Nird2    文件GroupInvitationValidator.java   
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,MAX_AUTHOR_NAME_LENGTH);
    byte[] creatorPublicKey = body.getRaw(3);
    checkLength(creatorPublicKey,MAX_PUBLIC_KEY_LENGTH);
    byte[] salt = body.getRaw(4);
    checkLength(salt,GROUP_SALT_LENGTH);
    String message = body.getoptionalString(5);
    checkLength(message,MAX_GROUP_INVITATION_MSG_LENGTH);
    byte[] signature = body.getRaw(6);
    checkLength(signature,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);
    return new BdfMessageContext(Meta);
}
项目:oneops    文件CMSClient.java   
/**
 * 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);
    }
}
项目:openjdk-jdk10    文件Des3DkCrypto.java   
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
    }
}
项目:Nird2    文件KeyAgreementProtocol.java   
private SecretKey deriveSharedSecret(byte[] theirPublicKey)
        throws AbortException {
    try {
        return crypto.deriveSharedSecret(theirPublicKey,ourKeyPair,alice);
    } catch (GeneralSecurityException e) {
        throw new AbortException(e);
    }
}
项目:TIIEHenry-Android-SDK    文件AESUtils.java   
/**
 * 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);
    }
}
项目:Openjsharp    文件ArcFourHmacEType.java   
public byte[] decrypt(byte[] cipher,int usage)
    throws KrbApErrException,KrbCryptoException {
    try {
        return ArcFourHmac.decrypt(key,cipher,cipher.length);
    } catch (GeneralSecurityException e) {
        KrbCryptoException ke = new KrbCryptoException(e.getMessage());
        ke.initCause(e);
        throw ke;
    }
}
项目:GitHub    文件CustomTrust.java   
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);
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。