Java 类java.security.NoSuchProviderException 实例源码

项目:xitk    文件:KeyUtil.java   
public static KeyPair generateECKeypair(ASN1ObjectIdentifier curveId, SecureRandom random)
        throws NoSuchAlgorithmException, NoSuchProviderException,
            InvalidAlgorithmParameterException {
    ParamUtil.requireNonNull("curveId", curveId);

    ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveId.getId());
    KeyPairGenerator kpGen = getKeyPairGenerator("EC");
    synchronized (kpGen) {
        if (random == null) {
            kpGen.initialize(spec);
        } else {
            kpGen.initialize(spec, random);
        }
        return kpGen.generateKeyPair();
    }
}
项目:mi-firma-android    文件:JseCryptoHelper.java   
@Override
public final byte[] doEcDh(final Key privateKey,
                     final byte[] publicKey,
                     final EcCurve curveName) throws NoSuchAlgorithmException,
                                                     InvalidKeyException,
                                                     InvalidKeySpecException {

    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.insertProviderAt(new BouncyCastleProvider(), 1);
    }
    KeyAgreement ka = null;
    try {
        ka = KeyAgreement.getInstance(ECDH, BouncyCastleProvider.PROVIDER_NAME);

    }
    catch (final NoSuchProviderException e) {
        ka = KeyAgreement.getInstance(ECDH);
    }
    ka.init(privateKey);
    ka.doPhase(loadEcPublicKey(publicKey, curveName), true);
    return ka.generateSecret();
}
项目:FingerPrint-Authentication-With-React-Native-Android    文件:Decrypter.java   
public String decrypt(final String alias, final byte[] encryptedData, Context appContext)
        throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException,
        NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException,
        BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {

    final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
    String IV = PreferenceHelper.getPrefernceHelperInstace().getString(appContext, "IV", "");

    if (null != IV && !IV.isEmpty()) {
        byte[] encryptionIv = Base64.decode(IV, Base64.DEFAULT);
        Log.e("Decrypter", "IV : " + IV + " IV size " + encryptionIv.length);
        final GCMParameterSpec spec = new GCMParameterSpec(128, encryptionIv);
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(alias), spec);
        return new String(cipher.doFinal(encryptedData), "UTF-8");
    } else {
        return "{}";
    }
}
项目:ipack    文件:EnvelopedDataHelper.java   
AlgorithmParameters createAlgorithmParameters(ASN1ObjectIdentifier algorithm)
    throws NoSuchAlgorithmException, NoSuchProviderException
{
    String algorithmName = (String)BASE_CIPHER_NAMES.get(algorithm);

    if (algorithmName != null)
    {
        try
        {
            // this is reversed as the Sun policy files now allow unlimited strength RSA
            return helper.createAlgorithmParameters(algorithmName);
        }
        catch (NoSuchAlgorithmException e)
        {
            // Ignore
        }
    }
    return helper.createAlgorithmParameters(algorithm.getId());
}
项目:encryptedprefs    文件:Vault.java   
@TargetApi(Build.VERSION_CODES.M)
public SecretKey getSymmetricKey(String alias)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException,
        CertificateException, KeyStoreException, UnrecoverableEntryException {

    ESLog.v("%s=>getSymmetricKey(%s)", getClass().getSimpleName(), alias);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        KeyStore ks = KeyStore.getInstance(KEYSTORE_PROVIDER);
        ks.load(null);

        Key key = ks.getKey(alias, null);
        if (key != null) {

            ESLog.i("SecretKey found in KeyStore.");
            return (SecretKey) key;
        }
        ESLog.w("SecretKey not found in KeyStore.");
        return null;
    }

    UnsupportedOperationException unsupportedOperationException = new UnsupportedOperationException();
    ESLog.wtf("Unsupported operation. This code should be called only from M onwards.", unsupportedOperationException.getCause());
    throw unsupportedOperationException;
}
项目:mi-firma-android    文件:JseCryptoHelper.java   
private static Key loadEcPublicKey(final byte [] pubKey,
                                      final EcCurve curveName) throws NoSuchAlgorithmException,
                                                                      InvalidKeySpecException {
    final ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveName.toString());
    KeyFactory kf;
    try {
        kf = KeyFactory.getInstance(ECDH, BouncyCastleProvider.PROVIDER_NAME);
    }
    catch (final NoSuchProviderException e) {
        kf = KeyFactory.getInstance(ECDH);
    }
    final ECNamedCurveSpec params = new ECNamedCurveSpec(curveName.toString(), spec.getCurve(), spec.getG(), spec.getN());
    final ECPoint point =  ECPointUtil.decodePoint(params.getCurve(), pubKey);
    final java.security.spec.ECPublicKeySpec pubKeySpec = new java.security.spec.ECPublicKeySpec(point, params);
    return kf.generatePublic(pubKeySpec);
}
项目:talchain    文件:TransactionTest.java   
@Test /* sign transaction  https://tools.ietf.org/html/rfc6979 */
public void test1() throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, IOException {

    //python taken exact data
    String txRLPRawData = "a9e880872386f26fc1000085e8d4a510008203e89413978aee95f38490e9769c39b2773ed763d9cd5f80";
    // String txRLPRawData = "f82804881bc16d674ec8000094cd2a3d9f938e13cd947ec05abc7fe734df8dd8268609184e72a0006480";

    byte[] cowPrivKey = Hex.decode("c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4");
    ECKey key = ECKey.fromPrivate(cowPrivKey);

    byte[] data = Hex.decode(txRLPRawData);

    // step 1: serialize + RLP encode
    // step 2: hash = keccak(step1)
    byte[] txHash = HashUtil.sha3(data);

    String signature = key.doSign(txHash).toBase64();
    System.out.println(signature);
}
项目:wolfcrypt-jni    文件:WolfCryptMessageDigestShaTest.java   
@Test
public void testShaSingleByteUpdate()
    throws NoSuchProviderException, NoSuchAlgorithmException {

    String input = "Hello World";
    byte[] inArray = input.getBytes();
    final byte expected[] = new byte[] {
        (byte)0x0a, (byte)0x4d, (byte)0x55, (byte)0xa8,
        (byte)0xd7, (byte)0x78, (byte)0xe5, (byte)0x02,
        (byte)0x2f, (byte)0xab, (byte)0x70, (byte)0x19,
        (byte)0x77, (byte)0xc5, (byte)0xd8, (byte)0x40,
        (byte)0xbb, (byte)0xc4, (byte)0x86, (byte)0xd0
    };

    byte[] output;

    MessageDigest sha = MessageDigest.getInstance("SHA-1", "wolfJCE");

    for (int i = 0; i < inArray.length; i++) {
        sha.update(inArray[i]);
    }
    output = sha.digest();
    assertEquals(expected.length, output.length);
    assertArrayEquals(expected, output);
}
项目:wolfcrypt-jni    文件:WolfCryptKeyPairGeneratorTest.java   
@Test
public void testKeyPairGeneratorEccMultipleInits()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           InvalidAlgorithmParameterException {

    if (enabledCurves.size() > 0) {

        KeyPairGenerator kpg =
            KeyPairGenerator.getInstance("EC", "wolfJCE");

        ECGenParameterSpec ecSpec =
            new ECGenParameterSpec(enabledCurves.get(0));

        kpg.initialize(ecSpec);
        kpg.initialize(ecSpec);
    }
}
项目:wolfcrypt-jni    文件:WolfCryptRandomTest.java   
@Test
public void testGenerateSeed()
    throws NoSuchProviderException, NoSuchAlgorithmException {

    byte[] valuesA = new byte[128];
    byte[] valuesB = new byte[128];

    SecureRandom rand = SecureRandom.getInstance("HashDRBG", "wolfJCE");

    valuesA = rand.generateSeed(valuesA.length);
    for (int i = 0; i < 10; i++) {
        valuesB = rand.generateSeed(valuesB.length);

        if(Arrays.equals(valuesA, valuesB))
            fail("SecureRandom generated two equal consecutive arrays");

        valuesA = Arrays.copyOf(valuesB, valuesB.length);
    }
}
项目:openjdk-jdk10    文件:TestCipher.java   
public void runAll() throws InvalidKeyException,
        NoSuchPaddingException, InvalidAlgorithmParameterException,
        ShortBufferException, IllegalBlockSizeException,
        BadPaddingException, NoSuchAlgorithmException,
        NoSuchProviderException {

    for (String mode : MODES) {
        for (String padding : PADDINGS) {
            if (!isMultipleKeyLengthSupported()) {
                runTest(mode, padding, minKeySize);
            } else {
                int keySize = maxKeySize;
                while (keySize >= minKeySize) {
                    out.println("With Key Strength: " + keySize);
                    runTest(mode, padding, keySize);
                    keySize -= KEYCUTTER;
                }
            }
        }
    }
}
项目:DMS    文件:RSA.java   
private static void init() {
    try {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        cipher = Cipher.getInstance(INSTANCE_TYPE);
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");
        generator.initialize(1024);
        KeyPair pair = generator.generateKeyPair();
        PUBLIC_KEY = org.apache.commons.codec.binary.Base64.encodeBase64String(pair.getPublic().getEncoded());
        privKey = pair.getPrivate();
    } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) {
        e.printStackTrace();
        Log.e(e.getMessage());
    }
}
项目:ipack    文件:NetscapeCertRequest.java   
public NetscapeCertRequest(
    String challenge,
    AlgorithmIdentifier signing_alg,
    PublicKey pub_key) throws NoSuchAlgorithmException,
        InvalidKeySpecException, NoSuchProviderException
{

    this.challenge = challenge;
    sigAlg = signing_alg;
    pubkey = pub_key;

    ASN1EncodableVector content_der = new ASN1EncodableVector();
    content_der.add(getKeySpec());
    //content_der.add(new SubjectPublicKeyInfo(sigAlg, new RSAPublicKeyStructure(pubkey.getModulus(), pubkey.getPublicExponent()).getDERObject()));
    content_der.add(new DERIA5String(challenge));

    try
    {
        content = new DERBitString(new DERSequence(content_der));
    }
    catch (IOException e)
    {
        throw new InvalidKeySpecException("exception encoding key: " + e.toString());
    }
}
项目:openjdk-jdk10    文件:TransformService.java   
/**
 * Returns a <code>TransformService</code> that supports the specified
 * algorithm URI (ex: {@link Transform#XPATH2}) and mechanism type
 * (ex: DOM) as supplied by the specified provider. The specified provider
 * must be registered in the security provider list.
 *
 * <p>Note that the list of registered providers may be retrieved via
 * the {@link Security#getProviders() Security.getProviders()} method.
 *
 * @param algorithm the URI of the algorithm
 * @param mechanismType the type of the XML processing mechanism and
 *   representation
 * @param provider the string name of the provider
 * @return a new <code>TransformService</code>
 * @throws NoSuchProviderException if the specified provider is not
 *   registered in the security provider list
 * @throws NullPointerException if <code>provider</code>,
 *   <code>mechanismType</code>, or <code>algorithm</code> is
 *   <code>null</code>
 * @throws NoSuchAlgorithmException if a <code>TransformService</code>
 *   implementation for the specified algorithm and mechanism type is not
 *   available from the specified provider
 * @see Provider
 */
