java.security.NoSuchAlgorithmException Java Examples
The following examples show how to use
java.security.NoSuchAlgorithmException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Order.java From AlipayOrdersSupervisor-GUI with MIT License | 6 votes |
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 ""; } }
Example #2
Source File: SecurityUtilities.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
/** * 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; }
Example #3
Source File: EmulatorP11Slot.java From xipki with Apache License 2.0 | 6 votes |
@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); }
Example #4
Source File: HttpEventPublisherTest.java From beam with Apache License 2.0 | 6 votes |
@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); }
Example #5
Source File: User.java From DataHubSystem with GNU Affero General Public License v3.0 | 6 votes |
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 (); }
Example #6
Source File: NotificationService.java From org.openhab.ui.habot with Eclipse Public License 1.0 | 6 votes |
/** * 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); }
Example #7
Source File: JWTClientUtil.java From carbon-device-mgt with Apache License 2.0 | 6 votes |
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; }
Example #8
Source File: QlassifiedCrypto.java From Qlassified-Android with MIT License | 6 votes |
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; } }
Example #9
Source File: DESCipherWrapper.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
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; }
Example #10
Source File: DexWriter.java From ZjDroid with Apache License 2.0 | 6 votes |
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(); }
Example #11
Source File: KeyPairSnowflakeCredentials.java From beam with Apache License 2.0 | 6 votes |
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"); } }
Example #12
Source File: RSAEncodeUtils.java From markdown-image-kit with MIT License | 6 votes |
@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); }
Example #13
Source File: KeyManagerImpl.java From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License | 6 votes |
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; }
Example #14
Source File: ConfigContainer.java From modeldb with Apache License 2.0 | 6 votes |
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); }
Example #15
Source File: PlatformKeyManager.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
/** * 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); }
Example #16
Source File: ResourceAuthenticator.java From spring-boot-protocol with Apache License 2.0 | 6 votes |
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); } }
Example #17
Source File: MacSyslogMessageModifier.java From syslog4j with GNU Lesser General Public License v2.1 | 6 votes |
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); } }
Example #18
Source File: JdkHashCalculatorTest.java From hash-checker with Apache License 2.0 | 5 votes |
@Test public void sha512FromString() throws NoSuchAlgorithmException { assertEquals( "c6ee9e33cf5c6715a1d148fd73f7318884b41adcb916021e2bc0e800a5c5dd97f5142178f6ae88c8fdd98e1afb0ce4c8d2c54b5f37b30b7da1997bb33b0b8a31", getJdkHashCalculatorFor(HashType.SHA_512).fromString(inputText) ); }
Example #19
Source File: CommTest.java From beakerx with Apache License 2.0 | 5 votes |
@Test public void commSend_sentMessageHasCommId() throws NoSuchAlgorithmException { //when comm.send(COMM_MSG, Buffer.EMPTY, comm.getData()); //then assertThat(kernel.getPublishedMessages()).isNotEmpty(); Message sendMessage = kernel.getPublishedMessages().get(0); assertThat((String) sendMessage.getContent().get(Comm.COMM_ID)).isNotEmpty(); }
Example #20
Source File: SignatureFileVerifier.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
/** * Given the PKCS7 block and SignerInfo[], create an array of * CodeSigner objects. We do this only *once* for a given * signature block file. */ private CodeSigner[] getSigners(SignerInfo[] infos, PKCS7 block) throws IOException, NoSuchAlgorithmException, SignatureException, CertificateException { ArrayList<CodeSigner> signers = null; for (int i = 0; i < infos.length; i++) { SignerInfo info = infos[i]; ArrayList<X509Certificate> chain = info.getCertificateChain(block); CertPath certChain = certificateFactory.generateCertPath(chain); if (signers == null) { signers = new ArrayList<>(); } // Append the new code signer signers.add(new CodeSigner(certChain, info.getTimestamp())); if (debug != null) { debug.println("Signature Block Certificate: " + chain.get(0)); } } if (signers != null) { return signers.toArray(new CodeSigner[signers.size()]); } else { return null; } }
Example #21
Source File: Random.java From swift-k with Apache License 2.0 | 5 votes |
@Override protected Node compileBody(WrapperNode w, Scope argScope, Scope scope) throws CompilationException { try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new CompilationException(w, "Cannot get SHA-1 instance"); } return super.compileBody(w, argScope, scope); }
Example #22
Source File: DSSUtilsTest.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
@Test public void loadEdDSACert() throws NoSuchAlgorithmException, IOException { // RFC 8410 Security.addProvider(DSSSecurityProvider.getSecurityProvider()); CertificateToken token = DSSUtils.loadCertificateFromBase64EncodedString( "MIIBLDCB36ADAgECAghWAUdKKo3DMDAFBgMrZXAwGTEXMBUGA1UEAwwOSUVURiBUZXN0IERlbW8wHhcNMTYwODAxMTIxOTI0WhcNNDAxMjMxMjM1OTU5WjAZMRcwFQYDVQQDDA5JRVRGIFRlc3QgRGVtbzAqMAUGAytlbgMhAIUg8AmJMKdUdIt93LQ+91oNvzoNJjga9OukqY6qm05qo0UwQzAPBgNVHRMBAf8EBTADAQEAMA4GA1UdDwEBAAQEAwIDCDAgBgNVHQ4BAQAEFgQUmx9e7e0EM4Xk97xiPFl1uQvIuzswBQYDK2VwA0EAryMB/t3J5v/BzKc9dNZIpDmAgs3babFOTQbs+BolzlDUwsPrdGxO3YNGhW7Ibz3OGhhlxXrCe1Cgw1AH9efZBw=="); assertNotNull(token); logger.info("{}", token); logger.info("{}", token.getPublicKey()); assertFalse(token.isSelfSigned()); assertFalse(token.isSignedBy(token)); assertEquals(SignatureAlgorithm.ED25519, token.getSignatureAlgorithm()); assertTrue(token.checkKeyUsage(KeyUsageBit.KEY_AGREEMENT)); assertEquals(EncryptionAlgorithm.X25519, EncryptionAlgorithm.forKey(token.getPublicKey())); X509CertificateHolder holder = new X509CertificateHolder(token.getEncoded()); SubjectPublicKeyInfo subjectPublicKeyInfo = holder.getSubjectPublicKeyInfo(); assertNotNull(subjectPublicKeyInfo); assertEquals(EncryptionAlgorithm.X25519.getOid(), subjectPublicKeyInfo.getAlgorithm().getAlgorithm().getId()); token = DSSUtils .loadCertificateFromBase64EncodedString( "MIIBCDCBuwIUGW78zw0OL0GptJi++a91dBa7DsQwBQYDK2VwMCcxCzAJBgNVBAYTAkRFMRgwFgYDVQQDDA93d3cuZXhhbXBsZS5jb20wHhcNMTkwMzMxMTc1MTIyWhcNMjEwMjI4MTc1MTIyWjAnMQswCQYDVQQGEwJERTEYMBYGA1UEAwwPd3d3LmV4YW1wbGUuY29tMCowBQYDK2VwAyEAK87g0b8CC1eA5mvKXt9uezZwJYWEyg74Y0xTZEkqCcwwBQYDK2VwA0EAIIu/aa3Qtr3IE5to/nvWVY9y3ciwG5DnA70X3ALUhFs+U5aLtfY8sNT1Ng72ht+UBwByuze20UsL9qMsmknQCA=="); assertNotNull(token); logger.info("{}", token); logger.info("{}", token.getPublicKey()); assertEquals(SignatureAlgorithm.ED25519, token.getSignatureAlgorithm()); assertEquals(EncryptionAlgorithm.ED25519, EncryptionAlgorithm.forKey(token.getPublicKey())); assertTrue(token.isSelfSigned()); assertTrue(token.isSignedBy(token)); }
Example #23
Source File: Util.java From bcm-android with GNU General Public License v3.0 | 5 votes |
public static byte[] getSecretBytes(int size) { try { byte[] secret = new byte[size]; SecureRandom.getInstance("SHA1PRNG").nextBytes(secret); return secret; } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } }
Example #24
Source File: RecoverableKeyStoreDb.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
@Nullable private static PublicKey decodeX509Key(byte[] keyBytes) throws InvalidKeySpecException { X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(keyBytes); try { return KeyFactory.getInstance("EC").generatePublic(publicKeySpec); } catch (NoSuchAlgorithmException e) { // Should never happen throw new RuntimeException(e); } }
Example #25
Source File: UploadCertificate.java From certificate-transparency-java with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws IOException, CertificateException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { if (args.length < 1) { System.out.println( String.format( "Usage: %s <certificates chain> [output file]", UploadCertificate.class.getSimpleName())); return; } String pemFile = args[0]; List<Certificate> certs = CryptoDataLoader.certificatesFromFile(new File(pemFile)); System.out.println(String.format("Total number of certificates in chain: %d", certs.size())); HttpLogClient client = new HttpLogClient("http://ct.googleapis.com/pilot/ct/v1/"); Ct.SignedCertificateTimestamp resp = client.addCertificate(certs); System.out.println(resp); if (args.length >= 2) { String outputFile = args[1]; //TODO(eranm): Binary encoding compatible with the C++ code. Files.write(resp.toByteArray(), new File(outputFile)); } }
Example #26
Source File: DecryptingPartInputStream.java From Silence with GNU General Public License v3.0 | 5 votes |
private Cipher initializeCipher(SecretKeySpec key) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, IOException { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = readIv(cipher.getBlockSize()); cipher.init(Cipher.DECRYPT_MODE, key, iv); return cipher; }
Example #27
Source File: ProxyCacheUtils.java From HaoReader with GNU General Public License v3.0 | 5 votes |
public static String computeMD5(String string) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); byte[] digestBytes = messageDigest.digest(string.getBytes()); return bytesToHexString(digestBytes); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } }
Example #28
Source File: SecretKeyGenerator.java From Much-Assembly-Required with GNU General Public License v3.0 | 5 votes |
public SecretKeyGenerator() { try { keyGen = KeyGenerator.getInstance(KEY_GENERATION_ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error creating Key generator", e); } keyGen.init(new SecureRandom(SecureRandom.getSeed(32))); }
Example #29
Source File: HashingInstanceUrlIdGenerator.java From spring-boot-admin with Apache License 2.0 | 5 votes |
@Override public InstanceId generateId(Registration registration) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); byte[] bytes = digest.digest(registration.getHealthUrl().getBytes(StandardCharsets.UTF_8)); return InstanceId.of(new String(encodeHex(bytes, 0, 12))); } catch (NoSuchAlgorithmException ex) { throw new IllegalStateException(ex); } }
Example #30
Source File: UploadController.java From pdf-sign-check with MIT License | 5 votes |
@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"; }