类java.security.NoSuchAlgorithmException源码实例Demo

下面列出了怎么用java.security.NoSuchAlgorithmException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: AlipayOrdersSupervisor-GUI   文件: Order.java
public static String Sign(ApsvOrder order, String secret) {
    String[] data = new String[]{order.time, order.tradeNo, Float.toString(order.amount), order.status, secret};
    String dataStr = String.join("|", data);
    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.reset();
        md5.update(dataStr.getBytes(Charset.forName("UTF-8")));
        byte[] dataBytes = md5.digest();
        StringBuffer buffer = new StringBuffer();
        for (int i=0; i<dataBytes.length; i++) {
            if (Integer.toHexString(0xFF & dataBytes[i]).length() == 1)
                buffer.append("0").append(
                        Integer.toHexString(0xFF & dataBytes[i]));
            else
                buffer.append(Integer.toHexString(0xFF & dataBytes[i]));
        }
        return buffer.toString();
    } catch (NoSuchAlgorithmException e) {
        return "";
    }
}
 
源代码2 项目: syslog4j   文件: MacSyslogMessageModifier.java
public MacSyslogMessageModifier(MacSyslogMessageModifierConfig config) throws SyslogRuntimeException {
	super(config);
	
	this.config = config;

	try {
		this.mac = Mac.getInstance(config.getMacAlgorithm());
		this.mac.init(config.getKey());
		
	} catch (NoSuchAlgorithmException nsae) {
		throw new SyslogRuntimeException(nsae);
		
	} catch (InvalidKeyException ike) {
		throw new SyslogRuntimeException(ike);
	}
}
 
public ResourceAuthenticator(IResourceLoader resourceLoader, String resourceName) {
    try {
        MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException nsaex) {
        LOG.error("Can't find SHA-256 for password encoding", nsaex);
        throw new RuntimeException(nsaex);
    }

    LOG.info(String.format("Loading password %s %s", resourceLoader.getName(), resourceName));
    Reader reader = null;
    try {
        reader = resourceLoader.loadResource(resourceName);
        if (reader == null) {
            LOG.warn(String.format("Parsing not existing %s %s", resourceLoader.getName(), resourceName));
        } else {
            parse(reader);
        }
    } catch (IResourceLoader.ResourceIsDirectoryException e) {
        LOG.warn(String.format("Trying to parse directory %s", resourceName));
    } catch (ParseException pex) {
        LOG.warn(
                String.format("Format error in parsing password %s %s", resourceLoader.getName(), resourceName),
                pex);
    }
}
 
源代码4 项目: markdown-image-kit   文件: RSAEncodeUtils.java
@NotNull
public static String encode(String toEncode, String pubKey, String pubExp)
    throws NoSuchAlgorithmException, NoSuchPaddingException,
           InvalidKeySpecException, InvalidKeyException, BadPaddingException,
           IllegalBlockSizeException {

    KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
    BigInteger modulus = new BigInteger(pubKey, 16);
    BigInteger publicExponent = new BigInteger(pubExp, 16);
    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
    PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);
    Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] encodeStr = cipher.doFinal(toEncode.getBytes());
    return bytesToHex(encodeStr);
}
 
源代码5 项目: beam   文件: KeyPairSnowflakeCredentials.java
private PrivateKey getPrivateKey(String privateKeyPath, String privateKeyPassphrase) {
  try {
    byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyPath));

    String encrypted = new String(keyBytes, Charset.defaultCharset());
    encrypted = encrypted.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "");
    encrypted = encrypted.replace("-----END ENCRYPTED PRIVATE KEY-----", "");
    EncryptedPrivateKeyInfo pkInfo =
        new EncryptedPrivateKeyInfo(Base64.getMimeDecoder().decode(encrypted));
    PBEKeySpec keySpec = new PBEKeySpec(privateKeyPassphrase.toCharArray());
    SecretKeyFactory pbeKeyFactory = SecretKeyFactory.getInstance(pkInfo.getAlgName());
    PKCS8EncodedKeySpec encodedKeySpec = pkInfo.getKeySpec(pbeKeyFactory.generateSecret(keySpec));

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePrivate(encodedKeySpec);
  } catch (IOException
      | NoSuchAlgorithmException
      | InvalidKeySpecException
      | InvalidKeyException ex) {
    throw new RuntimeException("Can't create PrivateKey from options");
  }
}
 