public static TransformService getInstance
    (String algorithm, String mechanismType, String provider)
    throws NoSuchAlgorithmException, NoSuchProviderException {
    if (mechanismType == null || algorithm == null || provider == null) {
        throw new NullPointerException();
    } else if (provider.length() == 0) {
        throw new NoSuchProviderException();
    }
    boolean dom = false;
    if (mechanismType.equals("DOM")) {
        dom = true;
    }
    Provider p = Security.getProvider(provider);
    if (p == null) {
        throw new NoSuchProviderException("No such provider: " +
                                          provider);
    }
    Service s = p.getService("TransformService", algorithm);
    if (s != null) {
        String value = s.getAttribute("MechanismType");
        if ((value == null && dom) ||
            (value != null && value.equals(mechanismType))) {
            Object obj = s.newInstance(null);
            if (obj instanceof TransformService) {
                TransformService ts = (TransformService) obj;
                ts.algorithm = algorithm;
                ts.mechanism = mechanismType;
                ts.provider = p;
                return ts;
            }
        }
    }
    throw new NoSuchAlgorithmException
        (algorithm + " algorithm and " + mechanismType
             + " mechanism not available from " + provider);
}
项目:jdk8u-jdk    文件:GCMParameterSpecTest.java   
/**
 * Initialize IV, IV with offset, plain text, AAD and SecretKey
 *
 * @param keyLength length of a secret key
 * @param tagLength tag length
 * @param IVlength IV length
 * @param offset offset in a buffer for IV
 * @param textLength plain text length
 * @param AADLength AAD length
 */
