Example usage for org.bouncycastle.util.encoders Base64 encode

List of usage examples for org.bouncycastle.util.encoders Base64 encode

Introduction

In this page you can find the example usage for org.bouncycastle.util.encoders Base64 encode.

Prototype

public static byte[] encode(byte[] data) 

Source Link

Document

encode the input data producing a base 64 encoded byte array.

Usage

From source file:org.ow2.jonas.jpaas.vm.configurator.providers.chef.manager.osgi.ChefManagerImpl.java

License:Apache License

/**
 * Sign a message with the private key and encode it in base64
 *
 * @param message//  www .ja va 2s  . c om
 *            the message to encrypt
 * @param privateKey
 *            the private key
 * @throws ChefManagerException if an error occurs
 * @return the signed message
 */
private String sign(String message, KeyPair privateKey) throws ChefManagerException {
    String hash;
    try {
        Signature signature = null;
        signature = Signature.getInstance("NONEwithRSA");

        signature.initSign(privateKey.getPrivate());
        signature.update(message.getBytes());
        byte[] signatureBytes = signature.sign();
        byte[] coded = Base64.encode(signatureBytes);
        hash = new String(coded);
    } catch (Exception e) {
        throw new ChefManagerException("Error during signature", e);
    }
    return hash;
}

From source file:org.owasp.webscarab.plugin.openid.OpenIdHTTPClient.java

License:Open Source License

private String corruptSignature(Request request) {
    NamedValue[] values = getParameters(request);
    if (null == values) {
        return "";
    }//  w  ww. java2 s . c om
    boolean corruptedSignature = false;
    for (int i = 0; i < values.length; i++) {
        String name = values[i].getName();
        String value = Encoding.urlDecode(values[i].getValue());
        if ("openid.sig".equals(name)) {
            byte[] decodedSignature = Base64.decode(value);
            decodedSignature[0]++;
            String corruptEncodedSignature = new String(Base64.encode(decodedSignature));
            values[i] = new NamedValue(name, corruptEncodedSignature);
            corruptedSignature = true;
            break;
        }
    }
    if (false == corruptedSignature) {
        return "";
    }
    updateParameters(values, request);
    return "corrupt signature;";
}

From source file:org.parandroid.sms.transaction.SmsMessageSender.java

License:Apache License

public boolean sendMessage(long token) throws MmsException {
    if ((mMessageText == null) || (mNumberOfDests == 0)) {
        // Don't try to send an empty message.
        throw new MmsException("Null message body or dest.");
    }/*from  ww w  .j a  v a2  s .c  om*/

    SmsManager smsManager = SmsManager.getDefault();

    for (int i = 0; i < mNumberOfDests; i++) {
        boolean isEncrypted = false;

        byte[] encryptedMessage = null;
        if (mTryToEncrypt && MessageEncryptionFactory.hasPublicKey(mContext, mDests[i])) {
            try {
                encryptedMessage = MessageEncryption.encrypt(mContext, mDests[i], mMessageText);
                isEncrypted = true;
            } catch (Exception e) {
                Log.e(TAG, "Error while encrypting message");
                e.printStackTrace();
            }
        }

        ArrayList<String> messages = null;
        if ((MmsConfig.getEmailGateway() != null)
                && (Mms.isEmailAddress(mDests[i]) || MessageUtils.isAlias(mDests[i]))) {
            String msgText;
            msgText = mDests[i] + " " + mMessageText;
            mDests[i] = MmsConfig.getEmailGateway();
            messages = smsManager.divideMessage(msgText);
        } else {
            messages = smsManager.divideMessage(mMessageText);
        }
        int messageCount = messages.size();

        if (messageCount == 0) {
            // Don't try to send an empty message.
            throw new MmsException("SmsMessageSender.sendMessage: divideMessage returned "
                    + "empty messages. Original message is \"" + mMessageText + "\"");
        }

        ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>(messageCount);
        ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>(messageCount);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
        boolean requestDeliveryReport = prefs.getBoolean(MessagingPreferenceActivity.SMS_DELIVERY_REPORT_MODE,
                DEFAULT_DELIVERY_REPORT_MODE);
        Uri uri = null;
        try {
            if (isEncrypted) {
                String outboxText = new String(Base64.encode(encryptedMessage));
                addToParandroidOutbox(i, outboxText);

            } else {
                uri = Sms.Outbox.addMessage(mContext.getContentResolver(), mDests[i], mMessageText, null,
                        mTimestamp, requestDeliveryReport, mThreadId);
            }
        } catch (SQLiteException e) {
            SqliteWrapper.checkSQLiteException(mContext, e);
        }

        for (int j = 0; j < messageCount; j++) {
            if (requestDeliveryReport) {
                // TODO: Fix: It should not be necessary to
                // specify the class in this intent.  Doing that
                // unnecessarily limits customizability.
                deliveryIntents.add(PendingIntent.getBroadcast(mContext, 0,
                        new Intent(MessageStatusReceiver.MESSAGE_STATUS_RECEIVED_ACTION, uri, mContext,
                                MessageStatusReceiver.class),
                        0));
            }
            sentIntents.add(PendingIntent.getBroadcast(mContext, 0,
                    new Intent(SmsReceiverService.MESSAGE_SENT_ACTION, uri, mContext, SmsReceiver.class), 0));
        }

        if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
            log("sendMessage: address[" + i + "]=" + mDests[i] + ", threadId=" + mThreadId + ", uri=" + uri
                    + ", msgs.count=" + messageCount);
        }

        if (!isEncrypted) {
            // we send the msg unencrypted if we don't have the public key, or when the number of
            // messages is larger than 1 (there is no support to send multipart datamessages yet)
            try {
                smsManager.sendMultipartTextMessage(mDests[i], mServiceCenter, messages, sentIntents,
                        deliveryIntents);
            } catch (Exception ex) {
                throw new MmsException("SmsMessageSender.sendMessage: caught " + ex
                        + " from SmsManager.sendMultipartTextMessage()");
            }
        } else {
            MultipartDataMessage m = new MultipartDataMessage(MultipartDataMessage.TYPE_MESSAGE, mDests[i],
                    encryptedMessage, sentIntents, deliveryIntents);
            m.send();
        }

    }

    return false;
}

