org.jivesoftware.smack.util.stringencoder.Base64 Java Examples

The following examples show how to use org.jivesoftware.smack.util.stringencoder.Base64. 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: InBandBytestreamSessionTest.java    From Smack with Apache License 2.0 7 votes vote down vote up
/**
 * Valid data packets should be confirmed.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldConfirmReceivedDataPacket() throws Exception {
    // verify data packet confirmation is of type RESULT
    protocol.addResponse(null, Verification.requestTypeRESULT);

    InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
                    initiatorJID);
    InputStream inputStream = session.getInputStream();
    StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class);

    String base64Data = Base64.encode("Data");
    DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data);
    Data data = new Data(dpe);

    listener.processStanza(data);

    protocol.verifyAll();

}
 
Example #2
Source File: XMPPSession.java    From mangosta-android with Apache License 2.0 6 votes vote down vote up
/**
 * This method is not necessary on this app, is only to show how BoB could be used
 */
private void sendResponse(BoBIQ bobIQ) {
    BoBHash bobHash = bobIQ.getBoBHash();

    Resources resources = MangostaApplication.getInstance().getResources();
    final int resourceId = resources.getIdentifier("sticker_" + Base64.decodeToString(bobHash.getHash()), "drawable",
            MangostaApplication.getInstance().getPackageName());
    Drawable drawable = resources.getDrawable(resourceId);

    Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.WEBP, 100, stream);
    byte[] bitMapData = stream.toByteArray();

    try {
        BoBData bobData = new BoBData(0, "image/png", bitMapData);
        getBoBManager().responseBoB(bobIQ, bobData);
    } catch (InterruptedException | SmackException.NotConnectedException | SmackException.NotLoggedInException e) {
        e.printStackTrace();
    }
}
 
Example #3
Source File: DataTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnValidIQStanzaXML() throws Exception {
    String encodedData = Base64.encode("Test");

    String control = XMLBuilder.create("iq")
        .a("from", "[email protected]/orchard")
        .a("to", "[email protected]/balcony")
        .a("id", "kr91n475")
        .a("type", "set")
        .e("data")
            .a("xmlns", "http://jabber.org/protocol/ibb")
            .a("seq", "0")
            .a("sid", "i781hf64")
            .t(encodedData)
        .asString(outputProperties);

    DataPacketExtension dpe = new DataPacketExtension("i781hf64", 0, encodedData);
    Data data = new Data(dpe);
    data.setFrom(JidCreate.from("[email protected]/orchard"));
    data.setTo(JidCreate.from("[email protected]/balcony"));
    data.setStanzaId("kr91n475");

    assertXmlSimilar(control, data.toXML(StreamOpen.CLIENT_NAMESPACE).toString());
}
 
Example #4
Source File: PainlessOpenPgpProvider.java    From Smack with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: SASLMechanism.java    From Smack with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: SASLMechanism.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #7
Source File: SCRAMSHA1MechanismTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void testScramSha1Mechanism() throws NotConnectedException, SmackException, InterruptedException {
    final DummyConnection con = new DummyConnection();
    SCRAMSHA1Mechanism mech = new SCRAMSHA1Mechanism() {
        @Override
        public String getRandomAscii() {
            this.connection = con;
            return "fyko+d2lbbFgONRv9qkxdawL";
        }
    };

    mech.authenticate(USERNAME, "unusedFoo", JidTestUtil.DOMAIN_BARE_JID_1, PASSWORD, null, null);
    AuthMechanism authMechanism = con.getSentPacket();
    assertEquals(SCRAMSHA1Mechanism.NAME, authMechanism.getMechanism());
    assertEquals(CLIENT_FIRST_MESSAGE, saslLayerString(authMechanism.getAuthenticationText()));

    mech.challengeReceived(Base64.encode(SERVER_FIRST_MESSAGE), false);
    Response response = con.getSentPacket();
    assertEquals(CLIENT_FINAL_MESSAGE, saslLayerString(response.getAuthenticationText()));

    mech.challengeReceived(Base64.encode(SERVER_FINAL_MESSAGE), true);
    mech.checkIfSuccessfulOrThrow();
}
 