public GCMParameterSpecTest(int keyLength, int tagLength, int IVlength,
        int offset, int textLength, int AADLength)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    this.tagLength = tagLength; // save tag length
    this.IVlength = IVlength; // save IV length
    this.offset = offset; // save IV offset

    // prepare IV
    IV = Helper.generateBytes(IVlength);

    // prepare IV with offset
    IVO = new byte[this.IVlength + this.offset];
    System.arraycopy(IV, 0, IVO, offset, this.IVlength);

    // prepare data
    data = Helper.generateBytes(textLength);

    // prepare AAD
    AAD = Helper.generateBytes(AADLength);

    // init a secret key
    KeyGenerator kg = KeyGenerator.getInstance("AES", "SunJCE");
    kg.init(keyLength);
    key = kg.generateKey();
}
项目:mi-firma-android    文件:JseCryptoHelper.java   
@Override
public byte[] doEcDh(final Key privateKey,
                     final byte[] publicKey,
                     final EcCurve curveName) throws NoSuchAlgorithmException,
                                                     InvalidKeyException,
                                                     InvalidKeySpecException {

    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
    KeyAgreement ka;
    try {
        ka = KeyAgreement.getInstance(ECDH, BouncyCastleProvider.PROVIDER_NAME);
    }
    catch (final NoSuchProviderException e) {
        ka = KeyAgreement.getInstance(ECDH);
    }
    ka.init(privateKey);
    ka.doPhase(loadEcPublicKey(publicKey, curveName), true);
    return ka.generateSecret();
}
项目:ZeroKit-Android-SDK    文件:Zerokit.java   
private void generateNewKey(@NonNull Context context, @NonNull String alias) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    Calendar notBefore = Calendar.getInstance();
    Calendar notAfter = Calendar.getInstance();
    notAfter.add(Calendar.YEAR, 1);

    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
            .setAlias(alias)
            .setSubject(new X500Principal("CN=zerokit"))
            .setSerialNumber(BigInteger.ONE)
            .setStartDate(notBefore.getTime())
            .setEndDate(notAfter.getTime())
            .build();
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", ANDROID_KEYSTORE);
    generator.initialize(spec);
    generator.generateKeyPair();
}
项目:wolfcrypt-jni    文件:WolfCryptKeyPairGeneratorTest.java   
@Test
public void testGetKeyPairGeneratorFromProvider()
    throws NoSuchProviderException, NoSuchAlgorithmException {

    KeyPairGenerator kpg;
    kpg = KeyPairGenerator.getInstance("EC", "wolfJCE");

    /* getting a garbage algorithm should throw an exception */
    try {
        kpg = KeyPairGenerator.getInstance("NotValid", "wolfJCE");

        fail("KeyPairGenerator.getInstance should throw " +
             "NoSuchAlgorithmException when given bad algorithm value");

    } catch (NoSuchAlgorithmException e) { }
}
项目:jdk8u-jdk    文件:SignatureTest.java   
public static void main(String[] args) throws Exception {
    String testAlg = args[0];
    int testSize = Integer.parseInt(args[1]);

    byte[] data = new byte[100];
    RandomFactory.getRandom().nextBytes(data);

    // create a key pair
    KeyPair kpair = generateKeys(KEYALG, testSize);
    Key[] privs = manipulateKey(PRIVATE_KEY, kpair.getPrivate());
    Key[] pubs = manipulateKey(PUBLIC_KEY, kpair.getPublic());
    // For signature algorithm, create and verify a signature

    Arrays.stream(privs).forEach(priv
            -> Arrays.stream(pubs).forEach(pub -> {
                try {
                    checkSignature(data, (PublicKey) pub, (PrivateKey) priv,
                            testAlg);
                } catch (NoSuchAlgorithmException | InvalidKeyException
                        | SignatureException | NoSuchProviderException ex) {
                    throw new RuntimeException(ex);
                }
            }
            ));

}
项目:jdk8u-jdk    文件:TestCipher.java   
public void runAll() throws InvalidKeyException,
        NoSuchPaddingException, InvalidAlgorithmParameterException,
        ShortBufferException, IllegalBlockSizeException,
        BadPaddingException, NoSuchAlgorithmException,
        NoSuchProviderException {

    for (String mode : MODES) {
        for (String padding : PADDINGS) {
            if (!isKeyStrenthSupported()) {
                runTest(mode, padding, 0);
            } else {
                int keySize = variousKeySize;
                while (keySize >= MINIMUM_KEY_SIZE) {
                    out.println("With Key Strength: " + keySize);
                    runTest(mode, padding, keySize);
                    keySize -= KEYCUTTER;
                }
            }
        }
    }
}
项目:xitk    文件:EmulatorP11Slot.java   
private P11Identity saveP11Entity(KeyPair keypair, String label) throws P11TokenException {
    byte[] id = generateId();
    savePkcs11PrivateKey(id, label, keypair.getPrivate());
    savePkcs11PublicKey(id, label, keypair.getPublic());
    P11EntityIdentifier identityId = new P11EntityIdentifier(slotId,
            new P11ObjectIdentifier(id, label));
    try {
        return new EmulatorP11Identity(this,identityId, keypair.getPrivate(),
                keypair.getPublic(), null, maxSessions, random);
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new P11TokenException(
                "could not construct KeyStoreP11Identity: " + ex.getMessage(), ex);
    }
}
项目:mDL-ILP    文件:ECCUtils.java   
/**
 * Generates a random key pair based on a curve
 * @param curve the curve to use
 * @return a randomly generated KeyPair
 */
