/** * Method that verifies an incoming signature and returns the response as application/xml. * * @param signatureVerificationRequest the request which is converted to a {@link * SignatureVerificationRequest} from xml * @return the {@link SignatureVerificationResponse} as application/xml */ @POST @Path("/verifySignature") @Consumes("application/xml") @Produces("application/xml") public SignatureVerificationResponse verifySignature( SignatureVerificationRequest signatureVerificationRequest) { SignatureVerificationResponse response = new SignatureVerificationResponse(); response.setCertificateInfos(new CertificateInfos()); boolean verified = false; String message = null; try { SignatureFormat format = signatureVerificationRequest.getSignatureFormat(); if (SignatureFormat.XMLDIGSIG.equals(format)) { try { SignatureData signatureData = getFromXmlDigSigSignature(signatureVerificationRequest, response); verified = super.verifySignature(signatureData); } catch (SignatureException e) { e.printStackTrace(); message = e.getMessage(); } } else if (SignatureFormat.CMS.equals(format)) { SignatureData signData = getFromCmsSignature(signatureVerificationRequest, response); try { // Verify verified = super.verifySignature(signData); } catch (SignatureException e) { e.printStackTrace(); message = e.getMessage(); } } response.setStatus(verified ? SignatureStatus.SUCCESS : SignatureStatus.FAILURE); if (message != null) { response.setMessage(message); } } catch (IOException ex) { throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR); } catch (MarshalException ex) { throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR); } catch (ParserConfigurationException ex) { throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR); } catch (SAXException ex) { throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR); } catch (CMSException ex) { throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR); } return response; }
@Override public Long readUserIdFromToken(String token) { Long id = null; try { Map<String, Object> parsed = verifier.verify(token); Object objectId = parsed.get("id"); if (objectId instanceof Integer) { id = Long.valueOf((Integer) objectId); } else if (objectId instanceof Long) { id = (Long) objectId; } else if (objectId instanceof String) { id = Long.valueOf((String) objectId); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } catch (JWTVerifyException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return id; }
@Override public Response createResponse() { // todo fix this with JSON etc. String plainText = getPlainText(); try { signedText_ = Signature.calculateRFC2104HMAC(plainText, key_); } catch (SignatureException e) { e.printStackTrace(); } return this; }
/** * Endorse the proof * * @param aStampContext current context * @param aProof proof * @return endorsed proof * @throws NoSuchAlgorithmException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws NoSuchPaddingException * @throws InvalidKeyException */ private static byte[] endorseP(WitnessContext aStampContext, byte aProof[]) { // Sign on the proof first byte[] sig = {}; try { sig = CryptoUtil.signDSA(aStampContext.getPriDSASelf(), aProof); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } // Include own ID in EP byte[] wID = aStampContext.getPubDSASelf().getEncoded(); ArrayList<byte[]> array = new ArrayList<byte[]>(); array.add(wID); array.add(aProof); array.add(sig); byte[] epContent = MessageUtil.compileMessages(array); // Encrypt epContent with an AES key first SecretKey aesKey = null; byte[] epEncrypted = {}; byte[] keyEncrypted = {}; try { aesKey = CryptoUtil.generateAESKey(128); epEncrypted = CryptoUtil.encryptAES(aesKey, epContent); keyEncrypted = CryptoUtil.encryptRSA(aStampContext.getPubRSACA(), aesKey.getEncoded()); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } ArrayList<byte[]> arrayOut = new ArrayList<byte[]>(); arrayOut.add(epEncrypted); arrayOut.add(keyEncrypted); return MessageUtil.compileMessages(arrayOut); }
/** * Verify that signature is ok or not. * * @param key * @param buffer * @param signature * @return */ public boolean verifySignature(byte[] buffer, byte[] signature) { try { Signature sig = Signature.getInstance("SHA1WithRSA"); sig.initVerify(keyPair.getPublic()); sig.update(buffer, 0, buffer.length); return sig.verify(signature); } catch (SignatureException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return false; }
private byte[] doSign() { KeyPair keys = loadAllKeysFromKeystore(); Signature sig = null; byte[] sigByte = null; PrivateKey privKey = keys.getPrivate(); try { sig = Signature.getInstance("SHA1WithRSA"); sig.initSign(privKey); sig.update(this.document, 0, this.document.length); sigByte = sig.sign(); } catch (SignatureException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return sigByte; }
@Override public MetadataObject resolve(X509Certificate attestationCertificate) { String issuer = attestationCertificate.getIssuerDN().getName(); for (X509Certificate cert : certs.get(issuer)) { try { attestationCertificate.verify(cert.getPublicKey()); return metadata.get(cert); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } } return null; }
/** * @param aSecretCertificate * @param currentDate * @param appId * @return */ private static boolean isValidCertificate( String aSecretCertificate, String currentDate, String appId) { boolean isValid = false; String hMacString; try { // load the privatekey for the appId // TODO load the private for this appid String privateKey = "kljlkdfldsflds"; String data = currentDate + appId; hMacString = calculateRFC2104HMAC(privateKey, data); if (aSecretCertificate.equals(hMacString)) ; isValid = true; } catch (InvalidKeyException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return isValid; }
public Boolean verifySignature(byte[] originalData, byte[] signedData) { boolean verified = false; try { Signature sig = Signature.getInstance("SHA1withDSA", "SUN"); sig.initVerify(getPublicKey()); sig.update(originalData, 0, originalData.length); verified = sig.verify(signedData); } catch (SignatureException ex) { ex.printStackTrace(); Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null); } catch (InvalidKeyException ex) { ex.printStackTrace(); Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null); } catch (NoSuchProviderException ex) { ex.printStackTrace(); Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null); } return verified; }
@Override public boolean verifySignature(Object message, byte[] signatureToVerify) { // return true; try { Signature newSig = Signature.getInstance(CryptoUtil.ALGORITHM, CryptoUtil.PROVIDER); newSig.initVerify(publicKey); byte[] byteRep = CryptoUtil.convertToJsonByteArray(message); newSig.update(byteRep); newSig.verify(signatureToVerify); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); return false; } return true; }
@Override public void onClick(View view) { Utils.Log("Send clicked"); // If the message field is not empty if (!messageText.getText().toString().isEmpty()) { final Message message = new Message(); message.setSender(username); message.setRecipient(conversation.getUsername()); // If DHKE was completed and a key exists if (!dbManager.getAESKey(conversation.getUsername()).isEmpty()) { String signature = ""; String key = dbManager.getAESKey(conversation.getUsername()); byte[] iv = Crypto.GenerateRandomIV(); final String plainText = messageText.getText().toString(); final String cipherText = Crypto.AESencrypt(key, plainText, iv); final String base64IV = Base64.encodeToString(iv, Base64.NO_WRAP); try { PrivateKey RSAKeySign = Crypto.RSAStringToPrivateKey(dbManager.getRSAKeySignaturePrivate()); signature = Base64.encodeToString( Crypto.RSASign(Base64.decode(cipherText, Base64.NO_WRAP), RSAKeySign), Base64.NO_WRAP); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } message.setMessage(cipherText); message.setIv(base64IV); message.setSignature(signature); new HttpHandler() { @Override public HttpUriRequest getHttpRequestMethod() { HttpPost httpPost = new HttpPost(Utils.SERVER_SEND_MESSAGE); List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("sender", message.getSender())); nameValuePairs.add(new BasicNameValuePair("recipient", message.getRecipient())); nameValuePairs.add(new BasicNameValuePair("message", message.getMessage())); nameValuePairs.add(new BasicNameValuePair("iv", message.getIv())); nameValuePairs.add(new BasicNameValuePair("signature", message.getSignature())); try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return httpPost; } @Override public void onResponse(String result) { Utils.Log("HttpResult: " + result); if (conversation.isEncrypted().equals("true")) { message.setMessage( Crypto.AESencrypt( conversationPass, plainText, Base64.decode(message.getIv(), Base64.NO_WRAP))); message.setEncrypted(true); dbManager.addMessage(message); message.setEncrypted(false); message.setMessage(plainText); messages.add(message); adapter.notifyDataSetChanged(); } else { message.setMessage(plainText); message.setEncrypted(false); dbManager.addMessage(message); messages.add(message); adapter.notifyDataSetChanged(); } messageList.setSelection(messages.size() + 1); } }.execute(); messageText.setText(""); } // DHKE was not complete yet, store messages unencrypted temporarily // and then encrypt and send them once the exchange is complete else { message.setEncrypted(false); message.setMessage(messageText.getText().toString()); message.setIv(Base64.encodeToString(Crypto.GenerateRandomIV(), Base64.NO_WRAP)); dbManager.addMessage(message); messages.add(message); adapter.notifyDataSetChanged(); messageList.setSelection(adapter.getCount() - 1); messageText.setText(""); } } }