Java Examples for java.security.SignatureException
The following java examples will help you to understand the usage of java.security.SignatureException. These source code samples are taken from different open source projects.
Example 1
Project: gazpachoquest-master File: LoginShiroFilterTest.java View source code |
@Test
public void handleRequestTest() throws SignatureException, IOException {
ContainerRequestContext requestContext = createMock(ContainerRequestContext.class);
ClassResourceInfo resourceClass = createMock(ClassResourceInfo.class);
HttpHeaders headers = createMock(HttpHeaders.class);
UriInfo uriInfo = createMock(UriInfo.class);
String date = DateFormatUtils.SMTP_DATETIME_FORMAT.format(new Date());
String resource = "/questionnaires/61";
String method = "GET";
String stringToSign = new StringBuilder().append(method).append(" ").append(resource).append("\n").append(date).toString();
String apiKey = "B868UOHUTKUDWXM";
String secret = "IQO27YUZO8NJ7RADIK6SJ9BQZNYP4EMO";
String signature = HMACSignature.calculateRFC2104HMAC(stringToSign, secret);
String authToken = generateAuth(apiKey, signature);
expect(requestContext.getMethod()).andReturn(method);
expect(uriInfo.getRequestUri()).andReturn(URI.create("http://localhost:8080/gazpachoquest-rest-web/api/" + resource));
expect(requestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).andReturn(authToken);
expect(requestContext.getHeaderString(HttpHeaders.DATE)).andReturn(date);
expect(headers.getRequestHeader(HttpHeaders.AUTHORIZATION)).andReturn(Arrays.asList(authToken));
expect(headers.getRequestHeader(HttpHeaders.DATE)).andReturn(Arrays.asList(date));
expect(uriInfo.getPath()).andReturn(resource.substring(1));
replay(requestContext, resourceClass, uriInfo, headers);
loginShiroFilter.setUriInfo(uriInfo);
loginShiroFilter.setHeaders(headers);
loginShiroFilter.filter(requestContext);
}
Example 2
Project: bigbluebutton-master File: TurnServer.java View source code |
public TurnEntry generatePasswordFor(String userId) {
TurnEntry turn = null;
try {
long expiryTime = System.currentTimeMillis() / 1000 + ttl;
String username = expiryTime + COLON + userId;
String password = calculateRFC2104HMAC(username, secretKey);
turn = new TurnEntry(username, password, ttl, url);
} catch (SignatureException e) {
e.printStackTrace();
}
return turn;
}
Example 3
Project: Snap2Pass-master File: Signature.java View source code |
/** * Computes RFC 2104-compliant HMAC signature. * * @param data * The data to be signed. * @param key * The signing key. * @return * The Base64-encoded RFC 2104-compliant HMAC signature. * @throws * java.security.SignatureException when signature generation fails */ public static String calculateRFC2104HMAC(String data, String key) throws java.security.SignatureException { String result; try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac //result = Base64.encode(rawHmac); result = new String(Base64.encodeBase64(rawHmac)); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; }
Example 4
Project: cryptoapplet-master File: TimeStampFactory.java View source code |
public static TSResponse getTimeStampResponse(String strUrl, byte[] data, boolean calculateDigest, String digestAlgorithm) throws NoSuchAlgorithmException, IOException, SignatureException {
HttpTimestamper httpTimestamper = new HttpTimestamper(strUrl);
byte[] digest = data;
if (calculateDigest) {
MessageDigest messageDigest = MessageDigest.getInstance(digestAlgorithm);
digest = messageDigest.digest(data);
}
TSRequest request = new TSRequest(digest, digestAlgorithm);
request.requestCertificate(true);
TSResponse response = httpTimestamper.generateTimestamp(request);
return response;
}
Example 5
Project: jjwt-master File: RsaSignatureValidator.java View source code |
@Override
public boolean isValid(byte[] data, byte[] signature) {
if (key instanceof PublicKey) {
Signature sig = createSignatureInstance();
PublicKey publicKey = (PublicKey) key;
try {
return doVerify(sig, publicKey, data, signature);
} catch (Exception e) {
String msg = "Unable to verify RSA signature using configured PublicKey. " + e.getMessage();
throw new SignatureException(msg, e);
}
} else {
Assert.notNull(this.SIGNER, "RSA Signer instance cannot be null. This is a bug. Please report it.");
byte[] computed = this.SIGNER.sign(data);
return Arrays.equals(computed, signature);
}
}
Example 6
Project: bc-java-master File: JcaTlsRSAVerifier.java View source code |
public TlsStreamVerifier getStreamVerifier(final DigitallySigned signature) throws IOException {
SignatureAndHashAlgorithm algorithm = signature.getAlgorithm();
/*
* NOTE: The SunMSCAPI provider's "NoneWithRSA" can't produce/verify RSA signatures in the correct format for TLS 1.2
*/
if (algorithm != null && algorithm.getSignature() == SignatureAlgorithm.rsa && JcaUtils.isSunMSCAPIProviderActive()) {
try {
Signature rawVerifier = getRawVerifier();
if (JcaUtils.isSunMSCAPIProvider(rawVerifier.getProvider())) {
String algorithmName = JcaUtils.getJcaAlgorithmName(algorithm);
final Signature verifier = helper.createSignature(algorithmName);
verifier.initVerify(pubKeyRSA);
return new TlsStreamVerifier() {
public OutputStream getOutputStream() {
return new SignatureOutputStream(verifier);
}
public boolean isVerified() throws IOException {
try {
return verifier.verify(signature.getSignature());
} catch (SignatureException e) {
throw new TlsFatalAlert(AlertDescription.internal_error, e);
}
}
};
}
} catch (GeneralSecurityException e) {
throw new TlsFatalAlert(AlertDescription.internal_error, e);
}
}
return null;
}
Example 7
Project: camelinaction2-master File: ManInTheMiddleTest.java View source code |
@Test
public void testSignAndVerifyMessage() throws Exception {
getMockEndpoint("mock:signed").expectedBodiesReceived("Hello World");
try {
template.sendBody("direct:sign", "Hello World");
} catch (CamelExecutionException e) {
assertMockEndpointsSatisfied();
assertIsInstanceOf(SignatureException.class, e.getCause());
}
}
Example 8
Project: irma_future_id-master File: SmartCardSignerCredential.java View source code |
@Override
public byte[] generateCertificateSignature(@Nonnull byte[] md5andsha1) throws IOException {
// Certificate.EMPTY_CHAIN
if (!certificate.equals(Certificate.EMPTY_CHAIN)) {
try {
return signerImpl.sign(md5andsha1);
} catch (SignatureException ex) {
throw new IOException("Failed to create signature because of an unknown error.", ex);
} catch (CredentialPermissionDenied ex) {
throw new IOException("Failed to create signature because of missing permissions.", ex);
}
} else {
return new byte[] {};
}
}
Example 9
Project: jsontoken-master File: SignedTokenAudienceChecker.java View source code |
private static void checkUri(String ourUriString, String tokenUriString) throws SignatureException { URI ourUri = URI.create(ourUriString); URI tokenUri = URI.create(tokenUriString); if (!ourUri.getScheme().equalsIgnoreCase(tokenUri.getScheme())) { throw new SignatureException("scheme in token URI (" + tokenUri.getScheme() + ") is wrong"); } if (!ourUri.getAuthority().equalsIgnoreCase(tokenUri.getAuthority())) { throw new SignatureException("authority in token URI (" + tokenUri.getAuthority() + ") is wrong"); } if (!Objects.equal(ourUri.getPath(), tokenUri.getPath())) { throw new SignatureException("path in token URI (" + tokenUri.getAuthority() + ") is wrong"); } if (!Objects.equal(ourUri.getQuery(), tokenUri.getQuery())) { throw new SignatureException("query string in URI (" + tokenUri.getQuery() + ") is wrong"); } }
Example 10
Project: Mineshafter-Launcher-master File: Signer.java View source code |
public byte[] sign(byte[] data) {
Signature signature;
try {
signature = Signature.getInstance("SHA1withRSA");
signature.initSign(key);
signature.update(data);
return signature.sign();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
}
return null;
}
Example 11
Project: oauth-master File: RSASha1SignatureService.java View source code |
/**
* {@inheritDoc}
*/
@Override
public String getSignature(String baseString, String apiSecret, String tokenSecret) {
try {
final Signature signature = Signature.getInstance(RSA_SHA1);
signature.initSign(privateKey);
signature.update(baseString.getBytes(UTF8));
return bytesToBase64String(signature);
} catch (NoSuchAlgorithmExceptionInvalidKeyException | SignatureException | UnsupportedEncodingException | RuntimeException | e) {
throw new OAuthSignatureException(baseString, e);
}
}
Example 12
Project: Resteasy-master File: KeyTools.java View source code |
public static X509Certificate generateTestCertificate(String subject, String issuer, KeyPair pair) throws InvalidKeyException, NoSuchProviderException, SignatureException {
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setIssuerDN(new X500Principal(issuer));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000));
certGen.setSubjectDN(new X500Principal(subject));
certGen.setPublicKey(pair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}
Example 13
Project: RipplePower-master File: DSABase.java View source code |
protected boolean engineVerify(byte[] sigBytes) throws SignatureException { byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); BigInteger[] sig; try { sig = encoder.decode(sigBytes); } catch (Exception e) { throw new SignatureException("error decoding signature bytes."); } return signer.verifySignature(hash, sig[0], sig[1]); }
Example 14
Project: scribe-master File: RSASha1SignatureService.java View source code |
/**
* {@inheritDoc}
*/
@Override
public String getSignature(String baseString, String apiSecret, String tokenSecret) {
try {
final Signature signature = Signature.getInstance(RSA_SHA1);
signature.initSign(privateKey);
signature.update(baseString.getBytes(UTF8));
return bytesToBase64String(signature);
} catch (NoSuchAlgorithmExceptionInvalidKeyException | SignatureException | UnsupportedEncodingException | RuntimeException | e) {
throw new OAuthSignatureException(baseString, e);
}
}
Example 15
Project: scribejava-master File: RSASha1SignatureService.java View source code |
/**
* {@inheritDoc}
*/
@Override
public String getSignature(String baseString, String apiSecret, String tokenSecret) {
try {
final Signature signature = Signature.getInstance(RSA_SHA1);
signature.initSign(privateKey);
signature.update(baseString.getBytes(UTF8));
return bytesToBase64String(signature);
} catch (NoSuchAlgorithmExceptionInvalidKeyException | SignatureException | UnsupportedEncodingException | RuntimeException | e) {
throw new OAuthSignatureException(baseString, e);
}
}
Example 16
Project: malcom-lib-android-master File: DigestUtils.java View source code |
/** * Computes RFC 2104-compliant HMAC signature. * * @param data The data to be signed. * @param key The signing key. * @return The Base64-encoded RFC 2104-compliant HMAC signature. * @throws java.security.SignatureException * when signature generation fails */ public static String calculateRFC2104HMAC(String data, String key) throws java.security.SignatureException { try { // Get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(UTF_8), mac.getAlgorithm()); mac.init(signingKey); // Compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes(UTF_8)); //It is important to use here the same implementation of B64 used in Malcom!!. return new String(Base64.encode(rawHmac)); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } }
Example 17
Project: cascading.simpledb-master File: AWSUtils.java View source code |
/** * Computes RFC 2104-compliant HMAC signature. * * @param data * The data to be signed. * @param key * The signing key. * @return The base64-encoded RFC 2104-compliant HMAC signature. * @throws java.security.SignatureException * when signature generation fails */ public static String generateSignature(String data, String key) throws SignatureException { try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac return Base64.encodeBytes(rawHmac); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } }
Example 18
Project: vuzitjava-master File: Service.java View source code |
// Private static methods /** * Computes RFC 2104-compliant HMAC signature. */ private static String calculateRFC2104HMAC(String data, String key) throws java.security.SignatureException { String result; try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac result = Base64.encodeBytes(rawHmac); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; }
Example 19
Project: alien-ofelia-conet-ccnx-master File: CCNMerkleTreeSigner.java View source code |
public void signBlocks(ContentObject[] contentObjects, Key signingKey) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException {
// Generate the signatures for these objects. This sets the
// signatures as a side effect
// DKS TODO remove side effect behavior.
CCNMerkleTree tree = new CCNMerkleTree(contentObjects, signingKey);
Log.info("Signed tree of " + tree.numLeaves() + " leaves, " + tree.nodeCount() + " nodes.");
}
Example 20
Project: atlas-lb-master File: PGPOnePassSignature.java View source code |
public void update(byte b) throws SignatureException {
if (signatureType == PGPSignature.CANONICAL_TEXT_DOCUMENT) {
if (b == '\r') {
sig.update((byte) '\r');
sig.update((byte) '\n');
} else if (b == '\n') {
if (lastb != '\r') {
sig.update((byte) '\r');
sig.update((byte) '\n');
}
} else {
sig.update(b);
}
lastb = b;
} else {
sig.update(b);
}
}
Example 21
Project: BitNomen-master File: CCNMerkleTreeSigner.java View source code |
public void signBlocks(ContentObject[] contentObjects, PrivateKey signingKey) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException {
// Generate the signatures for these objects. This sets the
// signatures as a side effect
// DKS TODO remove side effect behavior.
CCNMerkleTree tree = new CCNMerkleTree(contentObjects, signingKey);
Log.info("Signed tree of " + tree.numLeaves() + " leaves, " + tree.nodeCount() + " nodes.");
}
Example 22
Project: blogracy-master File: JwtSignature.java View source code |
public static String sign(String content, KeyPair keyPair) {
String result = null;
try {
String payload = Base64.encodeBase64URLSafeString(content.getBytes("UTF-8"));
byte[] encodedKey = keyPair.getPublic().getEncoded();
String kid = Base64.encodeBase64URLSafeString(encodedKey);
JSONObject headerObj = new JSONObject().put("typ", "JWT").put("alg", "RS256").put("kid", kid);
String header = Base64.encodeBase64URLSafeString(headerObj.toString().getBytes("UTF-8"));
byte[] bytesToSign = (header + "." + payload).getBytes("UTF-8");
Signature signer = Signature.getInstance("SHA256withRSA");
signer.initSign(keyPair.getPrivate());
signer.update(bytesToSign);
String signature = Base64.encodeBase64URLSafeString(signer.sign());
result = header + "." + payload + "." + signature;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
Example 23
Project: bugvm-master File: JcaContentSignerBuilder.java View source code |
public ContentSigner build(PrivateKey privateKey) throws OperatorCreationException {
try {
final Signature sig = helper.createSignature(sigAlgId);
if (random != null) {
sig.initSign(privateKey, random);
} else {
sig.initSign(privateKey);
}
return new ContentSigner() {
private SignatureOutputStream stream = new SignatureOutputStream(sig);
public AlgorithmIdentifier getAlgorithmIdentifier() {
return sigAlgId;
}
public OutputStream getOutputStream() {
return stream;
}
public byte[] getSignature() {
try {
return stream.getSignature();
} catch (SignatureException e) {
throw new RuntimeOperatorException("exception obtaining signature: " + e.getMessage(), e);
}
}
};
} catch (GeneralSecurityException e) {
throw new OperatorCreationException("cannot create signer: " + e.getMessage(), e);
}
}
Example 24
Project: ccnx-master File: CCNMerkleTreeSigner.java View source code |
public void signBlocks(ContentObject[] contentObjects, Key signingKey) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException {
// Generate the signatures for these objects. This sets the
// signatures as a side effect
// DKS TODO remove side effect behavior.
CCNMerkleTree tree = new CCNMerkleTree(contentObjects, signingKey);
Log.info("Signed tree of " + tree.numLeaves() + " leaves, " + tree.nodeCount() + " nodes.");
}
Example 25
Project: cloudpier-core-master File: BeansDescribeEnvironments.java View source code |
/** * Computes RFC 2104-compliant HMAC signature. * * @param data The data to be signed. * @return The base64-encoded RFC 2104-compliant HMAC signature. * @throws java.security.SignatureException * when signature generation fails */ protected String generateSignature(String data) throws java.security.SignatureException { String result; try { // get a hash key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(secretAccessKey.getBytes(), HASH_ALGORITHM); // get a hasher instance and initialize with the signing key Mac mac = Mac.getInstance(HASH_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac // result = Encoding.EncodeBase64(rawHmac); result = new BASE64Encoder().encode(rawHmac); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; }
Example 26
Project: coinbase-java-master File: CallbackVerifierImpl.java View source code |
@Override
public boolean verifyCallback(String body, String signature) {
try {
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initVerify(getPublicKey());
sig.update(body.getBytes());
return sig.verify(Base64.decodeBase64(signature));
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
} catch (InvalidKeyException ex) {
throw new RuntimeException(ex);
} catch (SignatureException e) {
return false;
}
}
Example 27
Project: drools-core-master File: KeyStoreHelperTest.java View source code |
public void testSignDataWithPrivateKey() throws UnsupportedEncodingException, UnrecoverableKeyException, InvalidKeyException, KeyStoreException, NoSuchAlgorithmException, SignatureException {
// The server signs the data with the private key
// Set properties to simulate the server
URL serverKeyStoreURL = getClass().getResource("droolsServer.keystore");
System.setProperty(KeyStoreHelper.PROP_SIGN, "true");
System.setProperty(KeyStoreHelper.PROP_PVT_KS_URL, serverKeyStoreURL.toExternalForm());
System.setProperty(KeyStoreHelper.PROP_PVT_KS_PWD, "serverpwd");
System.setProperty(KeyStoreHelper.PROP_PVT_ALIAS, "droolsKey");
System.setProperty(KeyStoreHelper.PROP_PVT_PWD, "keypwd");
KeyStoreHelper serverHelper = new KeyStoreHelper();
// get some data to sign
byte[] data = "Hello World".getBytes("UTF8");
// sign the data
byte[] signature = serverHelper.signDataWithPrivateKey(data);
// now, initialise the client helper
// Set properties to simulate the client
URL clientKeyStoreURL = getClass().getResource("droolsClient.keystore");
System.setProperty(KeyStoreHelper.PROP_SIGN, "true");
System.setProperty(KeyStoreHelper.PROP_PUB_KS_URL, clientKeyStoreURL.toExternalForm());
System.setProperty(KeyStoreHelper.PROP_PUB_KS_PWD, "clientpwd");
// client needs no password to access the certificate and public key
KeyStoreHelper clientHelper = new KeyStoreHelper();
// check the signature against the data
assertTrue(clientHelper.checkDataWithPublicKey("droolsKey", data, signature));
// check some fake data
assertFalse(clientHelper.checkDataWithPublicKey("droolsKey", "fake".getBytes("UTF8"), signature));
}
Example 28
Project: droolsjbpm-master File: KeyStoreHelperTest.java View source code |
public void testSignDataWithPrivateKey() throws UnsupportedEncodingException, UnrecoverableKeyException, InvalidKeyException, KeyStoreException, NoSuchAlgorithmException, SignatureException {
// The server signs the data with the private key
// Set properties to simulate the server
URL serverKeyStoreURL = getClass().getResource("droolsServer.keystore");
System.setProperty(KeyStoreHelper.PROP_SIGN, "true");
System.setProperty(KeyStoreHelper.PROP_PVT_KS_URL, serverKeyStoreURL.toExternalForm());
System.setProperty(KeyStoreHelper.PROP_PVT_KS_PWD, "serverpwd");
System.setProperty(KeyStoreHelper.PROP_PVT_ALIAS, "droolsKey");
System.setProperty(KeyStoreHelper.PROP_PVT_PWD, "keypwd");
KeyStoreHelper serverHelper = new KeyStoreHelper();
// get some data to sign
byte[] data = "Hello World".getBytes("UTF8");
// sign the data
byte[] signature = serverHelper.signDataWithPrivateKey(data);
// now, initialise the client helper
// Set properties to simulate the client
URL clientKeyStoreURL = getClass().getResource("droolsClient.keystore");
System.setProperty(KeyStoreHelper.PROP_SIGN, "true");
System.setProperty(KeyStoreHelper.PROP_PUB_KS_URL, clientKeyStoreURL.toExternalForm());
System.setProperty(KeyStoreHelper.PROP_PUB_KS_PWD, "clientpwd");
// client needs no password to access the certificate and public key
KeyStoreHelper clientHelper = new KeyStoreHelper();
// check the signature against the data
assertTrue(clientHelper.checkDataWithPublicKey("droolsKey", data, signature));
// check some fake data
assertFalse(clientHelper.checkDataWithPublicKey("droolsKey", "fake".getBytes("UTF8"), signature));
}
Example 29
Project: eucalyptus-fork-2.0-master File: Signatures.java View source code |
public String sign(PrivateKey pk, byte[] data) throws InvalidKeyException, SignatureException { Signature signer = this.getInstance(); signer.initSign(pk); try { signer.update(data); byte[] sig = signer.sign(); final StringBuilder hex = new StringBuilder(2 * sig.length); for (final byte b : sig) { hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F))); } return hex.toString().toLowerCase(); } catch (SignatureException e) { LOG.debug(e, e); throw e; } }
Example 30
Project: ggp-base-master File: SignableJSON.java View source code |
public static boolean verifySignedJSON(JSONObject theJSON) throws JSONException {
if (!theJSON.has("matchHostPK") || !theJSON.has("matchHostSignature"))
throw new RuntimeException("JSON not signed! Cannot verify.");
String thePK = theJSON.getString("matchHostPK");
String theSignature = theJSON.getString("matchHostSignature");
if (!theSignature.startsWith(theCanonicalizationPrefix))
return false;
theSignature = theSignature.replaceFirst(theCanonicalizationPrefix, "");
JSONObject tempObject = new JSONObject(theJSON.toString());
tempObject.remove("matchHostSignature");
try {
return BaseCryptography.verifySignature(thePK, theSignature, CanonicalJSON.getCanonicalForm(tempObject, CanonicalizationStrategy.SIMPLE));
} catch (InvalidKeyException e) {
} catch (SignatureException e) {
} catch (NoSuchAlgorithmException e) {
} catch (UnsupportedEncodingException e) {
}
return false;
}
Example 31
Project: hazelcast-archive-master File: RFC2104HMAC.java View source code |
public static String calculateRFC2104HMAC(String data, String key) throws SignatureException { String result = null; try { SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), SIGNATURE_METHOD); Mac mac = Mac.getInstance(SIGNATURE_METHOD); mac.init(signingKey); byte[] rawSignature = mac.doFinal(data.getBytes()); result = new String(encode(rawSignature)); result = result.trim(); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; }
Example 32
Project: jetty-bootstrap-master File: AbstractJettyKeystore.java View source code |
public static void checkValidity(KeyStore keystore, String keystoreAlias, boolean checkValidity, boolean verifySignature) throws JettyKeystoreException {
try {
Objects.requireNonNull(keystore, "Keystore can not be null");
Certificate certificate = keystore.getCertificate(keystoreAlias);
Objects.requireNonNull(certificate, "Certificate is unreacheable");
X509Certificate x509Certificate = (X509Certificate) certificate;
if (checkValidity) {
x509Certificate.checkValidity();
}
if (verifySignature) {
x509Certificate.verify(certificate.getPublicKey());
}
} catch (NullPointerExceptionInvalidKeyException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException | KeyStoreException | e) {
throw new JettyKeystoreException(JettyKeystoreException.ERROR_INVALID_KEYSTORE, "Keystore is not valid", e);
}
}
Example 33
Project: LimeWire-Pirate-Edition-master File: Verifier.java View source code |
/** Does the verification. */
public void run() {
SecureMessage message = getSecureMessage();
SecureMessageCallback callback = getSecureMessageCallback();
PublicKey pubKey = getPublicKey();
String algorithm = getAlgorithm();
if (pubKey == null) {
LOG.warn("Cannot verify message without a public key.");
message.setSecureStatus(Status.INSECURE);
callback.handleSecureMessage(message, false);
return;
}
byte[] signature = message.getSecureSignature();
if (signature == null) {
LOG.warn("Cannot verify message without a signature.");
message.setSecureStatus(Status.INSECURE);
callback.handleSecureMessage(message, false);
return;
}
try {
Signature verifier = Signature.getInstance(algorithm);
verifier.initVerify(pubKey);
message.updateSignatureWithSecuredBytes(verifier);
if (verifier.verify(signature)) {
message.setSecureStatus(Status.SECURE);
callback.handleSecureMessage(message, true);
return;
}
// fallthrough on not secure & failures to set failed.
} catch (NoSuchAlgorithmException nsax) {
LOG.error("No alg.", nsax);
} catch (InvalidKeyException ikx) {
LOG.error("Invalid key", ikx);
} catch (SignatureException sx) {
LOG.error("Bad sig", sx);
} catch (ClassCastException ccx) {
LOG.error("bad cast", ccx);
}
message.setSecureStatus(Status.FAILED);
callback.handleSecureMessage(message, false);
}
Example 34
Project: Nimbus-JOSE-JWT-master File: RSASSAVerifier.java View source code |
@Override
public boolean verify(final ReadOnlyJWSHeader header, final byte[] signedContent, final Base64URL signature) throws JOSEException {
Signature verifier = getRSASignerAndVerifier(header.getAlgorithm());
try {
verifier.initVerify(publicKey);
verifier.update(signedContent);
return verifier.verify(signature.decode());
} catch (InvalidKeyException e) {
throw new JOSEException("Invalid public RSA key: " + e.getMessage(), e);
} catch (SignatureException e) {
throw new JOSEException("RSA signature exception: " + e.getMessage(), e);
}
}
Example 35
Project: oobd-master File: JcaContentSignerBuilder.java View source code |
public ContentSigner build(PrivateKey privateKey) throws OperatorCreationException {
try {
final Signature sig = helper.createSignature(sigAlgId);
if (random != null) {
sig.initSign(privateKey, random);
} else {
sig.initSign(privateKey);
}
return new ContentSigner() {
private SignatureOutputStream stream = new SignatureOutputStream(sig);
public AlgorithmIdentifier getAlgorithmIdentifier() {
return sigAlgId;
}
public OutputStream getOutputStream() {
return stream;
}
public byte[] getSignature() {
try {
return stream.getSignature();
} catch (SignatureException e) {
throw new RuntimeOperatorException("exception obtaining signature: " + e.getMessage(), e);
}
}
};
} catch (GeneralSecurityException e) {
throw new OperatorCreationException("cannot create signer: " + e.getMessage(), e);
}
}
Example 36
Project: opencit-master File: AikValidityTest.java View source code |
@Test public void testPrivacyCASelfSignedCertificate() throws CertificateException, IOException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { // read privacy ca certificate // XXX TODO currently we only support one privacy CA cert... in the future we should read a PEM format file with possibly multiple trusted privacy ca certs InputStream privacyCaIn = new FileInputStream(new File("src/test/resources/PrivacyCA.2.crt")); X509Certificate privacyCaCert = X509Util.decodeDerCertificate(IOUtils.toByteArray(privacyCaIn)); IOUtils.closeQuietly(privacyCaIn); privacyCaCert.checkValidity(); // verify the trusted privacy ca signed this aik cert // NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException privacyCaCert.verify(privacyCaCert.getPublicKey()); }
Example 37
Project: QRCode-APG-master File: DSABase.java View source code |
protected boolean engineVerify(byte[] sigBytes) throws SignatureException { byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); BigInteger[] sig; try { sig = encoder.decode(sigBytes); } catch (Exception e) { throw new SignatureException("error decoding signature bytes."); } return signer.verifySignature(hash, sig[0], sig[1]); }
Example 38
Project: redPandaj-master File: Main.java View source code |
public static void main(String[] args) throws SignatureException, IOException {
// System.out.println("" + System.currentTimeMillis());
//
//
// ECKey ecKey = new ECKey();
//
// System.out.println("pub: " + Base58.encode(ecKey.getPubKey()));
// System.out.println("priv: " + Base58.encode(ecKey.getPrivKeyBytes()));
//
//
// String b = "jwbhfihwbfwyebgfwehfbvweufgvweufgvweufgvwefgvweufvweufnxyugnwxeufygmusfmuwugnwxeufygmusfmuwugnwxeufygmusfmuw";
//
// long start = System.currentTimeMillis();
//
// long bytes = 0;
// String signMessage = ecKey.signMessage(b);
//
//
//
// while (bytes < 35000) {
//
//
//
// bytes += b.length();
// //byte[] string2Byte = Identity.string2Byte(b);
//
// //Identity.byte2String(string2Byte);
//
// ecKey.verifyMessage(b, signMessage);
//
// System.out.println("bytes: " + bytes + " avg.: " + (bytes / ((System.currentTimeMillis() - start)*1.0))*1000/1024);
// }
byte[] key = new byte[32];
Random r = new SecureRandom();
r.nextBytes(key);
byte[] text = "asddwdwdwd".getBytes();
byte[] encode = AESCrypt.encode(key, text);
System.out.println(Utils.bytesToHexString(encode) + " " + encode.length);
byte[] toDecode = new byte[encode.length * 2];
System.arraycopy(encode, 0, toDecode, 0, 16);
System.arraycopy(encode, 0, toDecode, 16, 16);
System.out.println("decodeysize_: " + toDecode.length + " " + Utils.bytesToHexString(toDecode));
String string = new String(AESCrypt.decode(key, toDecode));
System.out.println(string + " " + string.length());
}
Example 39
Project: robovm-master File: SignatureHelper.java View source code |
public void test(PrivateKey encryptKey, PublicKey decryptKey) { Signature signature = null; try { signature = Signature.getInstance(algorithmName); } catch (NoSuchAlgorithmException e) { Assert.fail(e.getMessage()); } try { signature.initSign(encryptKey); } catch (InvalidKeyException e) { Assert.fail(e.getMessage()); } try { signature.update(plainData.getBytes()); } catch (SignatureException e) { Assert.fail(e.getMessage()); } byte[] signed = null; try { signed = signature.sign(); } catch (SignatureException e) { Assert.fail(e.getMessage()); } try { signature.initVerify(decryptKey); } catch (InvalidKeyException e) { Assert.fail(e.getMessage()); } try { signature.update(plainData.getBytes()); } catch (SignatureException e) { Assert.fail(e.getMessage()); } try { Assert.assertTrue("signature could not be verified", signature.verify(signed)); } catch (SignatureException e) { Assert.fail(e.getMessage()); } }
Example 40
Project: SAMLRaider-master File: CertificateStoreTest.java View source code |
@Before
public void setup() throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, NoSuchProviderException, InvalidKeySpecException, IOException {
Security.addProvider(new BouncyCastleProvider());
burpCertificateStore = new BurpCertificateStore();
// Single Certificate
BurpCertificateBuilder b1 = new BurpCertificateBuilder("CN=example.net");
BurpCertificate c1 = b1.generateSelfSignedCertificate();
burpCertificateStore.addCertificate(c1);
// Single Certificate
BurpCertificateBuilder b2 = new BurpCertificateBuilder("CN=foobar.net");
BurpCertificate c2 = b2.generateSelfSignedCertificate();
burpCertificateStore.addCertificate(c2);
// Single Certificate
BurpCertificateBuilder b3 = new BurpCertificateBuilder("CN=gugus.lan");
BurpCertificate c3 = b3.generateSelfSignedCertificate();
burpCertificateStore.addCertificate(c3);
// Certificate Chain
CertificateTabController certificateTabController = new CertificateTabController(new CertificateTab());
List<BurpCertificate> certificateChain = certificateTabController.importCertificateChain("src/test/resources/hsr_chain.pem");
burpCertificateStore.addCertificateChain(certificateChain);
certificateTabController.cloneCertificateChain(certificateChain);
}
Example 41
Project: servkeeper-master File: TestSignature.java View source code |
@Test
public void test() throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeyException, NoSuchProviderException, SignatureException, DecoderException {
byte[] assinatura = SignerSample.signTestFile();
assertTrue(assinatura != null);
String saida = Hex.encodeHexString(assinatura);
logger.debug("Assinatura: " + saida);
// Verifica a assinatura:
InputStream filepath = SignerSample.class.getClassLoader().getResourceAsStream("arquivo.txt");
byte[] bTexto = IOUtils.toByteArray(filepath);
String texto = new String(bTexto, "UTF-8");
logger.debug("Texto: " + texto);
boolean resultado = VerifySignature.verify(saida, texto, "*", "meucertificado", "teste001");
assertTrue(resultado);
/*
// Verifica com keystore externa (troque o path antes de rodar esse teste)
resultado = VerifySignature.verify(saida, texto,
"/home/cleuton/wsDropwizard01/certstore/verifykeystore.jks",
"meucertificado", "teste001");
assertTrue(resultado);
*/
// Altera o texto e verifica novamente:
bTexto[5] = 61;
String texto2 = new String(bTexto, "UTF-8");
resultado = VerifySignature.verify(saida, texto2, "*", "meucertificado", "teste001");
assertFalse(resultado);
}
Example 42
Project: sothis-master File: SignatureUtils.java View source code |
public static String sign(String secretKey, Map<String, String[]> requestParams) throws SignatureException {
Map<String, String[]> sortedRequestParams = new TreeMap<String, String[]>(requestParams);
StringBuilder dataString = new StringBuilder();
for (Map.Entry<String, String[]> entry : sortedRequestParams.entrySet()) {
dataString.append(entry.getKey());
String[] sortedValues;
if (entry.getValue().length <= 1) {
sortedValues = entry.getValue();
} else {
sortedValues = new String[entry.getValue().length];
System.arraycopy(entry.getValue(), 0, sortedValues, 0, sortedValues.length);
Arrays.sort(sortedValues);
}
for (String value : sortedValues) {
dataString.append(value);
}
}
return sign(secretKey, dataString.toString());
}
Example 43
Project: TLSDemo-master File: PEMTrustManager.java View source code |
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
boolean ok = false;
for (X509Certificate cert : chain) {
Log.e(TAG, "sigAlgName: " + cert.getSigAlgName() + "; SigAlgOID: " + cert.getSigAlgOID());
try {
Log.e(TAG, "public key algorithm: " + mCert.getPublicKey().getAlgorithm() + "; form: " + mCert.getPublicKey().getFormat() + "; key: " + mCert.getPublicKey().toString());
Log.e(TAG, "public key base64: " + Base64.encodeToString(mCert.getPublicKey().getEncoded(), Base64.DEFAULT));
cert.verify(mCert.getPublicKey());
ok = true;
break;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
}
}
if (!ok) {
throw new CertificateException();
}
}
Example 44
Project: tum-campus-master File: RSASigner.java View source code |
/** * Sign the message given as the parameter and return it as a base64 encoded * {@link String}. * * @param message The message to be encoded * @return A base64 encoded signature */ public String sign(String message) { Signature signer = getSignatureInstance(); try { signer.initSign(privateKey); } catch (InvalidKeyException e) { Utils.log(e); return null; } byte[] messageBytes = message.getBytes(Charsets.UTF_8); try { signer.update(messageBytes); } catch (SignatureException e) { Utils.log(e); return null; } byte[] signature; try { signature = signer.sign(); } catch (SignatureException e) { Utils.log(e); return null; } return Base64.encodeToString(signature, Base64.DEFAULT); }
Example 45
Project: TumCampusApp-master File: RSASigner.java View source code |
/** * Sign the message given as the parameter and return it as a base64 encoded * {@link String}. * * @param message The message to be encoded * @return A base64 encoded signature */ public String sign(String message) { Signature signer = getSignatureInstance(); try { signer.initSign(privateKey); } catch (InvalidKeyException e) { Utils.log(e); return null; } byte[] messageBytes = message.getBytes(Charsets.UTF_8); try { signer.update(messageBytes); } catch (SignatureException e) { Utils.log(e); return null; } byte[] signature; try { signature = signer.sign(); } catch (SignatureException e) { Utils.log(e); return null; } return Base64.encodeToString(signature, Base64.DEFAULT); }
Example 46
Project: UNH_NDN-master File: CCNMerkleTreeSigner.java View source code |
public void signBlocks(ContentObject[] contentObjects, PrivateKey signingKey) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException {
// Generate the signatures for these objects. This sets the
// signatures as a side effect
// DKS TODO remove side effect behavior.
CCNMerkleTree tree = new CCNMerkleTree(contentObjects, signingKey);
Log.info("Signed tree of " + tree.numLeaves() + " leaves, " + tree.nodeCount() + " nodes.");
}
Example 47
Project: XobotOS-master File: DSABase.java View source code |
protected boolean engineVerify(byte[] sigBytes) throws SignatureException { byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); BigInteger[] sig; try { sig = encoder.decode(sigBytes); } catch (Exception e) { throw new SignatureException("error decoding signature bytes."); } return signer.verifySignature(hash, sig[0], sig[1]); }
Example 48
Project: cagrid2-master File: SSLCertificateVerify.java View source code |
public int encode(SSLConn conn, OutputStream s) throws IOException {
try {
PrivateKey pk = conn.ctx.getPrivateKey();
String alg = getCVAlg(pk.getAlgorithm());
Signature sig = Signature.getInstance(alg);
sig.initSign(pk);
if (alg.equals("RawRSA")) {
((Blindable) sig).setBlindingInfo(conn.hs.rng, (CryptixRSAPublicKey) conn.ctx.getPublicKey());
}
SSLDebug.debug(SSLDebug.DEBUG_CRYPTO, "Certificate verify toBeSigned", toBeSigned);
// For DSA we sign only the SHA
if (alg.equals("RawDSA")) {
sig.setParameter("SecureRandom", conn.hs.rng);
sig.update(toBeSigned, 16, 20);
} else {
sig.update(toBeSigned, 0, toBeSigned.length);
}
byte[] sig_bytes = sig.sign();
// Test
// sig_bytes[sig_bytes.length-1]++;
SSLDebug.debug(SSLDebug.DEBUG_CRYPTO, "Certificate verify signature", sig_bytes);
signature.value = sig_bytes;
return signature.encode(conn, s);
} catch (java.security.NoSuchAlgorithmException e) {
throw new InternalError(e.toString());
} catch (java.security.SignatureException e) {
throw new InternalError(e.toString());
} catch (java.security.InvalidKeyException e) {
throw new InternalError(e.toString());
}
}
Example 49
Project: ISAvalidator-ISAconverter-BIImanager-master File: SRAAuthURLGenerator.java View source code |
public byte[] calculateRFC2104HMAC(String data, String key) throws java.security.SignatureException { try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac return rawHmac; } catch (Exception e) { throw new SignatureException(" Failed to generate HMAC : " + e.getMessage()); } }
Example 50
Project: miso-lims-master File: ShaPasswordCodecService.java View source code |
/** * Encrypt a plaintext String using a hmac_sha1 salt * * @param key of type String * @param plaintext of type String * @return String the encrypted String of the given plaintext String * @throws java.security.SignatureException when the HMAC is unable to be generated */ public synchronized String encryptHMACSHA1(String key, String plaintext) throws SignatureException { String result; try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1"); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(plaintext.getBytes()); // base64-encode the hmac //result = new BASE64Encoder().encode(rawHmac); result = new Base64().encodeToString(rawHmac); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; }
Example 51
Project: android-libcore64-master File: MySignature1.java View source code |
protected void engineUpdate(byte[] b, int off, int len) throws SignatureException {
if (b == null)
throw new NullPointerException();
if (off < 0 || off > b.length || off > len) {
throw new IllegalArgumentException("incorrect parameter off");
}
if (len < 0 || len > b.length) {
throw new IllegalArgumentException("incorrect parameter len");
}
runEngineUpdate2 = true;
}
Example 52
Project: android-rcs-ims-stack-master File: SimpleContentSignerBuilder.java View source code |
public ContentSigner build(PrivateKey privateKey) throws OperatorCreationException {
try {
final Signature sig = Signature.getInstance(mAlgorithm);
sig.initSign(privateKey);
return new ContentSigner() {
private SignatureOutputStream stream = new SignatureOutputStream(sig);
public AlgorithmIdentifier getAlgorithmIdentifier() {
return sigAlgId;
}
public OutputStream getOutputStream() {
return stream;
}
public byte[] getSignature() {
try {
return stream.getSignature();
} catch (SignatureException e) {
throw new RuntimeOperatorException("exception obtaining signature: " + e.getMessage(), e);
}
}
};
} catch (GeneralSecurityException e) {
throw new OperatorCreationException("cannot create signer: " + e.getMessage(), e);
}
}
Example 53
Project: AndroidClient-master File: ImportKeyPairListener.java View source code |
public void run() throws CertificateException, SignatureException, PGPException, IOException, NoSuchProviderException {
super.run();
try {
mImporter.load();
mKeyRing = mImporter.createKeyPairRing();
} finally {
try {
mImporter.close();
} catch (Exception e) {
}
}
// if we are here, it means personal key is likely valid
// proceed to send the public key to the server for approval
// listen for connection events
setupConnectedReceiver();
// request connection status
MessageCenterService.requestConnectionStatus(getContext());
// CONNECTED listener will do the rest
}
Example 54
Project: android_platform_libcore-master File: MySignature1.java View source code |
protected void engineUpdate(byte[] b, int off, int len) throws SignatureException {
if (b == null)
throw new NullPointerException();
if (off < 0 || off > b.length || off > len) {
throw new IllegalArgumentException("incorrect parameter off");
}
if (len < 0 || len > b.length) {
throw new IllegalArgumentException("incorrect parameter len");
}
runEngineUpdate2 = true;
}
Example 55
Project: ARTPart-master File: MySignature1.java View source code |
protected void engineUpdate(byte[] b, int off, int len) throws SignatureException {
if (b == null)
throw new NullPointerException();
if (off < 0 || off > b.length || off > len) {
throw new IllegalArgumentException("incorrect parameter off");
}
if (len < 0 || len > b.length) {
throw new IllegalArgumentException("incorrect parameter len");
}
runEngineUpdate2 = true;
}
Example 56
Project: browsermob-proxy-master File: DSASignature.java View source code |
/** * Converts the signature generated by DSA signature routines to * the one expected inside an RRSIG/SIG record. */ public static byte[] toDNS(DSAParams params, byte[] sig) throws SignatureException { int rLength, sLength; int rOffset, sOffset; if ((sig[0] != ASN1_SEQ) || (sig[2] != ASN1_INT)) throw new SignatureException("Expected SEQ, INT"); rLength = sig[3]; rOffset = 4; if (sig[rOffset] == 0) { rLength--; rOffset++; } if (sig[rOffset + rLength] != ASN1_INT) throw new SignatureException("Expected INT"); sLength = sig[rOffset + rLength + 1]; sOffset = rOffset + rLength + 2; if (sig[sOffset] == 0) { sLength--; sOffset++; } if ((rLength > 20) || (sLength > 20)) throw new SignatureException("DSA R/S too long"); byte[] newSig = new byte[41]; Arrays.fill(newSig, (byte) 0); newSig[0] = (byte) ((params.getP().bitLength() - 512) / 64); System.arraycopy(sig, rOffset, newSig, 1 + (20 - rLength), rLength); System.arraycopy(sig, sOffset, newSig, 21 + (20 - sLength), sLength); return newSig; }
Example 57
Project: camel-cookbook-examples-master File: SignaturesSpringTest.java View source code |
@Test public void testMessageModificationAfterSigning() throws InterruptedException { MockEndpoint mockSigned = getMockEndpoint("mock:signed"); mockSigned.whenAnyExchangeReceived(new Processor() { @Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); in.setBody(in.getBody(String.class) + "modified"); } }); MockEndpoint mockVerified = getMockEndpoint("mock:verified"); mockVerified.setExpectedMessageCount(0); try { template.sendBody("direct:sign", "foo"); fail(); } catch (CamelExecutionException cex) { assertTrue(ExceptionUtils.getRootCause(cex) instanceof SignatureException); assertEquals("SignatureException: Cannot verify signature of exchange", ExceptionUtils.getRootCauseMessage(cex)); } assertMockEndpointsSatisfied(); }
Example 58
Project: drools-master File: KeyStoreHelperTest.java View source code |
@Test
public void testSignDataWithPrivateKey() throws UnsupportedEncodingException, UnrecoverableKeyException, InvalidKeyException, KeyStoreException, NoSuchAlgorithmException, SignatureException {
// The server signs the data with the private key
// Set properties to simulate the server
URL serverKeyStoreURL = getClass().getResource("droolsServer.keystore");
System.setProperty(KeyStoreHelper.PROP_SIGN, "true");
System.setProperty(KeyStoreHelper.PROP_PVT_KS_URL, serverKeyStoreURL.toExternalForm());
System.setProperty(KeyStoreHelper.PROP_PVT_KS_PWD, "serverpwd");
System.setProperty(KeyStoreHelper.PROP_PVT_ALIAS, "droolsKey");
System.setProperty(KeyStoreHelper.PROP_PVT_PWD, "keypwd");
KeyStoreHelper serverHelper = new KeyStoreHelper();
// get some data to sign
byte[] data = "Hello World".getBytes("UTF8");
// sign the data
byte[] signature = serverHelper.signDataWithPrivateKey(data);
// now, initialise the client helper
// Set properties to simulate the client
URL clientKeyStoreURL = getClass().getResource("droolsClient.keystore");
System.setProperty(KeyStoreHelper.PROP_SIGN, "true");
System.setProperty(KeyStoreHelper.PROP_PUB_KS_URL, clientKeyStoreURL.toExternalForm());
System.setProperty(KeyStoreHelper.PROP_PUB_KS_PWD, "clientpwd");
// client needs no password to access the certificate and public key
KeyStoreHelper clientHelper = new KeyStoreHelper();
// check the signature against the data
assertTrue(clientHelper.checkDataWithPublicKey("droolsKey", data, signature));
// check some fake data
assertFalse(clientHelper.checkDataWithPublicKey("droolsKey", "fake".getBytes("UTF8"), signature));
}
Example 59
Project: dss-master File: CertificateServiceTest.java View source code |
@Test(expected = SignatureException.class)
public void isChildCertificateNotSelfSigned() throws Exception {
DSSPrivateKeyEntry entryChain = service.generateCertificateChain(SignatureAlgorithm.RSA_SHA256);
// Child certificate is signed with the issuer's private key
CertificateToken token = entryChain.getCertificate();
X509Certificate certificate = token.getCertificate();
certificate.verify(token.getPublicKey());
}
Example 60
Project: flashback-master File: HandshakeWithClient.java View source code |
@Override
public Future execute(ChannelMediator channelMediator, InetSocketAddress remoteAddress) {
//dynamically create SSLEngine based on CN and SANs
LOG.debug("Starting client to proxy connection handshaking");
try {
//TODO: if connect request only contains ip address, we need get either CA
//TODO: or SANS from server response
KeyStore keyStore = _certificateKeyStoreFactory.create(remoteAddress.getHostName(), new ArrayList<>());
SSLContext sslContext = SSLContextGenerator.createClientContext(keyStore, _certificateAuthority.getPassPhrase());
return channelMediator.handshakeWithClient(sslContext.createSSLEngine());
} catch (NoSuchAlgorithmExceptionKeyStoreException | IOException | CertificateException | OperatorCreationException | NoSuchProviderException | InvalidKeyException | SignatureException | KeyManagementException | UnrecoverableKeyException | e) {
throw new RuntimeException("Failed to create server identity certificate", e);
}
}
Example 61
Project: gitapp-master File: JsonTokenHelper.java View source code |
@Override public void check(JsonObject payload) throws SignatureException { if (!payload.has(JsonToken.AUDIENCE)) { throw new SignatureException("No audience in payload."); } String audience = payload.get(JsonToken.AUDIENCE).getAsString(); if (!expectedAudience.equals(audience)) { throw new SignatureException(String.format("Invalid audience: %s. Should be: %s", audience, expectedAudience)); } }
Example 62
Project: Hive2Hive-master File: H2HSignatureFactory.java View source code |
@Override
public SignatureCodec sign(PrivateKey privateKey, ByteBuffer[] byteBuffers) throws InvalidKeyException, SignatureException, IOException {
Signature signature = signatureInstance();
signature.initSign(privateKey);
int len = byteBuffers.length;
for (int i = 0; i < len; i++) {
ByteBuffer buffer = byteBuffers[i];
signature.update(buffer);
}
byte[] signatureData = signature.sign();
SignatureCodec decodedSignature = new H2HSignatureCodec(signatureData);
return decodedSignature;
}
Example 63
Project: kerst2012-master File: WampCraConnection.java View source code |
public void onResult(Object challenge) {
String sig = null;
try {
sig = authSignature((String) challenge, authSecret);
} catch (SignatureException e) {
Log.e("WampCraConnection:authenicate", e.toString());
}
call(Wamp.URI_WAMP_PROCEDURE + "auth", WampCraPermissions.class, new CallHandler() {
public void onResult(Object result) {
authHandler.onAuthSuccess(result);
}
public void onError(String errorUri, String errorDesc) {
authHandler.onAuthError(errorUri, errorDesc);
}
}, sig);
}
Example 64
Project: learning-bittorrent-master File: SecureMessageVerifier.java View source code |
/** Does the verification. */
private void verifyMessage(SecureMessage message, SecureMessageCallback callback) {
if (pubKey == null) {
LOG.warn("Cannot verify message without a public key.");
message.setSecureStatus(SecureMessage.INSECURE);
callback.handleSecureMessage(message, false);
return;
}
byte[] signature = message.getSecureSignature();
if (signature == null) {
LOG.warn("Cannot verify message without a signature.");
message.setSecureStatus(SecureMessage.INSECURE);
callback.handleSecureMessage(message, false);
return;
}
try {
Signature verifier = Signature.getInstance("SHA1withDSA");
verifier.initVerify(pubKey);
message.updateSignatureWithSecuredBytes(verifier);
if (verifier.verify(signature)) {
message.setSecureStatus(SecureMessage.SECURE);
callback.handleSecureMessage(message, true);
return;
}
// fallthrough on not secure & failures to set failed.
} catch (NoSuchAlgorithmException nsax) {
LOG.error("No alg.", nsax);
} catch (InvalidKeyException ikx) {
LOG.error("Invalid key", ikx);
} catch (SignatureException sx) {
LOG.error("Bad sig", sx);
} catch (ClassCastException ccx) {
LOG.error("bad cast", ccx);
}
message.setSecureStatus(SecureMessage.FAILED);
callback.handleSecureMessage(message, false);
}
Example 65
Project: limewire5-ruby-master File: Verifier.java View source code |
/** Does the verification. */
public void run() {
SecureMessage message = getSecureMessage();
SecureMessageCallback callback = getSecureMessageCallback();
PublicKey pubKey = getPublicKey();
String algorithm = getAlgorithm();
if (pubKey == null) {
LOG.warn("Cannot verify message without a public key.");
message.setSecureStatus(Status.INSECURE);
callback.handleSecureMessage(message, false);
return;
}
byte[] signature = message.getSecureSignature();
if (signature == null) {
LOG.warn("Cannot verify message without a signature.");
message.setSecureStatus(Status.INSECURE);
callback.handleSecureMessage(message, false);
return;
}
try {
Signature verifier = Signature.getInstance(algorithm);
verifier.initVerify(pubKey);
message.updateSignatureWithSecuredBytes(verifier);
if (verifier.verify(signature)) {
message.setSecureStatus(Status.SECURE);
callback.handleSecureMessage(message, true);
return;
}
// fallthrough on not secure & failures to set failed.
} catch (NoSuchAlgorithmException nsax) {
LOG.error("No alg.", nsax);
} catch (InvalidKeyException ikx) {
LOG.error("Invalid key", ikx);
} catch (SignatureException sx) {
LOG.error("Bad sig", sx);
} catch (ClassCastException ccx) {
LOG.error("bad cast", ccx);
}
message.setSecureStatus(Status.FAILED);
callback.handleSecureMessage(message, false);
}
Example 66
Project: nextprot-api-master File: JWTCodecImpl.java View source code |
@Override
public Map<String, Object> decodeJWT(String token) {
JWTVerifier jwtVerifier = new JWTVerifier(clientSecret, clientId);
Map<String, Object> verify;
try {
verify = jwtVerifier.verify(token);
String payload = (String) verify.get("payload");
Map<String, Object> map = new ObjectMapper().readValue(payload, Map.class);
return map;
} catch (InvalidKeyException e) {
throw new NextprotSecurityException(e);
} catch (NoSuchAlgorithmException e) {
throw new NextprotSecurityException(e);
} catch (IllegalStateException e) {
throw new NextprotSecurityException(e);
} catch (SignatureException e) {
throw new NextprotSecurityException(e);
} catch (IOException e) {
throw new NextprotSecurityException(e);
}
}
Example 67
Project: oxAuth-master File: HMACSigner.java View source code |
@Override public String generateSignature(String signingInput) throws SignatureException { if (getSignatureAlgorithm() == null) { throw new SignatureException("The signature algorithm is null"); } if (sharedSecret == null) { throw new SignatureException("The shared secret is null"); } if (signingInput == null) { throw new SignatureException("The signing input is null"); } String algorithm; switch(getSignatureAlgorithm()) { case HS256: algorithm = "HMACSHA256"; break; case HS384: algorithm = "HMACSHA384"; break; case HS512: algorithm = "HMACSHA512"; break; default: throw new SignatureException("Unsupported signature algorithm"); } try { SecretKey secretKey = new SecretKeySpec(sharedSecret.getBytes(Util.UTF8_STRING_ENCODING), algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(secretKey); byte[] sig = mac.doFinal(signingInput.getBytes(Util.UTF8_STRING_ENCODING)); return Base64Util.base64urlencode(sig); } catch (NoSuchAlgorithmException e) { throw new SignatureException(e); } catch (InvalidKeyException e) { throw new SignatureException(e); } catch (UnsupportedEncodingException e) { throw new SignatureException(e); } catch (Exception e) { throw new SignatureException(e); } }
Example 68
Project: ratpack-jwtauth-master File: JWTClaimsHandlerDecorator.java View source code |
@Override
public Handler decorate(Registry serverRegistry, Handler rest) throws Exception {
return context -> {
String tokens = context.getRequest().getHeaders().get(this.header);
if (tokens == null) {
context.insert(rest);
return;
}
try {
Map<String, Object> verify = jwtVerifier.verify(tokens);
JWTClaims claims = new JWTClaims(verify);
context.insert(Registry.single(claims), rest);
} catch (NoSuchAlgorithmExceptionInvalidKeyException | SignatureException | JWTVerifyException | e) {
LOGGER.error("Failed to verify token", e);
context.getResponse().status(500).send();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
Example 69
Project: sodacloud-master File: WampCraConnection.java View source code |
public void onResult(Object challenge) {
String sig = null;
try {
sig = authSignature((String) challenge, authSecret);
} catch (SignatureException e) {
Log.e("WampCraConnection:authenicate", e.toString());
}
call(Wamp.URI_WAMP_PROCEDURE + "auth", WampCraPermissions.class, new CallHandler() {
public void onResult(Object result) {
authHandler.onAuthSuccess(result);
}
public void onError(String errorUri, String errorDesc) {
authHandler.onAuthError(errorUri, errorDesc);
}
}, sig);
}
Example 70
Project: spring-crypto-utils-master File: VerifierImpl.java View source code |
/** * Verifies the authenticity of a message using a digital signature. * * @param message the original message to verify * @param signature the digital signature * @return true if the original message is verified by the digital signature */ public boolean verify(byte[] message, byte[] signature) { try { // this way signatureInstance should be thread safe final Signature signatureInstance = ((provider == null) || (provider.length() == 0)) ? Signature.getInstance(algorithm) : Signature.getInstance(algorithm, provider); signatureInstance.initVerify(publicKey); signatureInstance.update(message); return signatureInstance.verify(signature); } catch (java.security.SignatureException e) { return false; } catch (Exception e) { throw new SignatureException("error verifying signature", e); } }
Example 71
Project: TomP2P-master File: TestRelayUtils.java View source code |
@Test
public void testEncodeDecodeRelayedMessage() throws InvalidKeyException, SignatureException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {
Message message = UtilsNAT.createRandomMessage();
List<PeerSocketAddress> relays = new ArrayList<PeerSocketAddress>();
relays.add(PeerSocketAddress.create(InetAddress.getLocalHost(), 8000, 9000, 9001));
relays.add(PeerSocketAddress.create(InetAddress.getLocalHost(), 8001, 9001, 9002));
relays.add(PeerSocketAddress.create(InetAddress.getLocalHost(), 8002, 9002, 9003));
PeerAddress sender = UtilsNAT.createRandomAddress().withRelays(relays);
;
PeerAddress receiver = UtilsNAT.createRandomAddress();
message.sender(sender);
message.senderSocket(sender.createTCPSocket(receiver));
message.recipient(receiver);
message.recipientSocket(receiver.createTCPSocket(sender));
Buffer encoded = RelayUtils.encodeMessage(message, signature);
Message decoded = RelayUtils.decodeMessage(encoded.buffer(), message.recipientSocket(), message.senderSocket(), signature);
Assert.assertEquals(message.sender().relays(), decoded.sender().relays());
}
Example 72
Project: uaa-master File: SocketUtils.java View source code |
public static X509Certificate getSelfCertificate(X500Name x500Name, Date issueDate, long validForSeconds, KeyPair keyPair, String signatureAlgorithm) throws CertificateException, InvalidKeyException, SignatureException, NoSuchAlgorithmException, NoSuchProviderException {
try {
Date expirationDate = new Date();
expirationDate.setTime(issueDate.getTime() + validForSeconds * 1000L);
X509CertInfo certInfo = new X509CertInfo();
certInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber((new Random()).nextInt() & Integer.MAX_VALUE));
certInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(AlgorithmId.get(signatureAlgorithm)));
certInfo.set(X509CertInfo.SUBJECT, x500Name);
certInfo.set(X509CertInfo.ISSUER, x500Name);
certInfo.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic()));
certInfo.set(X509CertInfo.VALIDITY, new CertificateValidity(issueDate, expirationDate));
X509CertImpl selfSignedCert = new X509CertImpl(certInfo);
selfSignedCert.sign(keyPair.getPrivate(), signatureAlgorithm);
return selfSignedCert;
} catch (IOException ioe) {
throw new CertificateEncodingException("Error during creation of self-signed Certificate: " + ioe.getMessage(), ioe);
}
}
Example 73
Project: uma-master File: HMACSigner.java View source code |
@Override public String generateSignature(String signingInput) throws SignatureException { if (getSignatureAlgorithm() == null) { throw new SignatureException("The signature algorithm is null"); } if (sharedSecret == null) { throw new SignatureException("The shared secret is null"); } if (signingInput == null) { throw new SignatureException("The signing input is null"); } String algorithm; switch(getSignatureAlgorithm()) { case HS256: algorithm = "HMACSHA256"; break; case HS384: algorithm = "HMACSHA384"; break; case HS512: algorithm = "HMACSHA512"; break; default: throw new SignatureException("Unsupported signature algorithm"); } try { SecretKey secretKey = new SecretKeySpec(sharedSecret.getBytes(Util.UTF8_STRING_ENCODING), algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(secretKey); byte[] sig = mac.doFinal(signingInput.getBytes(Util.UTF8_STRING_ENCODING)); return Base64Util.base64urlencode(sig); } catch (NoSuchAlgorithmException e) { throw new SignatureException(e); } catch (InvalidKeyException e) { throw new SignatureException(e); } catch (UnsupportedEncodingException e) { throw new SignatureException(e); } catch (Exception e) { throw new SignatureException(e); } }
Example 74
Project: voms-api-java-master File: TestNoExtensionValidation.java View source code |
@Test
public void testNoExtensionValidation() throws InvalidKeyException, CertificateParsingException, SignatureException, NoSuchAlgorithmException {
ProxyCertificateOptions options = new ProxyCertificateOptions(cred.getCertificateChain());
options.setType(ProxyType.LEGACY);
ProxyCertificate proxy = ProxyGenerator.generate(options, cred.getKey());
VOMSACValidator validator = Utils.getVOMSValidator();
List<VOMSAttribute> attrs = validator.validate(proxy.getCertificateChain());
Assert.assertNotNull(attrs);
Assert.assertTrue(attrs.isEmpty());
}
Example 75
Project: Wilma-master File: DSASignature.java View source code |
/** * Converts the signature generated by DSA signature routines to * the one expected inside an RRSIG/SIG record. */ public static byte[] toDNS(DSAParams params, byte[] sig) throws SignatureException { int rLength, sLength; int rOffset, sOffset; if ((sig[0] != ASN1_SEQ) || (sig[2] != ASN1_INT)) throw new SignatureException("Expected SEQ, INT"); rLength = sig[3]; rOffset = 4; if (sig[rOffset] == 0) { rLength--; rOffset++; } if (sig[rOffset + rLength] != ASN1_INT) throw new SignatureException("Expected INT"); sLength = sig[rOffset + rLength + 1]; sOffset = rOffset + rLength + 2; if (sig[sOffset] == 0) { sLength--; sOffset++; } if ((rLength > 20) || (sLength > 20)) throw new SignatureException("DSA R/S too long"); byte[] newSig = new byte[41]; Arrays.fill(newSig, (byte) 0); newSig[0] = (byte) ((params.getP().bitLength() - 512) / 64); System.arraycopy(sig, rOffset, newSig, 1 + (20 - rLength), rLength); System.arraycopy(sig, sOffset, newSig, 21 + (20 - sLength), sLength); return newSig; }
Example 76
Project: cloudpier-adapters-master File: BeansDescribeEnvironments.java View source code |
/** * Computes RFC 2104-compliant HMAC signature. * * @param data The data to be signed. * @return The base64-encoded RFC 2104-compliant HMAC signature. * @throws java.security.SignatureException * when signature generation fails */ protected String generateSignature(String data) throws java.security.SignatureException { String result; try { // get a hash key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(secretAccessKey.getBytes(), HASH_ALGORITHM); // get a hasher instance and initialize with the signing key Mac mac = Mac.getInstance(HASH_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac // result = Encoding.EncodeBase64(rawHmac); result = new BASE64Encoder().encode(rawHmac); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; }
Example 77
Project: droidtowers-master File: RavenUtils.java View source code |
/** * Computes RFC 2104-compliant HMAC signature. * Based off of the sample here. http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AuthJavaSampleHMACSignature.html * * @param data The data to be signed. * @param key The signing key. * @return The hex-encoded RFC 2104-compliant HMAC signature. * @throws java.security.SignatureException * when signature generation fails */ public static String calculateHMAC(String data, String key) throws java.security.SignatureException { String result; try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); result = hexEncode(rawHmac); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; }
Example 78
Project: HadoopEKG-master File: PriorityAuthorization.java View source code |
/** * Adapted from AWS Query Authentication cookbook: * Computes RFC 2104-compliant HMAC signature. * * @param data * The data to be signed. * @param key * The signing key. * @return * The base64-encoded RFC 2104-compliant HMAC signature. * @throws * java.security.SignatureException when signature generation fails */ public static String hmac(String data, String key) throws java.security.SignatureException { String result; try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac result = new String(Base64.encodeBase64(rawHmac)); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e, e); } return result; }
Example 79
Project: runner-master File: Encryption.java View source code |
/** * Computes RFC 2104-compliant HMAC signature. * * @param data The data to be signed. * @param key The signing key. * @return The Base64-encoded RFC 2104-compliant HMAC signature. * @throws java.security.SignatureException when signature generation fails */ public static String calculateRFC2104HMAC(final String data, final String key) throws java.security.SignatureException { try { // get an hmac_sha1 key from the raw key bytes final SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); // get an hmac_sha1 Mac instance and initialize with the signing key final Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes final byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac return android.util.Base64.encodeToString(rawHmac, Base64.NO_WRAP); } catch (final Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } }
Example 80
Project: runnerup-master File: Encryption.java View source code |
/** * Computes RFC 2104-compliant HMAC signature. * * @param data The data to be signed. * @param key The signing key. * @return The Base64-encoded RFC 2104-compliant HMAC signature. * @throws java.security.SignatureException when signature generation fails */ public static String calculateRFC2104HMAC(final String data, final String key) throws java.security.SignatureException { try { // get an hmac_sha1 key from the raw key bytes final SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); // get an hmac_sha1 Mac instance and initialize with the signing key final Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes final byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac return android.util.Base64.encodeToString(rawHmac, Base64.NO_WRAP); } catch (final Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } }
Example 81
Project: ddf-master File: SimpleSign.java View source code |
public void signSamlObject(SignableSAMLObject samlObject) throws SignatureException { X509Certificate[] certificates = getSignatureCertificates(); String sigAlgo = getSignatureAlgorithm(certificates[0]); PrivateKey privateKey = getSignaturePrivateKey(); // Create the signature Signature signature = OpenSAMLUtil.buildSignature(); if (signature == null) { throw new SignatureException("Unable to build signature."); } signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); signature.setSignatureAlgorithm(sigAlgo); BasicX509Credential signingCredential = new BasicX509Credential(certificates[0]); signingCredential.setPrivateKey(privateKey); signature.setSigningCredential(signingCredential); X509KeyInfoGeneratorFactory x509KeyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory(); x509KeyInfoGeneratorFactory.setEmitEntityCertificate(true); try { KeyInfo keyInfo = x509KeyInfoGeneratorFactory.newInstance().generate(signingCredential); signature.setKeyInfo(keyInfo); } catch (org.opensaml.security.SecurityException e) { throw new SignatureException("Error generating KeyInfo from signing credential", e); } if (samlObject instanceof Response) { List<Assertion> assertions = ((Response) samlObject).getAssertions(); for (Assertion assertion : assertions) { assertion.getSignature().setSigningCredential(signingCredential); } } samlObject.setSignature(signature); SAMLObjectContentReference contentRef = (SAMLObjectContentReference) signature.getContentReferences().get(0); contentRef.setDigestAlgorithm(SignatureConstants.ALGO_ID_DIGEST_SHA1); samlObject.releaseDOM(); samlObject.releaseChildrenDOM(true); }
Example 82
Project: android-15-master File: MySignature1.java View source code |
protected void engineUpdate(byte[] b, int off, int len) throws SignatureException {
if (b == null)
throw new NullPointerException();
if (off < 0 || off > b.length || off > len) {
throw new IllegalArgumentException("incorrect parameter off");
}
if (len < 0 || len > b.length) {
throw new IllegalArgumentException("incorrect parameter len");
}
runEngineUpdate2 = true;
}
Example 83
Project: android-sdk-sources-for-api-level-23-master File: MySignature1.java View source code |
protected void engineUpdate(byte[] b, int off, int len) throws SignatureException {
if (b == null)
throw new NullPointerException();
if (off < 0 || off > b.length || off > len) {
throw new IllegalArgumentException("incorrect parameter off");
}
if (len < 0 || len > b.length) {
throw new IllegalArgumentException("incorrect parameter len");
}
runEngineUpdate2 = true;
}
Example 84
Project: AndroidBillingLibrary-master File: DefaultSignatureValidator.java View source code |
protected boolean validate(PublicKey publicKey, String signedData, String signature) {
Signature sig;
try {
sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(publicKey);
sig.update(signedData.getBytes());
if (!sig.verify(Base64.decode(signature))) {
Log.e(BillingController.LOG_TAG, "Signature verification failed.");
return false;
}
return true;
} catch (NoSuchAlgorithmException e) {
Log.e(BillingController.LOG_TAG, "NoSuchAlgorithmException");
} catch (InvalidKeyException e) {
Log.e(BillingController.LOG_TAG, "Invalid key specification");
} catch (SignatureException e) {
Log.e(BillingController.LOG_TAG, "Signature exception");
} catch (Base64DecoderException e) {
Log.e(BillingController.LOG_TAG, "Base64 decoding failed");
}
return false;
}
Example 85
Project: android_libcore-master File: MySignature1.java View source code |
protected void engineUpdate(byte[] b, int off, int len) throws SignatureException {
if (b == null)
throw new NullPointerException();
if (off < 0 || off > b.length || off > len) {
throw new IllegalArgumentException("incorrect parameter off");
}
if (len < 0 || len > b.length) {
throw new IllegalArgumentException("incorrect parameter len");
}
runEngineUpdate2 = true;
}
Example 86
Project: aws-sdk-for-android-master File: S3QueryStringSigner.java View source code |
public void sign(Request<T> request) throws SignatureException {
String expirationInSeconds = Long.toString(expiration.getTime() / 1000L);
String canonicalString = RestUtils.makeS3CanonicalString(httpVerb, resourcePath, request, expirationInSeconds);
String secretKey;
String accessKeyId;
synchronized (credentials) {
secretKey = credentials.getAWSSecretKey();
accessKeyId = credentials.getAWSAccessKeyId();
}
String signature = super.sign(canonicalString, secretKey, SigningAlgorithm.HmacSHA1);
request.addParameter("AWSAccessKeyId", accessKeyId);
request.addParameter("Expires", expirationInSeconds);
request.addParameter("Signature", signature);
}
Example 87
Project: Beer-Converter-master File: DefaultSignatureValidator.java View source code |
protected boolean validate(PublicKey publicKey, String signedData, String signature) {
Signature sig;
try {
sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(publicKey);
sig.update(signedData.getBytes());
if (!sig.verify(Base64.decode(signature))) {
Log.e(BillingController.LOG_TAG, "Signature verification failed.");
return false;
}
return true;
} catch (NoSuchAlgorithmException e) {
Log.e(BillingController.LOG_TAG, "NoSuchAlgorithmException");
} catch (InvalidKeyException e) {
Log.e(BillingController.LOG_TAG, "Invalid key specification");
} catch (SignatureException e) {
Log.e(BillingController.LOG_TAG, "Signature exception");
} catch (Base64DecoderException e) {
Log.e(BillingController.LOG_TAG, "Base64 decoding failed");
}
return false;
}
Example 88
Project: billy-master File: CertificationManager.java View source code |
public byte[] getHashBinary(String source) throws InvalidHashException, InvalidKeyException {
byte[] hash;
try {
this.signature.initSign(this.privateKey);
this.signature.update(source.getBytes());
hash = this.signature.sign();
if (this.autoVerifyHash) {
if (!this.verifyHashBinary(source, hash)) {
throw new InvalidHashException();
}
}
} catch (SignatureException e) {
throw new InvalidHashException("Signature exception - should not happen");
}
return hash;
}
Example 89
Project: camel-master File: VerifyingProcessor.java View source code |
public void process(Exchange exchange) throws Exception {
Signature signer = createSignatureService();
Certificate cert = getCertificate(exchange);
if (cert == null) {
PublicKey pk = getPublicKeyOrCertificateFromHeader(exchange, PublicKey.class, config.getPublicKey());
if (pk == null) {
throw new IllegalStateException(String.format("Cannot verify signature as no Public Key or Certificate has been supplied." + " Either supply one in the route definition or via the message header '%s'", DigitalSignatureConstants.SIGNATURE_PUBLIC_KEY_OR_CERT));
}
signer.initVerify(pk);
} else {
signer.initVerify(cert);
}
calculateSignature(exchange, signer);
byte[] signature = getSignatureFromExchange(exchange);
if (!signer.verify(signature)) {
throw new SignatureException("Cannot verify signature of exchange");
}
clearMessageHeaders(exchange.getIn());
}
Example 90
Project: CameraV-master File: SignatureService.java View source code |
@SuppressWarnings("deprecation") public boolean isVerified(final ILogPack data) throws IOException { try { byte[] signedData = (byte[]) data.remove(Signatures.Keys.SIGNATURE); ByteArrayInputStream sd = new ByteArrayInputStream(signedData); InputStream is = PGPUtil.getDecoderStream(sd); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PGPObjectFactory objFactory = new PGPObjectFactory(is); PGPCompressedData cd = (PGPCompressedData) objFactory.nextObject(); objFactory = new PGPObjectFactory(cd.getDataStream()); PGPOnePassSignatureList sigList_o = (PGPOnePassSignatureList) objFactory.nextObject(); PGPOnePassSignature sig = sigList_o.get(0); PGPLiteralData ld = (PGPLiteralData) objFactory.nextObject(); InputStream literalIn = ld.getInputStream(); sig.initVerify(publicKey, new BouncyCastleProvider()); int read; while ((read = literalIn.read()) > 0) { sig.update((byte) read); baos.write(read); } PGPSignatureList sigList = (PGPSignatureList) objFactory.nextObject(); if (sig.verify(sigList.get(0)) && data.toString().equals(new String(baos.toByteArray()))) { baos.close(); return true; } else { baos.close(); return false; } } catch (PGPException e) { Log.d(LOG, "SignatureException: " + e.getMessage(), e); return false; } catch (SignatureException e) { Log.d(LOG, "SignatureException: " + e.getMessage(), e); return false; } }
Example 91
Project: cloudstack-master File: GetServiceProviderMetaDataCmdTest.java View source code |
@Test
public void testAuthenticate() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, CertificateParsingException, CertificateEncodingException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException, UnknownHostException {
GetServiceProviderMetaDataCmd cmd = new GetServiceProviderMetaDataCmd();
Field apiServerField = GetServiceProviderMetaDataCmd.class.getDeclaredField("_apiServer");
apiServerField.setAccessible(true);
apiServerField.set(cmd, apiServer);
Field managerField = GetServiceProviderMetaDataCmd.class.getDeclaredField("_samlAuthManager");
managerField.setAccessible(true);
managerField.set(cmd, samlAuthManager);
String spId = "someSPID";
String url = "someUrl";
KeyPair kp = SAMLUtils.generateRandomKeyPair();
X509Certificate cert = SAMLUtils.generateRandomX509Certificate(kp);
SAMLProviderMetadata providerMetadata = new SAMLProviderMetadata();
providerMetadata.setEntityId("random");
providerMetadata.setSigningCertificate(cert);
providerMetadata.setEncryptionCertificate(cert);
providerMetadata.setKeyPair(kp);
providerMetadata.setSsoUrl("http://test.local");
providerMetadata.setSloUrl("http://test.local");
Mockito.when(samlAuthManager.getSPMetadata()).thenReturn(providerMetadata);
String result = cmd.authenticate("command", null, session, InetAddress.getByName("127.0.0.1"), HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
Assert.assertTrue(result.contains("md:EntityDescriptor"));
}
Example 92
Project: dcache-master File: ClientGsiEngine.java View source code |
@Override
public void call(ByteBuffer buffer) throws SSLException {
// read csr
ByteSource chunk = ByteSource.wrap(buffer.array()).slice(buffer.arrayOffset(), buffer.position());
ByteSource source = (data == null) ? chunk : ByteSource.concat(data, chunk);
try {
PKCS10CertificationRequest csr = new PKCS10CertificationRequest(source.read());
// generate proxy
ProxyRequestOptions options = new ProxyRequestOptions(credential.getCertificateChain(), csr);
options.setLimited(isDelegationLimited);
X509Certificate[] chain = ProxyGenerator.generate(options, credential.getKey());
// send to server
send(ByteBuffer.wrap(chain[0].getEncoded()));
} catch (EOFException f) {
try {
ByteSource copy = ByteSource.wrap(chunk.read());
data = (data == null) ? copy : ByteSource.concat(data, copy);
receive(this);
} catch (IOException e) {
f.addSuppressed(e);
}
} catch (CertificateParsingExceptionNoSuchAlgorithmException | NoSuchProviderException | SignatureException | CertificateEncodingException | InvalidKeyException | IOException | e) {
throw new SSLException("GSI delegation failed: " + e.toString(), e);
}
}
Example 93
Project: directory-studio-master File: CertificateUtils.java View source code |
public static X509Certificate createCertificate(String issuerDN, String subjectDN, Date startDate, Date expiryDate, KeyPair keypair) throws CertificateEncodingException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis());
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
X500Principal issuerName = new X500Principal(issuerDN);
X500Principal subjectName = new X500Principal(subjectDN);
certGen.setSerialNumber(serialNumber);
certGen.setIssuerDN(issuerName);
certGen.setNotBefore(startDate);
certGen.setNotAfter(expiryDate);
certGen.setSubjectDN(subjectName);
certGen.setPublicKey(keypair.getPublic());
certGen.setSignatureAlgorithm("SHA1WithRSA");
X509Certificate cert = certGen.generate(keypair.getPrivate(), "BC");
return cert;
}
Example 94
Project: grendel-master File: KeySignature.java View source code |
/**
* Verify this signature for a self-signed {@link MasterKey}.
*
* @param key a self-signed master key
* @return {@code true} if the signature is valid, {@code false} otherwise
*/
public boolean verifyCertification(MasterKey key) {
try {
signature.initVerify(key.getPublicKey(), "BC");
return signature.verifyCertification(key.getUserID(), key.getPublicKey());
} catch (PGPException e) {
return false;
} catch (SignatureException e) {
return false;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Example 95
Project: identity-toolkit-java-client-master File: JsonTokenHelper.java View source code |
@Override public void check(JsonObject payload) throws SignatureException { if (!payload.has(JsonToken.AUDIENCE)) { throw new SignatureException("No audience in payload."); } final String audienceInIdToken = payload.get(JsonToken.AUDIENCE).getAsString(); Optional<String> matchedAud = Iterables.tryFind(expectedAudiences, new Predicate<String>() { public boolean apply(String aud) { return audienceInIdToken.equals(aud); } }); if (!matchedAud.isPresent()) { throw new SignatureException(String.format("Gitkit token audience(%s) doesn't match projectId or clientId in server configuration", audienceInIdToken)); } }
Example 96
Project: incubator-brooklyn-master File: JmxmpClient.java View source code |
/** tries to connect to the given JMX url over tls,
* optionally using the given keystore (if null using a randomly generated key)
* and optionally using the given truststore (if null trusting all) */
public void connectTls(String urlString, KeyStore keyStore, String keyStorePass, KeyStore trustStore) throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, InvalidKeyException, CertificateException, SecurityException, SignatureException, IOException, KeyManagementException {
Map env = new LinkedHashMap();
env.put("jmx.remote.profiles", JmxmpAgent.TLS_JMX_REMOTE_PROFILES);
if (keyStore == null)
throw new NullPointerException("keyStore must be supplied");
//"SunX509");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, (keyStorePass != null ? keyStorePass : "").toCharArray());
TrustManager tms = trustStore != null ? SecureKeys.getTrustManager(trustStore) : SslTrustUtils.TRUST_ALL;
SSLContext ctx = SSLContext.getInstance("TLSv1");
ctx.init(kmf.getKeyManagers(), new TrustManager[] { tms }, null);
SSLSocketFactory ssf = ctx.getSocketFactory();
env.put(JmxmpAgent.TLS_SOCKET_FACTORY_PROPERTY, ssf);
connect(urlString, env);
}
Example 97
Project: informa-master File: SignatureService.java View source code |
@SuppressWarnings("deprecation") public boolean isVerified(final ILogPack data) throws IOException { try { byte[] signedData = (byte[]) data.remove(Signatures.Keys.SIGNATURE); ByteArrayInputStream sd = new ByteArrayInputStream(signedData); InputStream is = PGPUtil.getDecoderStream(sd); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PGPObjectFactory objFactory = new PGPObjectFactory(is); PGPCompressedData cd = (PGPCompressedData) objFactory.nextObject(); objFactory = new PGPObjectFactory(cd.getDataStream()); PGPOnePassSignatureList sigList_o = (PGPOnePassSignatureList) objFactory.nextObject(); PGPOnePassSignature sig = sigList_o.get(0); PGPLiteralData ld = (PGPLiteralData) objFactory.nextObject(); InputStream literalIn = ld.getInputStream(); sig.initVerify(publicKey, new BouncyCastleProvider()); int read; while ((read = literalIn.read()) > 0) { sig.update((byte) read); baos.write(read); } PGPSignatureList sigList = (PGPSignatureList) objFactory.nextObject(); if (sig.verify(sigList.get(0)) && data.toString().equals(new String(baos.toByteArray()))) { baos.close(); return true; } else { baos.close(); return false; } } catch (PGPException e) { Log.d(LOG, "SignatureException: " + e.getMessage(), e); return false; } catch (SignatureException e) { Log.d(LOG, "SignatureException: " + e.getMessage(), e); return false; } }
Example 98
Project: InformaCore-master File: SignatureService.java View source code |
@SuppressWarnings("deprecation") public boolean isVerified(final ILogPack data) throws IOException { try { byte[] signedData = (byte[]) data.remove(Signatures.Keys.SIGNATURE); ByteArrayInputStream sd = new ByteArrayInputStream(signedData); InputStream is = PGPUtil.getDecoderStream(sd); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PGPObjectFactory objFactory = new PGPObjectFactory(is); PGPCompressedData cd = (PGPCompressedData) objFactory.nextObject(); objFactory = new PGPObjectFactory(cd.getDataStream()); PGPOnePassSignatureList sigList_o = (PGPOnePassSignatureList) objFactory.nextObject(); PGPOnePassSignature sig = sigList_o.get(0); PGPLiteralData ld = (PGPLiteralData) objFactory.nextObject(); InputStream literalIn = ld.getInputStream(); sig.initVerify(publicKey, new BouncyCastleProvider()); int read; while ((read = literalIn.read()) > 0) { sig.update((byte) read); baos.write(read); } PGPSignatureList sigList = (PGPSignatureList) objFactory.nextObject(); if (sig.verify(sigList.get(0)) && data.toString().equals(new String(baos.toByteArray()))) { baos.close(); return true; } else { baos.close(); return false; } } catch (PGPException e) { Log.d(LOG, "SignatureException: " + e.getMessage(), e); return false; } catch (SignatureException e) { Log.d(LOG, "SignatureException: " + e.getMessage(), e); return false; } }
Example 99
Project: instantbuy-quickstart-java-master File: NotifyTransactionStatusServlet.java View source code |
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
Request req = GsonHelper.getGson().fromJson(reader, Request.class);
if (req.jwt == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing required parameter jwt");
return;
}
JwtResponseContainer jwtResponse = JwtGenerator.jwtToJava(JwtResponseContainer.class, req.jwt, Config.getMerchantSecret());
Clock clock = new SystemClock();
// Get the full wallet jwt and create a NotifyTransactionStatus
JwtRequests.TransactionStatusContainer notifyStatus = JwtRequests.newTransactionStatusBuilder().setIss(Config.getMerchantId()).setIat(TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS)).setExp(TimeUnit.SECONDS.convert(clock.now().plus(JwtGenerator.EXPIRATION_DELTA).getMillis(), TimeUnit.MILLISECONDS)).setRequest(TransactionStatusNotification.newBuilder().setGoogleTransactionId(jwtResponse.getResponse().getGoogleTransactionId()).setStatus(TransactionStatusNotification.Status.SUCCESS).build()).build();
response.getWriter().write(JwtGenerator.javaToJWT(notifyStatus, Config.getMerchantSecret()));
} catch (SignatureException e) {
logger.log(Level.SEVERE, "Signature exception ", e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} catch (InvalidKeyException e) {
logger.log(Level.SEVERE, "Invalid key exception", e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} finally {
if (reader != null) {
reader.close();
}
}
}
Example 100
Project: j2objc-master File: MySignature1.java View source code |
protected void engineUpdate(byte[] b, int off, int len) throws SignatureException {
if (b == null)
throw new NullPointerException();
if (off < 0 || off > b.length || off > len) {
throw new IllegalArgumentException("incorrect parameter off");
}
if (len < 0 || len > b.length) {
throw new IllegalArgumentException("incorrect parameter len");
}
runEngineUpdate2 = true;
}
Example 101
Project: java-docs-samples-master File: SignForAppServlet.java View source code |
private String simulateIdentityAssertion() throws CertificateException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
// Simulate the sending app.
String message = "abcdefg";
byte[] blob = message.getBytes();
byte[] blobSignature = signBlob(blob);
byte[] publicCert = getPublicCertificate();
// Simulate the receiving app, which gets the certificate, blob, and signature.
Certificate cert = parsePublicCertificate(publicCert);
PublicKey pk = cert.getPublicKey();
boolean isValid = verifySignature(blob, blobSignature, pk);
return String.format("isValid=%b for message: %s\n\tsignature: %s\n\tpublic cert: %s", isValid, message, Arrays.toString(blobSignature), Arrays.toString(publicCert));
}