public static KeyPair generateEphemeralKeys(EllipticCurveParameters curve) {
    try {
        final ECParameterSpec curveParams = EllipticCurveParameters.encodeECParameterSpec(curve);
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
        keyPairGenerator.initialize(curveParams);

        return keyPairGenerator.generateKeyPair();
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }

    return null;
}
项目:wolfcrypt-jni    文件:WolfCryptRandomTest.java   
@Test
public void testSetSeed()
    throws NoSuchProviderException, NoSuchAlgorithmException {

    long seed = 123456789;

    SecureRandom rand = SecureRandom.getInstance("HashDRBG", "wolfJCE");
    rand.setSeed(seed);
}
项目:ipack    文件:TimeStampToken.java   
/**
 * @deprecated use getCertificates() or getCRLs()
 */
public CertStore getCertificatesAndCRLs(
    String type,
    String provider)
    throws NoSuchAlgorithmException, NoSuchProviderException, CMSException
{
    return tsToken.getCertificatesAndCRLs(type, provider);
}
项目:xitk    文件:KeyUtil.java   
public static KeyPair generateECKeypairForCurveNameOrOid(String curveNameOrOid,
        SecureRandom random) throws NoSuchAlgorithmException, NoSuchProviderException,
            InvalidAlgorithmParameterException {
    ASN1ObjectIdentifier oid = AlgorithmUtil.getCurveOidForCurveNameOrOid(curveNameOrOid);
    if (oid == null) {
        throw new IllegalArgumentException("invalid curveNameOrOid '" + curveNameOrOid + "'");
    }
    return generateECKeypair(oid, random);
}
项目:ipack    文件:OCSPUtil.java   
static CertificateFactory createX509CertificateFactory(String provider)
    throws CertificateException, NoSuchProviderException
{
    if (provider == null)
    {
        return CertificateFactory.getInstance("X.509");
    }

    return CertificateFactory.getInstance("X.509", provider);
}
项目:xitk    文件:KeyUtil.java   
public static KeyPair generateDSAKeypair(DSAParameters dsaParams, SecureRandom random)
        throws NoSuchAlgorithmException, NoSuchProviderException,
            InvalidAlgorithmParameterException {
    DSAParameterSpec dsaParamSpec = new DSAParameterSpec(dsaParams.getP(), dsaParams.getQ(),
            dsaParams.getG());
    KeyPairGenerator kpGen = getKeyPairGenerator("DSA");
    synchronized (kpGen) {
        kpGen.initialize(dsaParamSpec, random);
        return kpGen.generateKeyPair();
    }
}
项目:atlant-android    文件:UnitTestApp.java   
@Test
public void TestValidAddress()
    throws ExecutionException, InterruptedException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
  for (int i = 0; i < 100; i++) {
    MyWallet myWallet = new MyWallet();
    if (!WalletUtils.isValidAddress(myWallet.getAddress()) || !WalletUtils
        .isValidPrivateKey(myWallet.getPrivateKey())) {
      assertTrue(false);
    }
  }
  assertTrue(true);
}
项目:springboot-shiro-cas-mybatis    文件:MockX509CRL.java   
/**
 * @see java.security.cert.X509CRL#verify(java.security.PublicKey, java.lang.String)
 */
