Java Code Examples for org.jivesoftware.smack.util.stringencoder.Base64#encodeToString()
The following examples show how to use
org.jivesoftware.smack.util.stringencoder.Base64#encodeToString() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PainlessOpenPgpProvider.java From Smack with Apache License 2.0 | 6 votes |
@Override public OpenPgpElementAndMetadata sign(SignElement element, OpenPgpSelf self) throws IOException, PGPException { InputStream plainText = element.toInputStream(); ByteArrayOutputStream cipherText = new ByteArrayOutputStream(); EncryptionStream cipherStream = PGPainless.createEncryptor().onOutputStream(cipherText) .doNotEncrypt() .signWith(getStore().getKeyRingProtector(), self.getSigningKeyRing()) .noArmor(); Streams.pipeAll(plainText, cipherStream); plainText.close(); cipherStream.flush(); cipherStream.close(); cipherText.close(); String base64 = Base64.encodeToString(cipherText.toByteArray()); OpenPgpElement openPgpElement = new OpenPgpElement(base64); return new OpenPgpElementAndMetadata(openPgpElement, cipherStream.getResult()); }
Example 2
Source File: SASLMechanism.java From Smack with Apache License 2.0 | 6 votes |
/** * The server is challenging the SASL mechanism for the stanza he just sent. Send a * response to the server's challenge. * * @param challengeString a base64 encoded string representing the challenge. * @param finalChallenge true if this is the last challenge send by the server within the success stanza * @throws SmackSaslException if a SASL related error occurs. * @throws InterruptedException if the connection is interrupted * @throws NotConnectedException if the XMPP connection is not connected. */ public final void challengeReceived(String challengeString, boolean finalChallenge) throws SmackSaslException, InterruptedException, NotConnectedException { byte[] challenge = Base64.decode((challengeString != null && challengeString.equals("=")) ? "" : challengeString); byte[] response = evaluateChallenge(challenge); if (finalChallenge) { return; } Response responseStanza; if (response == null) { responseStanza = new Response(); } else { responseStanza = new Response(Base64.encodeToString(response)); } // Send the authentication to the server connection.sendNonza(responseStanza); }
Example 3
Source File: SASLMechanism.java From Smack with Apache License 2.0 | 6 votes |
private void authenticate() throws SmackSaslException, NotConnectedException, InterruptedException { byte[] authenticationBytes = getAuthenticationText(); String authenticationText; // Some SASL mechanisms do return an empty array (e.g. EXTERNAL from javax), so check that // the array is not-empty. Mechanisms are allowed to return either 'null' or an empty array // if there is no authentication text. if (authenticationBytes != null && authenticationBytes.length > 0) { authenticationText = Base64.encodeToString(authenticationBytes); } else { // RFC6120 6.4.2 "If the initiating entity needs to send a zero-length initial response, // it MUST transmit the response as a single equals sign character ("="), which // indicates that the response is present but contains no data." authenticationText = "="; } // Send the authentication to the server connection.sendNonza(new AuthMechanism(getName(), authenticationText)); }
Example 4
Source File: InBandBytestreamSessionTest.java From Smack with Apache License 2.0 | 5 votes |
/** * Test the input stream read() method. * * @throws Exception should not happen */ @Test public void shouldReadAllReceivedData2() throws Exception { // create random data Random rand = new Random(); byte[] controlData = new byte[3 * blockSize]; rand.nextBytes(controlData); IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class); // set data packet acknowledgment and notify listener for (int i = 0; i < controlData.length / blockSize; i++) { protocol.addResponse(resultIQ); String base64Data = Base64.encodeToString(controlData, i * blockSize, blockSize); DataPacketExtension dpe = new DataPacketExtension(sessionID, i, base64Data); Data data = new Data(dpe); listener.processStanza(data); } // read data byte[] bytes = new byte[3 * blockSize]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) inputStream.read(); } // verify data for (int i = 0; i < bytes.length; i++) { assertEquals(controlData[i], bytes[i]); } protocol.verifyAll(); }
Example 5
Source File: OmemoBundleElement.java From Smack with Apache License 2.0 | 5 votes |
/** * Constructor to create a Bundle Element from decoded byte arrays. * * @param signedPreKeyId id * @param signedPreKey signedPreKey * @param signedPreKeySig signedPreKeySignature * @param identityKey identityKey * @param preKeys HashMap of preKeys */ public OmemoBundleElement(int signedPreKeyId, byte[] signedPreKey, byte[] signedPreKeySig, byte[] identityKey, HashMap<Integer, byte[]> preKeys) { this(signedPreKeyId, signedPreKey != null ? Base64.encodeToString(signedPreKey) : null, signedPreKeySig != null ? Base64.encodeToString(signedPreKeySig) : null, identityKey != null ? Base64.encodeToString(identityKey) : null, base64EncodePreKeys(preKeys)); this.signedPreKey = signedPreKey; this.signedPreKeySignature = signedPreKeySig; this.identityKey = identityKey; this.preKeys = preKeys; }
Example 6
Source File: InBandBytestreamSessionMessageTest.java From Smack with Apache License 2.0 | 5 votes |
/** * Test the input stream read() method. * * @throws Exception should not happen */ @Test public void shouldReadAllReceivedData2() throws Exception { // create random data Random rand = new Random(); byte[] controlData = new byte[3 * blockSize]; rand.nextBytes(controlData); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class); // verify data packet and notify listener for (int i = 0; i < controlData.length / blockSize; i++) { String base64Data = Base64.encodeToString(controlData, i * blockSize, blockSize); DataPacketExtension dpe = new DataPacketExtension(sessionID, i, base64Data); Message dataMessage = StanzaBuilder.buildMessage() .addExtension(dpe) .build(); listener.processStanza(dataMessage); } // read data byte[] bytes = new byte[3 * blockSize]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) inputStream.read(); } // verify data for (int i = 0; i < bytes.length; i++) { assertEquals(controlData[i], bytes[i]); } protocol.verifyAll(); }
Example 7
Source File: BoBData.java From Smack with Apache License 2.0 | 5 votes |
/** * Get the content in a Base64 encoded String. * * @return the content in a Base64 encoded String */ public String getContentBase64Encoded() { if (contentString == null) { contentString = Base64.encodeToString(getContent()); } return contentString; }
Example 8
Source File: VCard.java From Smack with Apache License 2.0 | 5 votes |
/** * Specify the bytes for the avatar to use as well as the mime type. * * @param bytes the bytes of the avatar. * @param mimeType the mime type of the avatar. */ public void setAvatar(byte[] bytes, String mimeType) { // If bytes is null, remove the avatar if (bytes == null) { removeAvatar(); return; } // Otherwise, add to mappings. String encodedImage = Base64.encodeToString(bytes); setAvatar(encodedImage, mimeType); }
Example 9
Source File: InBandBytestreamSession.java From Smack with Apache License 2.0 | 5 votes |
private synchronized void flushBuffer() throws IOException { // do nothing if no data to send available if (bufferPointer == 0) { return; } // create data packet String enc = Base64.encodeToString(buffer, 0, bufferPointer); DataPacketExtension data = new DataPacketExtension(byteStreamRequest.getSessionID(), this.seq, enc); // write to XMPP stream try { writeToXML(data); } catch (InterruptedException | NotConnectedException e) { IOException ioException = new IOException(); ioException.initCause(e); throw ioException; } // reset buffer pointer bufferPointer = 0; // increment sequence, considering sequence overflow this.seq = this.seq + 1 == 65535 ? 0 : this.seq + 1; }
Example 10
Source File: PainlessOpenPgpProvider.java From Smack with Apache License 2.0 | 5 votes |
@Override public OpenPgpElementAndMetadata encrypt(CryptElement element, OpenPgpSelf self, Collection<OpenPgpContact> recipients) throws IOException, PGPException { InputStream plainText = element.toInputStream(); ByteArrayOutputStream cipherText = new ByteArrayOutputStream(); ArrayList<PGPPublicKeyRingCollection> recipientKeys = new ArrayList<>(); for (OpenPgpContact contact : recipients) { PGPPublicKeyRingCollection keys = contact.getTrustedAnnouncedKeys(); if (keys != null) { recipientKeys.add(keys); } else { LOGGER.log(Level.WARNING, "There are no suitable keys for contact " + contact.getJid().toString()); } } EncryptionStream cipherStream = PGPainless.createEncryptor().onOutputStream(cipherText) .toRecipients(recipientKeys.toArray(new PGPPublicKeyRingCollection[] {})) .andToSelf(self.getTrustedAnnouncedKeys()) .usingSecureAlgorithms() .doNotSign() .noArmor(); Streams.pipeAll(plainText, cipherStream); plainText.close(); cipherStream.flush(); cipherStream.close(); cipherText.close(); String base64 = Base64.encodeToString(cipherText.toByteArray()); OpenPgpElement openPgpElement = new OpenPgpElement(base64); return new OpenPgpElementAndMetadata(openPgpElement, cipherStream.getResult()); }
Example 11
Source File: PainlessOpenPgpProvider.java From Smack with Apache License 2.0 | 5 votes |
@Override public OpenPgpElementAndMetadata signAndEncrypt(SigncryptElement element, OpenPgpSelf self, Collection<OpenPgpContact> recipients) throws IOException, PGPException { InputStream plainText = element.toInputStream(); ByteArrayOutputStream cipherText = new ByteArrayOutputStream(); ArrayList<PGPPublicKeyRingCollection> recipientKeys = new ArrayList<>(); for (OpenPgpContact contact : recipients) { PGPPublicKeyRingCollection keys = contact.getTrustedAnnouncedKeys(); if (keys != null) { recipientKeys.add(keys); } else { LOGGER.log(Level.WARNING, "There are no suitable keys for contact " + contact.getJid().toString()); } } EncryptionStream cipherStream = PGPainless.createEncryptor().onOutputStream(cipherText) .toRecipients(recipientKeys.toArray(new PGPPublicKeyRingCollection[] {})) .andToSelf(self.getTrustedAnnouncedKeys()) .usingSecureAlgorithms() .signWith(getStore().getKeyRingProtector(), self.getSigningKeyRing()) .noArmor(); Streams.pipeAll(plainText, cipherStream); plainText.close(); cipherStream.flush(); cipherStream.close(); cipherText.close(); String base64 = Base64.encodeToString(cipherText.toByteArray()); OpenPgpElement openPgpElement = new OpenPgpElement(base64); return new OpenPgpElementAndMetadata(openPgpElement, cipherStream.getResult()); }
Example 12
Source File: OmemoVAxolotlElementTest.java From Smack with Apache License 2.0 | 5 votes |
@Test public void serializationTest() throws Exception { byte[] payload = "This is payload.".getBytes(StandardCharsets.UTF_8); int keyId1 = 8; int keyId2 = 33333; byte[] keyData1 = "KEYDATA".getBytes(StandardCharsets.UTF_8); byte[] keyData2 = "DATAKEY".getBytes(StandardCharsets.UTF_8); int sid = 12131415; byte[] iv = OmemoMessageBuilder.generateIv(); ArrayList<OmemoKeyElement> keys = new ArrayList<>(); keys.add(new OmemoKeyElement(keyData1, keyId1)); keys.add(new OmemoKeyElement(keyData2, keyId2, true)); OmemoHeaderElement_VAxolotl header = new OmemoHeaderElement_VAxolotl(sid, keys, iv); OmemoElement_VAxolotl element = new OmemoElement_VAxolotl(header, payload); String expected = "<encrypted xmlns='eu.siacs.conversations.axolotl'>" + "<header sid='12131415'>" + "<key rid='8'>" + Base64.encodeToString(keyData1) + "</key>" + "<key prekey='true' rid='33333'>" + Base64.encodeToString(keyData2) + "</key>" + "<iv>" + Base64.encodeToString(iv) + "</iv>" + "</header>" + "<payload>" + Base64.encodeToString(payload) + "</payload>" + "</encrypted>"; String actual = element.toXML().toString(); assertEquals("Serialized xml of OmemoElement must match.", expected, actual); OmemoElement_VAxolotl parsed = new OmemoVAxolotlProvider().parse(TestUtils.getParser(actual)); assertEquals("Parsed OmemoElement must equal the original.", element.toXML().toString(), parsed.toXML().toString()); }
Example 13
Source File: HashElement.java From Smack with Apache License 2.0 | 4 votes |
/** * Create a HashElement from pre-calculated values. * @param algorithm The algorithm which was used. * @param hash the checksum as byte array. */ public HashElement(HashManager.ALGORITHM algorithm, byte[] hash) { this.algorithm = requireNonNull(algorithm); this.hash = requireNonNull(hash); hashB64 = Base64.encodeToString(hash); }
Example 14
Source File: JivePropertiesExtension.java From Smack with Apache License 2.0 | 4 votes |
@Override public CharSequence toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) { XmlStringBuilder xml = new XmlStringBuilder(this); xml.rightAngleBracket(); // Loop through all properties and write them out. for (String name : getPropertyNames()) { Object value = getProperty(name); xml.openElement("property"); xml.element("name", name); xml.halfOpenElement("value"); String type; String valueStr; if (value instanceof Integer) { type = "integer"; valueStr = Integer.toString((Integer) value); } else if (value instanceof Long) { type = "long"; valueStr = Long.toString((Long) value); } else if (value instanceof Float) { type = "float"; valueStr = Float.toString((Float) value); } else if (value instanceof Double) { type = "double"; valueStr = Double.toString((Double) value); } else if (value instanceof Boolean) { type = "boolean"; valueStr = Boolean.toString((Boolean) value); } else if (value instanceof String) { type = "string"; valueStr = (String) value; } // Otherwise, it's a generic Serializable object. Serialized objects are in // a binary format, which won't work well inside of XML. Therefore, we base-64 // encode the binary data before adding it. else { try ( ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteStream); ) { out.writeObject(value); type = "java-object"; valueStr = Base64.encodeToString(byteStream.toByteArray()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error encoding java object", e); type = "java-object"; valueStr = "Serializing error: " + e.getMessage(); } } xml.attribute("type", type); xml.rightAngleBracket(); xml.escape(valueStr); xml.closeElement("value"); xml.closeElement("property"); } xml.closeElement(this); return xml; }
Example 15
Source File: InBandBytestreamSessionMessageTest.java From Smack with Apache License 2.0 | 4 votes |
/** * Test the input stream read(byte[], int, int) method. * * @throws Exception should not happen */ @Test public void shouldReadAllReceivedData1() throws Exception { // create random data Random rand = new Random(); byte[] controlData = new byte[3 * blockSize]; rand.nextBytes(controlData); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class); // verify data packet and notify listener for (int i = 0; i < controlData.length / blockSize; i++) { String base64Data = Base64.encodeToString(controlData, i * blockSize, blockSize); DataPacketExtension dpe = new DataPacketExtension(sessionID, i, base64Data); Message dataMessage = StanzaBuilder.buildMessage() .addExtension(dpe) .build(); listener.processStanza(dataMessage); } byte[] bytes = new byte[3 * blockSize]; int read; read = inputStream.read(bytes, 0, blockSize); assertEquals(blockSize, read); read = inputStream.read(bytes, 10, blockSize); assertEquals(blockSize, read); read = inputStream.read(bytes, 20, blockSize); assertEquals(blockSize, read); // verify data for (int i = 0; i < bytes.length; i++) { assertEquals(controlData[i], bytes[i]); } protocol.verifyAll(); }
Example 16
Source File: InBandBytestreamSessionTest.java From Smack with Apache License 2.0 | 4 votes |
/** * Test the input stream read(byte[], int, int) method. * * @throws Exception should not happen */ @Test public void shouldReadAllReceivedData1() throws Exception { // create random data Random rand = new Random(); byte[] controlData = new byte[3 * blockSize]; rand.nextBytes(controlData); IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class); // set data packet acknowledgment and notify listener for (int i = 0; i < controlData.length / blockSize; i++) { protocol.addResponse(resultIQ); String base64Data = Base64.encodeToString(controlData, i * blockSize, blockSize); DataPacketExtension dpe = new DataPacketExtension(sessionID, i, base64Data); Data data = new Data(dpe); listener.processStanza(data); } byte[] bytes = new byte[3 * blockSize]; int read; read = inputStream.read(bytes, 0, blockSize); assertEquals(blockSize, read); read = inputStream.read(bytes, 10, blockSize); assertEquals(blockSize, read); read = inputStream.read(bytes, 20, blockSize); assertEquals(blockSize, read); // verify data for (int i = 0; i < bytes.length; i++) { assertEquals(controlData[i], bytes[i]); } protocol.verifyAll(); }
Example 17
Source File: OmemoBundleVAxolotlElementTest.java From Smack with Apache License 2.0 | 4 votes |
@Test public void serializationTest() throws Exception { int signedPreKeyId = 420; String signedPreKeyB64 = Base64.encodeToString("SignedPreKey".getBytes(StandardCharsets.UTF_8)); String signedPreKeySigB64 = Base64.encodeToString("SignedPreKeySignature".getBytes(StandardCharsets.UTF_8)); String identityKeyB64 = Base64.encodeToString("IdentityKey".getBytes(StandardCharsets.UTF_8)); int preKeyId1 = 220, preKeyId2 = 284; String preKey1B64 = Base64.encodeToString("FirstPreKey".getBytes(StandardCharsets.UTF_8)), preKey2B64 = Base64.encodeToString("SecondPreKey".getBytes(StandardCharsets.UTF_8)); HashMap<Integer, String> preKeysB64 = new HashMap<>(); preKeysB64.put(preKeyId1, preKey1B64); preKeysB64.put(preKeyId2, preKey2B64); OmemoBundleElement_VAxolotl bundle = new OmemoBundleElement_VAxolotl(signedPreKeyId, signedPreKeyB64, signedPreKeySigB64, identityKeyB64, preKeysB64); assertEquals("ElementName must match.", "bundle", bundle.getElementName()); assertEquals("Namespace must match.", "eu.siacs.conversations.axolotl", bundle.getNamespace()); String expected = "<bundle xmlns='eu.siacs.conversations.axolotl'>" + "<signedPreKeyPublic signedPreKeyId='420'>" + signedPreKeyB64 + "</signedPreKeyPublic>" + "<signedPreKeySignature>" + signedPreKeySigB64 + "</signedPreKeySignature>" + "<identityKey>" + identityKeyB64 + "</identityKey>" + "<prekeys>" + "<preKeyPublic preKeyId='220'>" + preKey1B64 + "</preKeyPublic>" + "<preKeyPublic preKeyId='284'>" + preKey2B64 + "</preKeyPublic>" + "</prekeys>" + "</bundle>"; String actual = bundle.toXML().toString(); assertEquals("Bundles XML must match.", expected, actual); byte[] signedPreKey = "SignedPreKey".getBytes(StandardCharsets.UTF_8); byte[] signedPreKeySig = "SignedPreKeySignature".getBytes(StandardCharsets.UTF_8); byte[] identityKey = "IdentityKey".getBytes(StandardCharsets.UTF_8); byte[] firstPreKey = "FirstPreKey".getBytes(StandardCharsets.UTF_8); byte[] secondPreKey = "SecondPreKey".getBytes(StandardCharsets.UTF_8); OmemoBundleElement_VAxolotl parsed = new OmemoBundleVAxolotlProvider().parse(TestUtils.getParser(actual)); assertTrue("B64-decoded signedPreKey must match.", Arrays.equals(signedPreKey, parsed.getSignedPreKey())); assertEquals("SignedPreKeyId must match", signedPreKeyId, parsed.getSignedPreKeyId()); assertTrue("B64-decoded signedPreKey signature must match.", Arrays.equals(signedPreKeySig, parsed.getSignedPreKeySignature())); assertTrue("B64-decoded identityKey must match.", Arrays.equals(identityKey, parsed.getIdentityKey())); assertTrue("B64-decoded first preKey must match.", Arrays.equals(firstPreKey, parsed.getPreKey(220))); assertTrue("B64-decoded second preKey must match.", Arrays.equals(secondPreKey, parsed.getPreKey(284))); assertEquals("toString outputs must match.", bundle.toString(), parsed.toString()); }
Example 18
Source File: OpenPgpManager.java From Smack with Apache License 2.0 | 2 votes |
/** * Create a {@link PubkeyElement} which contains the given {@code data} base64 encoded. * * @param bytes byte representation of an OpenPGP public key * @param date date of creation of the element * @return {@link PubkeyElement} containing the key */ private static PubkeyElement createPubkeyElement(byte[] bytes, Date date) { String base64EncodedOpenPgpPubKey = Base64.encodeToString(bytes); return new PubkeyElement(new PubkeyElement.PubkeyDataElement(base64EncodedOpenPgpPubKey), date); }