List of usage examples for java.security Signature getInstance
public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:com.cedarsoft.crypt.X509Support.java
/** * <p>sign</p>/*from w w w . j a v a 2 s. c o m*/ * * @param plainText an array of byte. * @return a com.cedarsoft.crypt.Signature object. * * @throws GeneralSecurityException * if any. */ @Nonnull public com.cedarsoft.crypt.Signature sign(@Nonnull byte[] plainText) throws GeneralSecurityException { Signature signature = Signature.getInstance(SHA_256_WITH_RSA); signature.initSign(getPrivateKey()); signature.update(plainText); return new com.cedarsoft.crypt.Signature(signature.sign()); }
From source file:test.be.fedict.eid.applet.PKCS11Test.java
@Test public void testTokenHasBeenRemovedWorkaround() throws Exception { File tmpConfigFile = File.createTempFile("pkcs11-", "conf"); tmpConfigFile.deleteOnExit();//from w w w . j a v a 2s .c o m PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile), true); configWriter.println("name=SmartCard"); configWriter.println("library=/usr/lib/libbeidpkcs11.so.0"); configWriter.println("slotListIndex=1"); SunPKCS11 provider = new SunPKCS11(tmpConfigFile.getAbsolutePath()); Security.addProvider(provider); { KeyStore keyStore = KeyStore.getInstance("PKCS11", provider); keyStore.load(null, null); PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(privateKeyEntry.getPrivateKey()); byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); } JOptionPane.showMessageDialog(null, "Please remove and re-insert the token..."); Security.removeProvider(provider.getName()); { SunPKCS11 provider2 = new SunPKCS11(tmpConfigFile.getAbsolutePath()); Security.addProvider(provider2); KeyStore keyStore = KeyStore.getInstance("PKCS11", provider2); keyStore.load(null, null); PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(privateKeyEntry.getPrivateKey()); byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); Security.removeProvider(provider2.getName()); } }
From source file:org.apache.james.jdkim.IscheduleDKIMSigner.java
private byte[] signatureSign(final Headers h, final SignatureRecord sign, final PrivateKey key, final List<CharSequence> headers) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, PermFailException { Signature signature = Signature.getInstance(sign.getHashMethod().toString().toUpperCase() + "with" + sign.getHashKeyType().toString().toUpperCase()); signature.initSign(key);/*w w w . ja v a2 s . c o m*/ signatureCheck(h, sign, headers, signature); return signature.sign(); }
From source file:jp.alessandro.android.iab.Security.java
/** * Verifies that the signature from the server matches the computed * signature on the data. Returns true if the data is correctly signed. * * @param logger the logger to use for printing events * @param publicKey rsa public key generated by Google Play Developer Console * @param signedData signed data from server * @param signature server signature//from w w w. j a v a2s . c o m * @return true if the data and signature match */ protected boolean verify(Logger logger, PublicKey publicKey, String signedData, String signature) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, IllegalArgumentException { byte[] signatureBytes = Base64.decode(signature, Base64.DEFAULT); Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey); sig.update(signedData.getBytes("UTF-8")); if (!sig.verify(signatureBytes)) { logger.e(Logger.TAG, "Signature verification failed."); return false; } return true; }
From source file:com.streamsets.datacollector.publicrestapi.TestCredentialsDeploymentResource.java
@Test public void testSuccess() throws Exception { Properties sdcProps = new Properties(); sdcProps.setProperty("a", "b"); sdcProps.setProperty("c", "d"); sdcProps.setProperty("kerberos.client.keytab", "sdc.keytab"); sdcProps.setProperty("kerberos.client.enabled", "false"); sdcProps.setProperty("kerberos.client.principal", "sdc/_HOST@EXAMPLE.COM"); File sdcFile = new File(RuntimeInfoTestInjector.confDir, "sdc.properties"); Properties dpmProps = new Properties(); dpmProps.setProperty("x", "y"); dpmProps.setProperty("z", "a"); dpmProps.setProperty("dpm.enabled", "false"); dpmProps.setProperty("dpm.base.url", "http://localhost:18631"); File dpmFile = new File(RuntimeInfoTestInjector.confDir, "dpm.properties"); try (FileWriter fw = new FileWriter(sdcFile)) { sdcProps.store(fw, ""); }/*from w w w .j av a 2 s. co m*/ try (FileWriter fw = new FileWriter(dpmFile)) { dpmProps.store(fw, ""); } Response response = null; KeyPair keys = generateKeys(); mockCheckForCredentialsRequiredToTrue(); System.setProperty(DPM_AGENT_PUBLIC_KEY, Base64.getEncoder().encodeToString(keys.getPublic().getEncoded())); String token = "Frenchies and Pandas"; Signature sig = Signature.getInstance("SHA256withRSA"); sig.initSign(keys.getPrivate()); sig.update(token.getBytes(Charsets.UTF_8)); List<String> labels = Arrays.asList("deployment-prod-1", "deployment-prod-2"); CredentialsBeanJson json = new CredentialsBeanJson(token, "streamsets/172.1.1.0@EXAMPLE.COM", Base64.getEncoder().encodeToString("testKeytab".getBytes(Charsets.UTF_8)), Base64.getEncoder().encodeToString(sig.sign()), "https://dpm.streamsets.com:18631", Arrays.asList("deployment-prod-1", "deployment-prod-2"), "deployment1:org"); try { response = target("/v1/deployment/deployCredentials").request().post(Entity.json(json)); Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); CredentialDeploymentResponseJson responseJson = OBJECT_MAPPER .readValue((InputStream) response.getEntity(), CredentialDeploymentResponseJson.class); Assert.assertEquals(CredentialDeploymentStatus.CREDENTIAL_USED_AND_DEPLOYED, responseJson.getCredentialDeploymentStatus()); // Verify sdc.properties sdcProps = new Properties(); try (FileReader fr = new FileReader(sdcFile)) { sdcProps.load(fr); } Assert.assertEquals("b", sdcProps.getProperty("a")); Assert.assertEquals("d", sdcProps.getProperty("c")); Assert.assertEquals("streamsets/172.1.1.0@EXAMPLE.COM", sdcProps.getProperty("kerberos.client.principal")); Assert.assertEquals("true", sdcProps.getProperty("kerberos.client.enabled")); Assert.assertEquals("sdc.keytab", sdcProps.getProperty("kerberos.client.keytab")); byte[] keyTab = Files.toByteArray(new File(RuntimeInfoTestInjector.confDir, "sdc.keytab")); Assert.assertEquals("testKeytab", new String(keyTab, Charsets.UTF_8)); response = target("/v1/definitions").request().get(); Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); dpmProps = new Properties(); try (FileReader fr = new FileReader(dpmFile)) { dpmProps.load(fr); } Assert.assertEquals("y", dpmProps.getProperty("x")); Assert.assertEquals("a", dpmProps.getProperty("z")); Assert.assertEquals("true", dpmProps.getProperty("dpm.enabled")); Assert.assertEquals( Configuration.FileRef.PREFIX + "application-token.txt" + Configuration.FileRef.SUFFIX, dpmProps.getProperty("dpm.appAuthToken")); Assert.assertEquals("https://dpm.streamsets.com:18631", dpmProps.getProperty("dpm.base.url")); Assert.assertEquals(StringUtils.join(labels.toArray(), ","), dpmProps.getProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS)); Assert.assertEquals("deployment1:org", dpmProps.getProperty(RemoteSSOService.DPM_DEPLOYMENT_ID)); File tokenFile = new File(RuntimeInfoTestInjector.confDir, "application-token.txt"); try (FileInputStream fr = new FileInputStream(tokenFile)) { int len = token.length(); byte[] tokenBytes = new byte[len]; Assert.assertEquals(len, fr.read(tokenBytes)); Assert.assertEquals(token, new String(tokenBytes, Charsets.UTF_8)); } //Test redeploying the credentials again response = target("/v1/deployment/deployCredentials").request().post(Entity.json(json)); responseJson = OBJECT_MAPPER.readValue((InputStream) response.getEntity(), CredentialDeploymentResponseJson.class); Assert.assertEquals(CredentialDeploymentStatus.CREDENTIAL_NOT_USED_ALREADY_DEPLOYED, responseJson.getCredentialDeploymentStatus()); } finally { if (response != null) { response.close(); } } }
From source file:org.apache.sshd.common.util.SecurityUtils.java
public static synchronized Signature getSignature(String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException { register();// w w w .j a va 2s .c o m if (getSecurityProvider() == null) { return Signature.getInstance(algorithm); } else { return Signature.getInstance(algorithm, getSecurityProvider()); } }
From source file:com.vmware.o11n.plugin.crypto.service.CryptoRSAService.java
/** * Creates an RSA Signature/*w ww.jav a 2 s. c o m*/ * * @param pemKey RSA Private Key * @param dataB64 Base64 encoded data to sign * @return Base64 encoded signature * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws IOException * @throws InvalidKeyException * @throws SignatureException */ public String sign(String pemKey, String dataB64) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, InvalidKeyException, SignatureException { String signatureB64 = null; PrivateKey privateKey = null; Key key = null; try { key = CryptoUtil.getKey(pemKey); } catch (IOException e) { //try to fix key: key = CryptoUtil.getKey(CryptoUtil.fixPemString(pemKey)); } if (key instanceof PrivateKey) { privateKey = (PrivateKey) key; } else { throw new IllegalArgumentException("Invalid key object type: " + key.getClass().getName()); } Signature signer = Signature.getInstance(SIGNATURE_ALGORITHM); signer.initSign(privateKey); signer.update(Base64.decodeBase64(dataB64)); byte[] sigBytes = signer.sign(); signatureB64 = Base64.encodeBase64String(sigBytes); return signatureB64; }
From source file:mx.bigdata.sat.cfd.CFDv2.java
public void verificar(Certificate cert) throws Exception { String sigStr = document.getSello(); Base64 b64 = new Base64(); byte[] signature = b64.decode(sigStr); byte[] bytes = getOriginalBytes(); boolean md5 = true; if (getYear() < 2011) { Signature sig = Signature.getInstance("MD5withRSA"); sig.initVerify(cert);/*from w w w. java 2 s . c om*/ sig.update(bytes); try { sig.verify(signature); } catch (SignatureException e) { // Not MD5 md5 = false; } } if (getYear() > 2010 || !md5) { Signature sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(cert); sig.update(bytes); boolean bool = sig.verify(signature); if (!bool) { throw new Exception("Invalid signature"); } } }
From source file:org.apache.james.jdkim.DKIMSigner.java
private byte[] signatureSign(Headers h, SignatureRecord sign, PrivateKey key, List<CharSequence> headers) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, PermFailException { Signature signature = Signature.getInstance(sign.getHashMethod().toString().toUpperCase() + "with" + sign.getHashKeyType().toString().toUpperCase()); signature.initSign(key);// www .ja v a 2 s. c o m signatureCheck(h, sign, headers, signature); return signature.sign(); }
From source file:com.muk.services.commerce.CryptoServiceImpl.java
@Override public String signature(String algorithm, String payload, PrivateKey privateKey) { Signature signator;/* w w w . j av a2 s .c o m*/ String signedPayload = "Failed"; try { signator = Signature.getInstance(algorithm); signator.initSign(privateKey); signator.update(payload.getBytes(StandardCharsets.UTF_8)); signedPayload = encodeUrlSafe(signator.sign()); } catch (final SignatureException sigEx) { LOG.error("Failed to sign payload.", sigEx); } catch (final InvalidKeyException keyEx) { LOG.error("Failed initialize with private key.", keyEx); } catch (final NoSuchAlgorithmException algEx) { LOG.error("Failed getting signature.", algEx); } return signedPayload; }