@Override
public void verify(final PublicKey key, final String sigProvider) throws CRLException,
NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException,
SignatureException {
    // Do nothing to indicate valid signature
}
项目:bubichain-sdk-java    文件:HttpKit.java   
/**
 * 鍙戦�丟et璇锋眰
 * @param url
 * @return
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws IOException 
 * @throws KeyManagementException 
 */
public static String get(String url) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
    if(enableSSL){
        return get(url,true);
    }else{
        StringBuffer bufferRes = null;
        URL urlGet = new URL(url);
        HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
        // 杩炴帴瓒呮椂
        http.setConnectTimeout(25000);
        // 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
        http.setReadTimeout(25000);
        http.setRequestMethod("GET");
        http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();

        InputStream in = http.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
        String valueString = null;
        bufferRes = new StringBuffer();
        while ((valueString = read.readLine()) != null){
            bufferRes.append(valueString);
        }
        in.close();
        if (http != null) {
            // 鍏抽棴杩炴帴
            http.disconnect();
        }
        return bufferRes.toString();
    }
}
项目:OpenJSharp    文件:TransformService.java   
/**
 * Returns a <code>TransformService</code> that supports the specified
 * algorithm URI (ex: {@link Transform#XPATH2}) and mechanism type
 * (ex: DOM) as supplied by the specified provider. The specified provider
 * must be registered in the security provider list.
 *
 * <p>Note that the list of registered providers may be retrieved via
 * the {@link Security#getProviders() Security.getProviders()} method.
 *
 * @param algorithm the URI of the algorithm
 * @param mechanismType the type of the XML processing mechanism and
 *   representation
 * @param provider the string name of the provider
 * @return a new <code>TransformService</code>
 * @throws NoSuchProviderException if the specified provider is not
 *   registered in the security provider list
 * @throws NullPointerException if <code>provider</code>,
 *   <code>mechanismType</code>, or <code>algorithm</code> is
 *   <code>null</code>
 * @throws NoSuchAlgorithmException if a <code>TransformService</code>
 *   implementation for the specified algorithm and mechanism type is not
 *   available from the specified provider
 * @see Provider
 */