源代码6 项目: TencentKona-8   文件: DESCipherWrapper.java
public DESCipherWrapper(String algo, String mode, String pad)
        throws NoSuchAlgorithmException, NoSuchPaddingException {
    ci = Cipher.getInstance(algo + "/" + mode + "/" + pad);

    iv = new byte[8];
    for (int i = 0; i < 8; i++) {
        iv[i] = (byte) (i & 0xff);
    }

    KeyGenerator kg = KeyGenerator.getInstance(algo);
    key = kg.generateKey();
    keyStrength = algo.equalsIgnoreCase("DESede") ? 112
            : key.getEncoded().length * 8;

    this.algo = algo;
    this.mode = mode;
    this.pad = pad;
}
 
源代码7 项目: xipki   文件: EmulatorP11Slot.java
@Override
protected P11Identity generateECEdwardsKeypair0(ASN1ObjectIdentifier curveOid,
    P11NewKeyControl control) throws P11TokenException {
  assertMechanismSupported(PKCS11Constants.CKM_EC_EDWARDS_KEY_PAIR_GEN);

  KeyPair keypair;
  try {
    if (!EdECConstants.isEdwardsCurve(curveOid)) {
      throw new P11TokenException("unknown curve  " + curveOid.getId());
    }

    keypair = KeyUtil.generateEdECKeypair(curveOid, random);
  } catch (NoSuchAlgorithmException | NoSuchProviderException
      | InvalidAlgorithmParameterException ex) {
    throw new P11TokenException(ex.getMessage(), ex);
  }
  return saveP11Entity(keypair, control);
}
 
源代码8 项目: DataHubSystem   文件: User.java
public String hash ()
{
   String source = getUUID() + "-" + getUsername () + "@" + getEmail () + 
      " - " + getPassword ();
   MessageDigest md;
   byte[] digest;
   try
   {
      md = MessageDigest.getInstance ("MD5");
      digest = md.digest (source.getBytes ());
   }
   catch (NoSuchAlgorithmException e)
   {
      throw new UnsupportedOperationException (
         "Cannot compute MD5 digest for user " + getUsername (), e);
   }
   StringBuffer sb = new StringBuffer ();
   for (int i = 0; i < digest.length; ++i)
   {
      sb.append (Integer.toHexString ( (digest[i] & 0xFF) | 0x100)
         .substring (1, 3));
   }
   return sb.toString ();
}
 
源代码9 项目: carbon-device-mgt   文件: JWTClientUtil.java
private static KeyStore loadKeyStore(final File keystoreFile, final String password, final String keyStoreType)
		throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
	if (null == keystoreFile) {
		throw new IllegalArgumentException("Keystore url may not be null");
	}
	URI keystoreUri = keystoreFile.toURI();
	URL keystoreUrl = keystoreUri.toURL();
	KeyStore keystore = KeyStore.getInstance(keyStoreType);
	InputStream is = null;
	try {
		is = keystoreUrl.openStream();
		keystore.load(is, null == password ? null : password.toCharArray());
	} finally {
		if (null != is) {
			is.close();
		}
	}
	return keystore;
}
 
源代码10 项目: modeldb   文件: ConfigContainer.java
private String computeContinuousSHA(
    String name,
    HyperparameterElementConfigBlobEntity hyperparameterElementConfigBlobEntityBegin,
    HyperparameterElementConfigBlobEntity hyperparameterElementConfigBlobEntityEnd,
    HyperparameterElementConfigBlobEntity hyperparameterElementConfigBlobEntityStep)
    throws NoSuchAlgorithmException {
  final String payload =
      "name:"
          + name
          + ":begin:"
          + hyperparameterElementConfigBlobEntityBegin.getBlobHash()
          + ":end:"
          + hyperparameterElementConfigBlobEntityEnd.getBlobHash()
          + ":step:"
          + hyperparameterElementConfigBlobEntityStep.getBlobHash();
  return FileHasher.getSha(payload);
}
 