From source file:org.parandroid.sms.ui.ConversationList.java

License:Apache License

private void encryptBackward() throws Exception {
    Uri uriSms = Uri.parse("content://sms");
    String selection = Inbox.TYPE + "='" + MessageItem.MESSAGE_TYPE_PARANDROID_INBOX + "' OR " + Inbox.TYPE
            + "='" + MessageItem.MESSAGE_TYPE_PARANDROID_OUTBOX + "'";

    final Cursor backwardCursor = getContentResolver().query(uriSms, BACKWARD_PROJECTION, selection, null,
            null);/*from   www  . j  a  v  a2  s.  c o m*/
    if (!backwardCursor.moveToFirst()) {
        Log.i(TAG, "backward: No messages");
        return;
    }

    int numMessages = backwardCursor.getCount();
    Log.i(TAG, "Re-encrypting " + numMessages + " messages");

    final ProgressDialog progressDialog = new ProgressDialog(ConversationList.this);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.setMessage(getString(R.string.reencrypting_messages));
    progressDialog.setCancelable(false);
    progressDialog.setMax(numMessages);
    progressDialog.show();

    new Thread(new Runnable() {
        public void run() {
            do {
                try {
                    String address = backwardCursor.getString(backwardCursor.getColumnIndex(Inbox.ADDRESS));

                    Log.i(TAG, "backward: oldpriv: " + oldPrivateKey);
                    Log.i(TAG, "backward: address: " + address);

                    String body = backwardCursor.getString(backwardCursor.getColumnIndex(Inbox.BODY));
                    Log.i(TAG, "backward: oldbody: " + body);

                    String clearBody = MessageEncryption.decrypt(ConversationList.this, oldPrivateKey, address,
                            Base64.decode(body));
                    Log.i(TAG, "backward: clear: " + clearBody);

                    String newBody = new String(Base64
                            .encode(MessageEncryption.encrypt(ConversationList.this, address, clearBody)));
                    Log.i(TAG, "backward: newbody: " + newBody);

                    backwardCursor.updateString(backwardCursor.getColumnIndex(Inbox.BODY), newBody);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                progressDialog.incrementProgressBy(1);
            } while (backwardCursor.moveToNext());

            progressDialog.dismiss();

            backwardCursor.commitUpdates();
            backwardCursor.close();
            oldPrivateKey = null;
        }
    }).start();
}

From source file:org.qipki.crypto.codec.CryptCodexImpl.java

License:Open Source License

@Override
public String toBase64String(byte[] bytes) {
    try {/*ww  w.  ja v  a 2 s. c  om*/
        return new String(Base64.encode(bytes), "UTF-8");
    } catch (UnsupportedEncodingException ex) {
        throw new CryptoFailure("Unable to encode data in Base64", ex);
    }
}

From source file:org.qipki.crypto.io.CryptIOImpl.java

License:Open Source License

@Override
public String base64Encode(KeyStore keystore, char[] password) {
    ByteArrayOutputStream baos = null;
    try {/*from w  ww .j  a  v  a 2 s  .c om*/
        baos = new ByteArrayOutputStream();
        keystore.store(baos, password);
        baos.flush();
        return new String(Base64.encode(baos.toByteArray()), IOConstants.UTF_8);
    } catch (IOException ex) {
        throw new CryptoFailure("Unable to Base64 encode KeyStore", ex);
    } catch (GeneralSecurityException ex) {
        throw new CryptoFailure("Unable to Base64 encode KeyStore", ex);
    } finally {
        IO.closeSilently(baos);
    }
}

From source file:org.red5.net.websocket.codec.WebSocketDecoder.java

License:Open Source License

/**
 * Build a handshake response based on the given client key.
 * //from   w ww. j  av a  2  s.c om
 * @param clientKey
 * @return response
 * @throws WebSocketException
 */
private HandshakeResponse buildHandshakeResponse(WebSocketConnection conn, String clientKey)
        throws WebSocketException {
    byte[] accept;
    try {
        // performs the accept creation routine from RFC6455 @see <a href="http://tools.ietf.org/html/rfc6455">RFC6455</a>
        // concatenate the key and magic string, then SHA1 hash and base64 encode
        MessageDigest md = MessageDigest.getInstance("SHA1");
        accept = Base64.encode(md.digest((clientKey + Constants.WEBSOCKET_MAGIC_STRING).getBytes()));
    } catch (NoSuchAlgorithmException e) {
        throw new WebSocketException("Algorithm is missing");
    }
    // make up reply data...
    IoBuffer buf = IoBuffer.allocate(308);
    buf.setAutoExpand(true);
    buf.put("HTTP/1.1 101 Switching Protocols".getBytes());
    buf.put(Constants.CRLF);
    buf.put("Upgrade: websocket".getBytes());
    buf.put(Constants.CRLF);
    buf.put("Connection: Upgrade".getBytes());
    buf.put(Constants.CRLF);
    buf.put("Server: Red5".getBytes());
    buf.put(Constants.CRLF);
    buf.put("Sec-WebSocket-Version-Server: 13".getBytes());
    buf.put(Constants.CRLF);
    buf.put(String.format("Sec-WebSocket-Origin: %s", conn.getOrigin()).getBytes());
    buf.put(Constants.CRLF);
    buf.put(String.format("Sec-WebSocket-Location: %s", conn.getHost()).getBytes());
    buf.put(Constants.CRLF);
    // send back extensions if enabled
    if (conn.hasExtensions()) {
        buf.put(String.format("Sec-WebSocket-Extensions: %s", conn.getExtensionsAsString()).getBytes());
        buf.put(Constants.CRLF);
    }
    // send back protocol if enabled
    if (conn.hasProtocol()) {
        buf.put(String.format("Sec-WebSocket-Protocol: %s", conn.getProtocol()).getBytes());
        buf.put(Constants.CRLF);
    }
    buf.put(String.format("Sec-WebSocket-Accept: %s", new String(accept)).getBytes());
    buf.put(Constants.CRLF);
    buf.put(Constants.CRLF);
    // if any bytes follow this crlf, the follow-up data will be corrupted
    if (log.isTraceEnabled()) {
        log.trace("Handshake response size: {}", buf.limit());
    }
    return new HandshakeResponse(buf);
}

From source file:org.ScripterRon.BitcoinCore.ECKey.java

License:Apache License

/**
 * Signs a message using the private key
 *
 * @param       message             Message to be signed
 * @return                          Base64-encoded signature string
 * @throws      ECException         Unable to sign the message
 *//*  w w w  . j  a va2  s  .  c o  m*/
public String signMessage(String message) throws ECException {
    String encodedSignature;
    if (privKey == null)
        throw new IllegalStateException("No private key available");
    try {
        //
        // Format the message for signing
        //
        byte[] contents;
        try (ByteArrayOutputStream outStream = new ByteArrayOutputStream(message.length() * 2)) {
            byte[] headerBytes = BITCOIN_SIGNED_MESSAGE_HEADER.getBytes("UTF-8");
            outStream.write(VarInt.encode(headerBytes.length));
            outStream.write(headerBytes);
            byte[] messageBytes = message.getBytes("UTF-8");
            outStream.write(VarInt.encode(messageBytes.length));
            outStream.write(messageBytes);
            contents = outStream.toByteArray();
        }
        //
        // Create the signature
        //
        ECDSASignature sig = createSignature(contents);
        //
        // Get the RecID used to recover the public key from the signature
        //
        BigInteger e = new BigInteger(1, Utils.doubleDigest(contents));
        int recID = -1;
        for (int i = 0; i < 4; i++) {
            ECKey k = recoverFromSignature(i, sig, e, isCompressed());
            if (k != null && Arrays.equals(k.getPubKey(), pubKey)) {
                recID = i;
                break;
            }
        }
        if (recID == -1)
            throw new ECException("Unable to recover public key from signature");
        //
        // The message signature consists of a header byte followed by the R and S values
        //
        int headerByte = recID + 27 + (isCompressed() ? 4 : 0);
        byte[] sigData = new byte[65];
        sigData[0] = (byte) headerByte;
        System.arraycopy(Utils.bigIntegerToBytes(sig.getR(), 32), 0, sigData, 1, 32);
        System.arraycopy(Utils.bigIntegerToBytes(sig.getS(), 32), 0, sigData, 33, 32);
        //
        // Create a Base-64 encoded string for the message signature
        //
        encodedSignature = new String(Base64.encode(sigData), "UTF-8");
    } catch (IOException exc) {
        throw new IllegalStateException("Unexpected IOException", exc);
    }
    return encodedSignature;
}

From source file:org.signserver.client.api.SigningAndValidationWS.java

License:Open Source License

public List<ProcessResponse> process(String workerIdOrName, List<ProcessRequest> requests,
        RequestContext context)/*  w ww.j  a v a 2 s.  c  o m*/
        throws IllegalRequestException, CryptoTokenOfflineException, SignServerException {
    try {
        List<ProcessRequestWS> list = new LinkedList<ProcessRequestWS>();

        ProcessRequestWS.RequestMetadata metadata = new ProcessRequestWS.RequestMetadata();
        final RequestMetadata requestMetadata = RequestMetadata.getInstance(context);

        List<Entry> entries = metadata.getEntry();
        for (Map.Entry<String, String> entry : requestMetadata.entrySet()) {
            Entry e = new Entry();
            e.setKey(entry.getKey());
            e.setValue(entry.getValue());
            entries.add(e);
        }

        for (ProcessRequest req : requests) {
            ProcessRequestWS reqWS = new ProcessRequestWS();
            reqWS.setRequestDataBase64(
                    new String(Base64.encode(RequestAndResponseManager.serializeProcessRequest(req))));
            reqWS.setRequestMetadata(metadata);
            list.add(reqWS);
        }

        List<ProcessResponseWS> resps;
        try {
            resps = signserver.process(workerIdOrName, list);
        } catch (CryptoTokenOfflineException_Exception e) {
            LOG.error(null, e);
            throw new CryptoTokenOfflineException(e.getMessage());
        } catch (IllegalRequestException_Exception e) {
            LOG.error(null, e);
            throw new IllegalRequestException(e.getMessage());
        } catch (InvalidWorkerIdException_Exception e) {
            LOG.error(null, e);
            throw new IllegalRequestException(e.getMessage());
        } catch (SignServerException_Exception e) {
            LOG.error(null, e);
            throw new SignServerException(e.getMessage());
        }

        List<org.signserver.protocol.ws.ProcessResponseWS> responses2 = WSClientUtil
                .convertProcessResponseWS(resps);

        List<ProcessResponse> responses3 = new LinkedList<ProcessResponse>();
        for (org.signserver.protocol.ws.ProcessResponseWS resp : responses2) {
            responses3.add(RequestAndResponseManager.parseProcessResponse(resp.getResponseData()));
        }

        return responses3;

    } catch (IOException ex) {
        throw new SignServerException("Serialization/deserialization failed", ex);
    }
}

From source file:org.signserver.client.api.SigningAndValidationWSBalanced.java

License:Open Source License

public List<ProcessResponse> process(String workerIdOrName, List<ProcessRequest> requests,
        RequestContext context)// w w  w .  ja va2s.  co  m
        throws IllegalRequestException, CryptoTokenOfflineException, SignServerException {

    try {

        List<org.signserver.protocol.ws.ProcessRequestWS> list = new LinkedList<org.signserver.protocol.ws.ProcessRequestWS>();

        for (ProcessRequest req : requests) {
            org.signserver.protocol.ws.ProcessRequestWS reqWS = new org.signserver.protocol.ws.ProcessRequestWS();
            reqWS.setRequestDataBase64(
                    new String(Base64.encode(RequestAndResponseManager.serializeProcessRequest(req))));
            list.add(reqWS);
        }

        List<org.signserver.protocol.ws.ProcessResponseWS> resps = signserver.process(workerIdOrName, list);

        if (resps == null) {
            LOG.error(exception.getMessage(), exception);
            throw new SignServerException("Exception", exception);
        }

        List<ProcessResponse> responses3 = new LinkedList<ProcessResponse>();

        for (org.signserver.protocol.ws.ProcessResponseWS resp : resps) {
            responses3.add(RequestAndResponseManager.parseProcessResponse(resp.getResponseData()));
        }

        return responses3;

    } catch (IOException ex) {
        throw new SignServerException("Serialization/deserialization failed", ex);
    }
}