public static TransformService getInstance
    (String algorithm, String mechanismType, String provider)
    throws NoSuchAlgorithmException, NoSuchProviderException {
    if (mechanismType == null || algorithm == null || provider == null) {
        throw new NullPointerException();
    } else if (provider.length() == 0) {
        throw new NoSuchProviderException();
    }
    boolean dom = false;
    if (mechanismType.equals("DOM")) {
        dom = true;
    }
    Service s = GetInstance.getService
        ("TransformService", algorithm, provider);
    String value = s.getAttribute("MechanismType");
    if ((value == null && dom) ||
        (value != null && value.equals(mechanismType))) {
        Instance instance = GetInstance.getInstance(s, null);
        TransformService ts = (TransformService) instance.impl;
        ts.algorithm = algorithm;
        ts.mechanism = mechanismType;
        ts.provider = instance.provider;
        return ts;
    }
    throw new NoSuchAlgorithmException
        (algorithm + " algorithm and " + mechanismType
             + " mechanism not available");
}
项目:ipack    文件:SignerInformation.java   
/**
 * verify that the given certificate successfully handles and confirms
 * the signature associated with this signer and, if a signingTime
 * attribute is available, that the certificate was valid at the time the
 * signature was generated.
 * @deprecated use verify(ContentVerifierProvider)
 */