源代码11 项目: android_9.0.0_r45   文件: PlatformKeyManager.java
/**
 * Initializes the class. If there is no current platform key, and the user has a lock screen
 * set, will create the platform key and set the generation ID.
 *
 * @param userId The ID of the user to whose lock screen the platform key must be bound.
 * @throws KeyStoreException if there was an error in AndroidKeyStore.
 * @throws NoSuchAlgorithmException if AES is unavailable - should never happen.
 * @throws IOException if there was an issue with local database update.
 *
 * @hide
 */
void init(int userId)
        throws KeyStoreException, NoSuchAlgorithmException, InsecureUserException, IOException {
    if (!isAvailable(userId)) {
        throw new InsecureUserException(String.format(
                Locale.US, "%d does not have a lock screen set.", userId));
    }

    int generationId = getGenerationId(userId);
    if (isKeyLoaded(userId, generationId)) {
        Log.i(TAG, String.format(
                Locale.US, "Platform key generation %d exists already.", generationId));
        return;
    }
    if (generationId == -1) {
        Log.i(TAG, "Generating initial platform key generation ID.");
        generationId = 1;
    } else {
        Log.w(TAG, String.format(Locale.US, "Platform generation ID was %d but no "
                + "entry was present in AndroidKeyStore. Generating fresh key.", generationId));
        // Have to generate a fresh key, so bump the generation id
        generationId++;
    }

    generateAndLoadKey(userId, generationId);
}
 
源代码12 项目: beam   文件: HttpEventPublisherTest.java
@Test
public void stringPayloadTest()
    throws UnsupportedEncodingException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException {

  HttpEventPublisher publisher =
      HttpEventPublisher.newBuilder()
          .withUrl("http://example.com")
          .withToken("test-token")
          .withDisableCertificateValidation(false)
          .build();

  String actual = publisher.getStringPayload(SPLUNK_EVENTS);

  String expected =
      "{\"time\":12345,\"host\":\"test-host-1\",\"source\":\"test-source-1\","
          + "\"sourcetype\":\"test-source-type-1\",\"index\":\"test-index-1\","
          + "\"event\":\"test-event-1\"}{\"time\":12345,\"host\":\"test-host-2\","
          + "\"source\":\"test-source-2\",\"sourcetype\":\"test-source-type-2\","
          + "\"index\":\"test-index-2\",\"event\":\"test-event-2\"}";

  assertEquals(expected, actual);
}
 
源代码13 项目: Knowage-Server   文件: SecurityUtilities.java
/**
 * Generate a random array of bytes (1024 bits) using the SHA1PRNG alghoritm.
 * 
 * @return Byte array filled with random byte
 */ 
public byte[] generateRandomChallenge() {
	byte[] challenge = null;
	try {
		SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
		// Get 1024 random bits
		challenge = new byte[1024];
		sr.nextBytes(challenge);
	} catch (NoSuchAlgorithmException e) {
		SpagoBITracer.major("ENGINES",
							this.getClass().getName(),
							"generateRandomChallenge",
							"Alghoritm SHA1PRNG not found ", e);
	} 
	return challenge;
}
 
源代码14 项目: Qlassified-Android   文件: QlassifiedCrypto.java
public String encrypt(String input, RSAPublicKey publicKey) {

        if (input == null) {
            return null;
        }

        try {
            byte[] dataBytes = input.getBytes(CHARSET);
            Cipher cipher = Cipher.getInstance(ALGORITHM, new BouncyCastleProvider());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeToString(cipher.doFinal(dataBytes), BASE64_MODE);
        } catch (IllegalBlockSizeException |
                BadPaddingException |
                NoSuchAlgorithmException |
                NoSuchPaddingException |
                UnsupportedEncodingException |
                InvalidKeyException e) {
            Log.e("QlassifiedCrypto", String.format("Could not encrypt this string. Stacktrace: %s", e));
            return null;
        }
    }
 
源代码15 项目: org.openhab.ui.habot   文件: NotificationService.java
/**
 * Generate an EC keypair on the prime256v1 curve and save them to a file for later usage.
 *
 * Some code borrowed from
 * <a href=
 * "https://github.com/web-push-libs/webpush-java/blob/master/src/main/java/nl/martijndwars/webpush/cli/handlers/GenerateKeyHandler.java">webpush-java</a>.
 *
 * @author Martijn Dwars
 *
 * @throws InvalidAlgorithmParameterException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws FileNotFoundException
 */