Example #8
Source File: DataPacketExtension.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the decoded data or null if data could not be decoded.
 * <p>
 * The encoded data is invalid if it contains bad Base64 input characters or
 * if it contains the pad ('=') character on a position other than the last
 * character(s) of the data. See <a
 * href="http://xmpp.org/extensions/xep-0047.html#sec">XEP-0047</a> Section
 * 6.
 *
 * @return the decoded data
 */
public byte[] getDecodedData() {
    // return cached decoded data
    if (this.decodedData != null) {
        return this.decodedData;
    }

    // data must not contain the pad (=) other than end of data
    if (data.matches(".*={1,2}+.+")) {
        return null;
    }

    // decodeBase64 will return null if bad characters are included
    this.decodedData = Base64.decode(data);
    return this.decodedData;
}
 
Example #9
Source File: XMPPSession.java    From mangosta-android with Apache License 2.0 6 votes vote down vote up
private void manageMessageAlreadyExists(Message message, Date delayDate, String messageId) {
    Realm realm = RealmManager.getInstance().getRealm();
    realm.beginTransaction();

    ChatMessage chatMessage = realm.where(ChatMessage.class).equalTo("messageId", messageId).findFirst();
    chatMessage.setStatus(ChatMessage.STATUS_SENT);

    if (isBoBMessage(message)) {
        BoBExtension bobExtension = BoBExtension.from(message);
        chatMessage.setContent(Base64.decodeToString(bobExtension.getBoBHash().getHash()));
    } else {
        chatMessage.setContent(message.getBody());
    }

    if (delayDate != null) {
        chatMessage.setDate(delayDate);
    }

    realm.copyToRealmOrUpdate(chatMessage);
    realm.commitTransaction();
    realm.close();
}
 
Example #10
Source File: InBandBytestreamSessionMessageTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * If a data stanza is received out of order the session should be closed. See XEP-0047 Section
 * 2.2.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldSendCloseRequestIfInvalidSequenceReceived() throws Exception {
    // confirm close request
    IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
    protocol.addResponse(resultIQ, Verification.requestTypeSET,
                    Verification.correspondingSenderReceiver);

    // 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);

    // build invalid packet with out of order sequence
    String base64Data = Base64.encode("Data");
    DataPacketExtension dpe = new DataPacketExtension(sessionID, 123, base64Data);
    Message dataMessage = StanzaBuilder.buildMessage()
            .addExtension(dpe)
            .build();

    // add data packets
    listener.processStanza(dataMessage);

    // read until exception is thrown
    try {
        inputStream.read();
        fail("exception should be thrown");
    }
    catch (IOException e) {
        assertTrue(e.getMessage().contains("Packets out of sequence"));
    }

    protocol.verifyAll();

}
 
Example #11
Source File: AndroidSmackInitializer.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public List<Exception> initialize() {
    SmackConfiguration.setDefaultHostnameVerifier(new StrictHostnameVerifier());
    Base64.setEncoder(AndroidBase64Encoder.getInstance());
    Base64UrlSafeEncoder.setEncoder(AndroidBase64UrlSafeEncoder.getInstance());
    return null;
}
 
Example #12
Source File: InBandBytestreamSession.java    From Smack with Apache License 2.0 5 votes vote down vote up
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 #13
Source File: SecretKeyBackupHelper.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Decrypt a secret key backup and return the {@link PGPSecretKeyRing} contained in it.
 * TODO: Return a PGPSecretKeyRingCollection instead?
 *
 * @param backup encrypted {@link SecretkeyElement} containing the backup
 * @param backupCode passphrase for decrypting the {@link SecretkeyElement}.
 * @return the TODO javadoc me please
 * @throws InvalidBackupCodeException in case the provided backup code is invalid.
 * @throws IOException IO is dangerous.
 * @throws PGPException PGP is brittle.
 */