public boolean verify(
    X509Certificate cert,
    String          sigProvider)
    throws NoSuchAlgorithmException, NoSuchProviderException,
        CertificateExpiredException, CertificateNotYetValidException,
        CMSException
{
    return verify(cert, CMSUtils.getProvider(sigProvider));
}
项目:AppCoins-ethereumj    文件:ECSignatureFactory.java   
public static Signature getRawInstance(String provider) throws NoSuchProviderException {
  try {
    return Signature.getInstance(RAW_ALGORITHM, provider);
  } catch (NoSuchAlgorithmException ex) {
    throw new AssertionError(rawAlgorithmAssertionMsg, ex);
  }
}
项目:openjdk-jdk10    文件:TestSHAOids.java   
private static void runTest(DataTuple dataTuple)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    MessageDigest mdAlgorithm = MessageDigest.getInstance(
            dataTuple.algorithm, PROVIDER_NAME);
    MessageDigest mdOid = MessageDigest.getInstance(dataTuple.oid,
            PROVIDER_NAME);

    if (mdAlgorithm == null) {
        throw new RuntimeException(String.format(
                "Test failed: algorithm string %s getInstance failed.%n",
                dataTuple.algorithm));
    }

    if (mdOid == null) {
        throw new RuntimeException(
                String.format("Test failed: OID %s getInstance failed.%n",
                        dataTuple.oid));
    }

    if (!mdAlgorithm.getAlgorithm().equals(dataTuple.algorithm)) {
        throw new RuntimeException(String.format(
                "Test failed: algorithm string %s getInstance doesn't "
                        + "generate expected algorithm.%n",
                dataTuple.algorithm));
    }

    mdAlgorithm.update(INPUT);
    mdOid.update(INPUT);

    // Comparison
    if (!Arrays.equals(mdAlgorithm.digest(), mdOid.digest())) {
        throw new RuntimeException("Digest comparison failed: "
                + "the two digests are not the same");
    }
}
项目:wolfcrypt-jni    文件:WolfCryptSignatureTest.java   
@Test
public void testWolfSignInitMulti()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           SignatureException, InvalidKeyException,
           InvalidAlgorithmParameterException {

    String toSign = "Hello World";
    byte[] toSignBuf = toSign.getBytes();
    byte[] signature = null;

    for (int i = 0; i < wolfJCEAlgos.length; i++) {

        Signature signer =
            Signature.getInstance(wolfJCEAlgos[i], "wolfJCE");
        Signature verifier =
            Signature.getInstance(wolfJCEAlgos[i], "wolfJCE");

        assertNotNull(signer);
        assertNotNull(verifier);

        SecureRandom rand =
            SecureRandom.getInstance("HashDRBG", "wolfJCE");
        assertNotNull(rand);

        /* generate key pair */
        KeyPair pair = generateKeyPair(wolfJCEAlgos[i], rand);
        assertNotNull(pair);

        PrivateKey priv = pair.getPrivate();
        PublicKey  pub  = pair.getPublic();

        /* test multiple inits on signer */
        signer.initSign(priv);
        signer.initSign(priv);

        /* test multiple inits on verifier */
        verifier.initVerify(pub);
        verifier.initVerify(pub);

        /* make sure sign/verify still work after multi init */
        signer.update(toSignBuf, 0, toSignBuf.length);
        signature = signer.sign();

        verifier.update(toSignBuf, 0, toSignBuf.length);
        boolean verified = verifier.verify(signature);

        if (verified != true) {
            fail("Signature verification failed when generating with " +
                    "wolfJCE and verifying with system default JCE " +
                    "provider");
        }
    }
}
项目:bubichain-sdk-java    文件:HttpKit.java   
public static String buildQR(String url,String actionName,Integer sceneId) throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException{
    String params = "";
    if("QR_SCENE".equals(actionName)){//涓存椂鏁板瓧鍙傛暟鍊�
        params = "{\"expire_seconds\": 1800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": "+sceneId+"}}}";
    }else if("QR_LIMIT_SCENE".equals(actionName)){//姘镐箙鏁板瓧鍙傛暟鍊�
        params = "{\"expire_seconds\": 1800, \"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": "+sceneId+"}}}";
    }else if("QR_LIMIT_STR_SCENE".equals(actionName)){//姘镐箙鐨勫瓧绗︿覆鍙傛暟鍊�
        params = "{\"expire_seconds\": 1800, \"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+sceneId+"\"}}}";
    }
    return HttpKit.post(url, params);
}
项目:ipack    文件:CMSSignedDataGenerator.java   
/**
 * generate a signed object that for a CMS Signed Data
 * object using the given provider.
 * @deprecated use generate() method not taking provider.
 */