private void generateVAPIDKeyPair() throws InvalidAlgorithmParameterException, NoSuchProviderException,
        NoSuchAlgorithmException, FileNotFoundException, IOException {
    ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(Utils.CURVE);

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(Utils.ALGORITHM, PROVIDER_NAME);
    keyPairGenerator.initialize(parameterSpec);

    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    byte[] publicKey = Utils.savePublicKey((ECPublicKey) keyPair.getPublic());
    byte[] privateKey = Utils.savePrivateKey((ECPrivateKey) keyPair.getPrivate());

    List<String> encodedKeys = new ArrayList<String>();
    encodedKeys.add(BaseEncoding.base64Url().encode(publicKey));
    encodedKeys.add(BaseEncoding.base64Url().encode(privateKey));

    // write the public key, then the private key in encoded form on separate lines in the file
    File file = new File(ConfigConstants.getUserDataFolder() + File.separator + VAPID_KEYS_FILE_NAME);
    file.getParentFile().mkdirs();
    IOUtils.writeLines(encodedKeys, System.lineSeparator(), new FileOutputStream(file));

    this.publicVAPIDKey = encodedKeys.get(0);
    this.privateVAPIDKey = encodedKeys.get(1);
}
 
源代码16 项目: ZjDroid   文件: DexWriter.java
private void updateSignature(@Nonnull DexDataStore dataStore) throws IOException {
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }

    byte[] buffer = new byte[4 * 1024];
    InputStream input = dataStore.readAt(HeaderItem.SIGNATURE_DATA_START_OFFSET);
    int bytesRead = input.read(buffer);
    while (bytesRead >= 0) {
        md.update(buffer, 0, bytesRead);
        bytesRead = input.read(buffer);
    }

    byte[] signature = md.digest();
    if (signature.length != HeaderItem.SIGNATURE_SIZE) {
        throw new RuntimeException("unexpected digest write: " + signature.length + " bytes");
    }

    // write signature
    OutputStream output = dataStore.outputAt(HeaderItem.SIGNATURE_OFFSET);
    output.write(signature);
    output.close();
}
 
源代码17 项目: WebIDE-Backend   文件: KeyManagerImpl.java
public Key generateKey() throws IOException {
    KeyPairGenerator generator = null;
    try {
        generator = KeyPairGenerator.getInstance("RSA");
        // or: generator = KeyPairGenerator.getInstance("DSA");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    generator.initialize(2048);
    KeyPair keyPair = generator.genKeyPair();
    final String publicKey = keyToString((RSAPublicKey) keyPair.getPublic(), username);
    final String privateKey = keyToString((RSAPrivateKey) keyPair.getPrivate());
    final String fingerprint = fingerprint(publicKey);

    Key key = new Key(privateKey, publicKey, fingerprint);

    saveOrUpdateKey(key);

    return key;
}
 
源代码18 项目: pdf-sign-check   文件: UploadController.java
@PostMapping("/")
public Object singleFileUpload(Model model, @RequestParam("file") MultipartFile file, @RequestParam(value = "json", required = false) String json, HttpServletResponse response ) {

    if (file.isEmpty()) {
        model.addAttribute("message", "Empty file");
        return "home";
    }

    try {

        byte[] bytes = file.getBytes();
        List<PDFSignatureInfo> info = PDFSignatureInfoParser.getPDFSignatureInfo(bytes);

        model.addAttribute("message", "OK");
        model.addAttribute("filename", file.getOriginalFilename());
        model.addAttribute("pdfSignatureInfo", info);

    } catch (IOException | InvalidNameException | CertificateException| NoSuchAlgorithmException | InvalidKeyException |SignatureException | NoSuchProviderException e) {
        model.addAttribute("message", "Cannot open file: " + e.getMessage());
        e.printStackTrace();
    }

    if(json!=null && json.equals("on")) {
        return gr.hcg.JsonView.Render(model, response );
    }

    return new ModelAndView("home", model.asMap());

    //return "home";
}
 
源代码19 项目: meghanada-server   文件: Gen12.java
public void getChecksum(final File file) throws IOException {
  try {
    final MessageDigest md = MessageDigest.getInstance("MD5");
    try (InputStream is = Files.newInputStream(file.toPath());
        DigestInputStream dis = new DigestInputStream(is, md)) {
      final byte[] buf = new byte[8192];
      while (dis.read(buf) != -1) {}
    }
  } catch (NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}
 
源代码20 项目: jdk8u-jdk   文件: XMLCipher.java
/**
 * Construct a Cipher object
 */
private Cipher constructCipher(String algorithm, String digestAlgorithm) throws XMLEncryptionException {
    String jceAlgorithm = JCEMapper.translateURItoJCEID(algorithm);
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm);
    }

    Cipher c;
    try {
        if (requestedJCEProvider == null) {
            c = Cipher.getInstance(jceAlgorithm);
        } else {
            c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider);
        }
    } catch (NoSuchAlgorithmException nsae) {
        // Check to see if an RSA OAEP MGF-1 with SHA-1 algorithm was requested
        // Some JDKs don't support RSA/ECB/OAEPPadding
        if (XMLCipher.RSA_OAEP.equals(algorithm)
            && (digestAlgorithm == null
                || MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1.equals(digestAlgorithm))) {
            try {
                if (requestedJCEProvider == null) {
                    c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
                } else {
                    c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", requestedJCEProvider);
                }
            } catch (Exception ex) {
                throw new XMLEncryptionException("empty", ex);
            }
        } else {
            throw new XMLEncryptionException("empty", nsae);
        }
    } catch (NoSuchProviderException nspre) {
        throw new XMLEncryptionException("empty", nspre);
    } catch (NoSuchPaddingException nspae) {
        throw new XMLEncryptionException("empty", nspae);
    }

    return c;
}
 
