下面列出了怎么用java.security.NoSuchAlgorithmException的API类实例代码及写法,或者点击链接到github查看源代码。
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 "";
}
}
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);
}
}
@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);
}
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");
}
}
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;
}
@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);
}
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 ();
}
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;
}
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);
}
/**
* 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);
}
@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);
}
/**
* 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;
}
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;
}
}
/**
* 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);
}
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();
}
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;
}
@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";
}
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);
}
}
/**
* 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;
}
/**
* 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));
}
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();
}
public MD5Function() throws SQLException {
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new SQLException(e);
}
}
/**
* 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));
}
}
}
/**
* 发送图片消息给客服。如果没有提供图片宽高,此函数会自动计算,不过为了效率考虑,由外部提供会比较好。
* @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;
}
private static CertStore handleException(NoSuchAlgorithmException e)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
Throwable cause = e.getCause();
if (cause instanceof InvalidAlgorithmParameterException) {
throw (InvalidAlgorithmParameterException)cause;
}
throw e;
}
/**
* 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);
}
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));
}
}
/**
* 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;
}