public static PGPSecretKeyRing restoreSecretKeyBackup(SecretkeyElement backup, String backupCode)
        throws InvalidBackupCodeException, IOException, PGPException {
    byte[] encrypted = Base64.decode(backup.getB64Data());

    byte[] decrypted;
    try {
        decrypted = PGPainless.decryptWithPassword(encrypted, new Passphrase(backupCode.toCharArray()));
    } catch (IOException | PGPException e) {
        throw new InvalidBackupCodeException("Could not decrypt secret key backup. Possibly wrong passphrase?", e);
    }

    return PGPainless.readKeyRing().secretKeyRing(decrypted);
}
 
Example #14
Source File: InBandBytestreamSessionMessageTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #15
Source File: PainlessOpenPgpProvider.java    From Smack with Apache License 2.0 5 votes vote down vote up
@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 #16
Source File: VCard.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #17
Source File: PainlessOpenPgpProvider.java    From Smack with Apache License 2.0 5 votes vote down vote up
@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 #18
Source File: BoBData.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #19
Source File: InBandBytestreamSessionTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * If the input stream is closed the output stream should not be closed as well.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldNotCloseBothStreamsIfOutputStreamIsClosed() throws Exception {

    InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
                    initiatorJID);
    OutputStream outputStream = session.getOutputStream();
    outputStream.close();

    // verify data packet confirmation is of type RESULT
    protocol.addResponse(null, Verification.requestTypeRESULT);

    // insert data to read
    InputStream inputStream = session.getInputStream();
    StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class);
    String base64Data = Base64.encode("Data");
    DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data);
    Data data = new Data(dpe);
    listener.processStanza(data);

    // verify no packet send
    protocol.verifyAll();

    try {
        outputStream.flush();
        fail("should throw an exception");
    }
    catch (IOException e) {
        assertTrue(e.getMessage().contains("closed"));
    }

    assertTrue(inputStream.read() != 0);

}
 
Example #20
Source File: DnsIq.java    From Smack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("ByteBufferBackingArray")
public String getDnsMessageBase64Encoded() {
    if (base64DnsMessage == null) {
        ByteBuffer byteBuffer = dnsMessage.getInByteBuffer();
        byte[] bytes = byteBuffer.array();
        base64DnsMessage = Base64.encodeToStringWithoutPadding(bytes);
    }
    return base64DnsMessage;
}
 
Example #21
Source File: InBandBytestreamSessionTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * If the data stanza has a sequence that is already used an 'unexpected-request' error should
 * be returned. See XEP-0047 Section 2.2.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldReplyWithErrorIfAlreadyUsedSequenceIsReceived() throws Exception {
    // verify reply to first valid data packet is of type RESULT
    protocol.addResponse(null, Verification.requestTypeRESULT);

    // verify reply to invalid data packet is an error
    protocol.addResponse(null, Verification.requestTypeERROR, new Verification<IQ, IQ>() {

        @Override
        public void verify(IQ request, IQ response) {
            assertEquals(StanzaError.Condition.unexpected_request,
                            request.getError().getCondition());
        }

    });

    // 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);

    // build data packets
    String base64Data = Base64.encode("Data");
    DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data);
    Data data1 = new Data(dpe);
    Data data2 = new Data(dpe);

    // notify listener
    listener.processStanza(data1);
    listener.processStanza(data2);

    protocol.verifyAll();

}
 