源代码21 项目: android-easy-checkout   文件: Security.java
/**
 * Generates a PublicKey instance from a string containing the
 * Base64-encoded public key.
 *
 * @param encodedPublicKey rsa public key generated by Google Play Developer Console
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
protected PublicKey generatePublicKey(String encodedPublicKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException {

    byte[] decodedKey = Base64.decode(encodedPublicKey, Base64.DEFAULT);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
}
 
源代码22 项目: besu   文件: TlsHelpers.java
private static String generateFingerprint(final X509Certificate cert)
    throws NoSuchAlgorithmException, CertificateEncodingException {
  final MessageDigest md = MessageDigestFactory.create("SHA-256");
  md.update(cert.getEncoded());
  final byte[] digest = md.digest();

  final StringJoiner joiner = new StringJoiner(":");
  for (final byte b : digest) {
    joiner.add(String.format("%02X", b));
  }

  return joiner.toString().toLowerCase();
}
 
源代码23 项目: phoenix   文件: MD5Function.java
public MD5Function() throws SQLException {
    try {
        messageDigest = MessageDigest.getInstance("MD5");
      } catch (NoSuchAlgorithmException e) {
        throw new SQLException(e);
      }      
}
 
源代码24 项目: android-chromium   文件: X509Util.java
/**
 * Ensures that the trust managers and certificate factory are initialized.
 */
private static void ensureInitialized() throws CertificateException,
        KeyStoreException, NoSuchAlgorithmException {
    synchronized(sLock) {
        if (sCertificateFactory == null) {
            sCertificateFactory = CertificateFactory.getInstance("X.509");
        }
        if (sDefaultTrustManager == null) {
            sDefaultTrustManager = X509Util.createTrustManager(null);
        }
        if (sTestKeyStore == null) {
            sTestKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            try {
                sTestKeyStore.load(null);
            } catch(IOException e) {}  // No IO operation is attempted.
        }
        if (sTestTrustManager == null) {
            sTestTrustManager = X509Util.createTrustManager(sTestKeyStore);
        }
        if (!sDisableCertificateObservationForTest &&
                sTrustStorageListener == null) {
            sTrustStorageListener = new TrustStorageListener();
            nativeGetApplicationContext().registerReceiver(sTrustStorageListener,
                    new IntentFilter(KeyChain.ACTION_STORAGE_CHANGED));
        }
    }
}
 