public CMSSignedData generate(
    CMSProcessable content,
    String         sigProvider)
    throws NoSuchAlgorithmException, NoSuchProviderException, CMSException
{
    return generate(content, CMSUtils.getProvider(sigProvider));
}
项目:cas-5.1.0    文件:MockX509CRL.java   
/**
 * @see java.security.cert.X509CRL#verify(java.security.PublicKey, java.lang.String)
 */
@Override
public void verify(final PublicKey key, final String sigProvider) throws CRLException,
NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException,
SignatureException {
    // Do nothing to indicate valid signature
}
项目:lams    文件:SecurityHelper.java   
/**
 * Generate a random asymmetric key pair and return in a BasicCredential.
 * 
 * @param algorithmURI The XML Encryption algorithm URI
 * @param keyLength key length
 * @param includePrivate if true, the private key will be included as well
 * @return a basic credential containing a randomly generated asymmetric key pair
 * @throws NoSuchAlgorithmException algorithm not found
 * @throws NoSuchProviderException provider not found
 */
public static Credential generateKeyPairAndCredential(String algorithmURI, int keyLength, boolean includePrivate) 
        throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPair keyPair = generateKeyPairFromURI(algorithmURI, keyLength);
    BasicCredential credential = new BasicCredential();
    credential.setPublicKey(keyPair.getPublic());
    if (includePrivate) {
        credential.setPrivateKey(keyPair.getPrivate());
    }
    return credential;
}
项目:ipack    文件:X509Util.java   
static byte[] calculateSignature(
    DERObjectIdentifier sigOid,
    String              sigName,
    String              provider,
    PrivateKey          key,
    SecureRandom        random,
    ASN1Encodable       object)
    throws IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException
{
    Signature sig;

    if (sigOid == null)
    {
        throw new IllegalStateException("no signature algorithm specified");
    }

    sig = X509Util.getSignatureInstance(sigName, provider);

    if (random != null)
    {
        sig.initSign(key, random);
    }
    else
    {
        sig.initSign(key);
    }

    sig.update(object.toASN1Primitive().getEncoded(ASN1Encoding.DER));

    return sig.sign();
}