Example #22
Source File: InBandBytestreamSessionTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * If a data stanza is received out of order the session should be closed. See XEP-0047 Section
 * 2.2.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldSendCloseRequestIfInvalidSequenceReceived() throws Exception {
    IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);

    // confirm data packet with invalid sequence
    protocol.addResponse(resultIQ);

    // confirm close request
    protocol.addResponse(resultIQ, Verification.requestTypeSET,
                    Verification.correspondingSenderReceiver);

    // 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);

    // build invalid packet with out of order sequence
    String base64Data = Base64.encode("Data");
    DataPacketExtension dpe = new DataPacketExtension(sessionID, 123, base64Data);
    Data data = new Data(dpe);

    // add data packets
    listener.processStanza(data);

    // read until exception is thrown
    try {
        inputStream.read();
        fail("exception should be thrown");
    }
    catch (IOException e) {
        assertTrue(e.getMessage().contains("Packets out of sequence"));
    }

    protocol.verifyAll();

}
 
Example #23
Source File: OmemoVAxolotlElementTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@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 #24
Source File: Java7SmackInitializer.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public List<Exception> initialize() {
    if (SystemUtil.onAndroid()) {
        // @formatter:off
        throw new RuntimeException(
                        "You need to remove the smack-java7 dependency/jar from your build, " +
                        "as it does not run on Android. " +
                        "Use smack-android instead.");
        // @formatter:on
    }
    SmackConfiguration.setDefaultHostnameVerifier(new XmppHostnameVerifier());
    Base64.setEncoder(Java7Base64Encoder.getInstance());
    Base64UrlSafeEncoder.setEncoder(Java7Base64UrlSafeEncoder.getInstance());
    return null;
}
 
Example #25
Source File: InBandBytestreamSessionTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #26
Source File: OmemoBundleElement.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Return the HashMap of preKeys in the bundle.
 * The map uses the preKeys ids as key and the preKeys as value.
 *
 * @return preKeys Pre-Keys contained in the bundle
 */
public HashMap<Integer, byte[]> getPreKeys() {
    if (preKeys == null) {
        preKeys = new HashMap<>();
        for (int id : preKeysB64.keySet()) {
            preKeys.put(id, Base64.decode(preKeysB64.get(id)));
        }
    }
    return this.preKeys;
}
 
Example #27
Source File: InBandBytestreamSessionTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * If the output stream is closed the input stream should not be closed as well.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldNotCloseBothStreamsIfInputStreamIsClosed() throws Exception {
    // acknowledgment for data packet
    IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
    protocol.addResponse(resultIQ);

    // 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);

    // build data packet
    String base64Data = Base64.encode("Data");
    DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data);
    Data data = new Data(dpe);

    // add data packets
    listener.processStanza(data);

    inputStream.close();

    protocol.verifyAll();

    try {
        while (inputStream.read() != -1) {
        }
        inputStream.read();
        fail("should throw an exception");
    }
    catch (IOException e) {
        assertTrue(e.getMessage().contains("closed"));
    }

    session.getOutputStream().flush();

}
 
Example #28
Source File: OmemoBundleElement.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Get the signature of the signedPreKey.
 *
 * @return signature as byte array
 */
public byte[] getSignedPreKeySignature() {
    if (signedPreKeySignature == null) {
        signedPreKeySignature = Base64.decode(signedPreKeySignatureB64);
    }
    return signedPreKeySignature.clone();
}
 
Example #29
Source File: OmemoKeyElement.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public XmlStringBuilder toXML(XmlEnvironment enclosingXmlEnvironment) {
    XmlStringBuilder sb = new XmlStringBuilder(this, enclosingXmlEnvironment);

    if (isPreKey()) {
        sb.attribute(ATTR_PREKEY, true);
    }

    sb.attribute(ATTR_RID, getId());
    sb.rightAngleBracket();
    sb.append(Base64.encodeToString(getData()));
    sb.closeElement(this);
    return sb;
}
 
Example #30
Source File: OmemoBundleElement.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Return the signedPreKey of the OmemoBundleElement.
 *
 * @return signedPreKey as byte array
 */
public byte[] getSignedPreKey() {
    if (signedPreKey == null) {
        signedPreKey = Base64.decode(signedPreKeyB64);
    }
    return this.signedPreKey.clone();
}