源代码25 项目: message_interface   文件: SessionClient.java
/**
 * 发送图片消息给客服。如果没有提供图片宽高,此函数会自动计算,不过为了效率考虑,由外部提供会比较好。
 * @param fromUid 消息来源访客的ID
 * @param path 图片文件的路径
 * @param width 图片的宽
 * @param height 图片的高
 * @return 发送的结果
 * @throws IOException
 */
public CommonResult sendImageMessage(String fromUid, String path, int width, int height) throws IOException, NoSuchAlgorithmException {
    String md5 = FileUtil.getMd5(path).toLowerCase();
    long size = FileUtil.getSize(path);
    String url = uploadFile(path, md5);

    if (width <= 0 || height <= 0) {
        int[] imageSize = MediaUtil.querySize(path);
        width = imageSize[0];
        height = imageSize[1];
    }
    return sendImageMessage(fromUid, url, md5, size, width, height);

}
 
@Override
public EncryptionStatus getEncryptionStatus()
{
    String password;

    int maxKeyLength;

    // Check for JCE files is present (key length > 128) and AES is available

    try
    {
        maxKeyLength = Cipher.getMaxAllowedKeyLength( "AES" );

        if ( maxKeyLength == 128 )
        {
            return EncryptionStatus.MISSING_JCE_POLICY;
        }
    }
    catch ( NoSuchAlgorithmException e )
    {
        return EncryptionStatus.MISSING_JCE_POLICY;
    }

    password = getProperty( ConfigurationKey.ENCRYPTION_PASSWORD );

    if ( password.length() == 0 )
    {
        return EncryptionStatus.MISSING_ENCRYPTION_PASSWORD;
    }

    if ( password.length() < 24 )
    {
        return EncryptionStatus.ENCRYPTION_PASSWORD_TOO_SHORT;
    }

    return EncryptionStatus.OK;
}
 
源代码27 项目: openjdk-jdk8u-backup   文件: CertStore.java
private static CertStore handleException(NoSuchAlgorithmException e)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    Throwable cause = e.getCause();
    if (cause instanceof InvalidAlgorithmParameterException) {
        throw (InvalidAlgorithmParameterException)cause;
    }
    throw e;
}
 
源代码28 项目: CloverETL-Engine   文件: AsymKeyManager.java
/**
 * Loads private key from file.
 * @param privFile
 * @return
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
public static PrivateKey readPrivate(InputStream inStream) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException {
	byte[] buf = new byte[maxKeySize];
	int n = inStream.read(buf);
	byte[] encoded = new byte[n];
	for (int i = 0; i < n; i++) {
		encoded[i] = buf[i];
	}
	PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(buf);
	return KeyFactory.getInstance(alg).generatePrivate(kspec);
}
 
源代码29 项目: gemfirexd-oss   文件: JCECipherFactory.java
private byte[] generateUniqueBytes() throws StandardException
{
	try {

		String provider = cryptoProviderShort;

		KeyGenerator keyGen;
		if (provider == null)
		{
			keyGen = KeyGenerator.getInstance(cryptoAlgorithmShort);
		}
		else
		{
			if( provider.equals("BouncyCastleProvider"))
				provider = "BC";
			keyGen = KeyGenerator.getInstance(cryptoAlgorithmShort, provider);
		}

		keyGen.init(keyLengthBits);

		SecretKey key = keyGen.generateKey();

		return key.getEncoded();

	} catch (java.security.NoSuchAlgorithmException nsae) {
   		throw StandardException.newException(SQLState.ENCRYPTION_NOSUCH_ALGORITHM, cryptoAlgorithm,
			JCECipherFactory.providerErrorName(cryptoProviderShort));
	} catch (java.security.NoSuchProviderException nspe) {
		throw StandardException.newException(SQLState.ENCRYPTION_BAD_PROVIDER,
			JCECipherFactory.providerErrorName(cryptoProviderShort));
	}
}
 
源代码30 项目: spacewalk   文件: SHA256Crypt.java
/**
 * getSHA256MD - get SHA256 MessageDigest object instance
 * @return MessageDigest object instance
 */
private static MessageDigest getSHA256MD() {
    MessageDigest md;

    try {
        md = MessageDigest.getInstance("SHA-256");
    }
    catch (NoSuchAlgorithmException e) {
        throw new SHA256CryptException("Problem getting SHA-256 message digest");
    }

    return md;
}
 
 类所在包
 同包方法