Java Code Examples for org.whispersystems.libsignal.util.ByteUtil#combine()

The following examples show how to use org.whispersystems.libsignal.util.ByteUtil#combine() . 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: ProfileCipher.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public byte[] encryptName(byte[] input, int paddedLength) {
  try {
    byte[] inputPadded = new byte[paddedLength];

    if (input.length > inputPadded.length) {
      throw new IllegalArgumentException("Input is too long: " + new String(input));
    }

    System.arraycopy(input, 0, inputPadded, 0, input.length);

    byte[] nonce = Util.getSecretBytes(12);

    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.serialize(), "AES"), new GCMParameterSpec(128, nonce));

    return ByteUtil.combine(nonce, cipher.doFinal(inputPadded));
  } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | BadPaddingException | NoSuchPaddingException | IllegalBlockSizeException | InvalidKeyException e) {
    throw new AssertionError(e);
  }
}
 
Example 2
Source File: ProfileCipher.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
public byte[] encryptName(byte[] input, int paddedLength) {
    try {
        byte[] inputPadded = new byte[paddedLength];

        if (input.length > inputPadded.length) {
            throw new IllegalArgumentException("Input is too long: " + new String(input));
        }

        System.arraycopy(input, 0, inputPadded, 0, input.length);

        byte[] nonce = Util.getSecretBytes(12);

        GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
        cipher.init(true, new AEADParameters(new KeyParameter(key), 128, nonce));

        byte[] ciphertext = new byte[cipher.getUpdateOutputSize(inputPadded.length)];
        cipher.processBytes(inputPadded, 0, inputPadded.length, ciphertext, 0);

        byte[] tag = new byte[cipher.getOutputSize(0)];
        cipher.doFinal(tag, 0);

        return ByteUtil.combine(nonce, ciphertext, tag);
    } catch (InvalidCipherTextException e) {
        throw new AssertionError(e);
    }
}
 
Example 3
Source File: ProfileCipher.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public byte[] encryptName(byte[] input, int paddedLength) {
  try {
    byte[] inputPadded = new byte[paddedLength];

    if (input.length > inputPadded.length) {
      throw new IllegalArgumentException("Input is too long: " + new String(input));
    }

    System.arraycopy(input, 0, inputPadded, 0, input.length);

    byte[] nonce = Util.getSecretBytes(12);

    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, nonce));

    return ByteUtil.combine(nonce, cipher.doFinal(inputPadded));
  } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | BadPaddingException | NoSuchPaddingException | IllegalBlockSizeException | InvalidKeyException e) {
    throw new AssertionError(e);
  }
}
 
Example 4
Source File: NumericFingerprintGenerator.java    From libsignal-protocol-java with GNU General Public License v3.0 6 votes vote down vote up
private byte[] getFingerprint(int iterations, byte[] stableIdentifier, List<IdentityKey> unsortedIdentityKeys) {
  try {
    MessageDigest digest    = MessageDigest.getInstance("SHA-512");
    byte[]        publicKey = getLogicalKeyBytes(unsortedIdentityKeys);
    byte[]        hash      = ByteUtil.combine(ByteUtil.shortToByteArray(FINGERPRINT_VERSION),
                                               publicKey, stableIdentifier);

    for (int i=0;i<iterations;i++) {
      digest.update(hash);
      hash = digest.digest(publicKey);
    }

    return hash;
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example 5
Source File: SenderKeyMessage.java    From libsignal-protocol-java with GNU General Public License v3.0 6 votes vote down vote up
public SenderKeyMessage(int keyId, int iteration, byte[] ciphertext, ECPrivateKey signatureKey) {
  byte[] version = {ByteUtil.intsToByteHighAndLow(CURRENT_VERSION, CURRENT_VERSION)};
  byte[] message = SignalProtos.SenderKeyMessage.newBuilder()
                                                .setId(keyId)
                                                .setIteration(iteration)
                                                .setCiphertext(ByteString.copyFrom(ciphertext))
                                                .build().toByteArray();

  byte[] signature = getSignature(signatureKey, ByteUtil.combine(version, message));

  this.serialized       = ByteUtil.combine(version, message, signature);
  this.messageVersion   = CURRENT_VERSION;
  this.keyId            = keyId;
  this.iteration        = iteration;
  this.ciphertext       = ciphertext;
}
 
Example 6
Source File: SignalMessage.java    From libsignal-protocol-java with GNU General Public License v3.0 6 votes vote down vote up
public SignalMessage(int messageVersion, SecretKeySpec macKey, ECPublicKey senderRatchetKey,
                     int counter, int previousCounter, byte[] ciphertext,
                     IdentityKey senderIdentityKey,
                     IdentityKey receiverIdentityKey)
{
  byte[] version = {ByteUtil.intsToByteHighAndLow(messageVersion, CURRENT_VERSION)};
  byte[] message = SignalProtos.SignalMessage.newBuilder()
                                             .setRatchetKey(ByteString.copyFrom(senderRatchetKey.serialize()))
                                             .setCounter(counter)
                                             .setPreviousCounter(previousCounter)
                                             .setCiphertext(ByteString.copyFrom(ciphertext))
                                             .build().toByteArray();

  byte[] mac     = getMac(senderIdentityKey, receiverIdentityKey, macKey, ByteUtil.combine(version, message));

  this.serialized       = ByteUtil.combine(version, message, mac);
  this.senderRatchetKey = senderRatchetKey;
  this.counter          = counter;
  this.previousCounter  = previousCounter;
  this.ciphertext       = ciphertext;
  this.messageVersion   = messageVersion;
}
 
Example 7
Source File: RemoteAttestationKeys.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public RemoteAttestationKeys(Curve25519KeyPair keyPair, byte[] serverPublicEphemeral, byte[] serverPublicStatic) {
  byte[] ephemeralToEphemeral = Curve25519.getInstance(Curve25519.BEST).calculateAgreement(serverPublicEphemeral, keyPair.getPrivateKey());
  byte[] ephemeralToStatic    = Curve25519.getInstance(Curve25519.BEST).calculateAgreement(serverPublicStatic, keyPair.getPrivateKey());

  byte[] masterSecret = ByteUtil.combine(ephemeralToEphemeral, ephemeralToStatic                          );
  byte[] publicKeys   = ByteUtil.combine(keyPair.getPublicKey(), serverPublicEphemeral, serverPublicStatic);

  HKDFv3 generator = new HKDFv3();
  byte[] keys      = generator.deriveSecrets(masterSecret, publicKeys, null, clientKey.length + serverKey.length);

  System.arraycopy(keys, 0, clientKey, 0, clientKey.length);
  System.arraycopy(keys, clientKey.length, serverKey, 0, serverKey.length);
}
 
Example 8
Source File: ProfileCipher.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public byte[] decryptName(byte[] input) throws InvalidCiphertextException {
    try {
        if (input.length < 12 + 16 + 1) {
            throw new InvalidCiphertextException("Too short: " + input.length);
        }

        byte[] nonce = new byte[12];
        System.arraycopy(input, 0, nonce, 0, nonce.length);

        GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
        cipher.init(false, new AEADParameters(new KeyParameter(key), 128, nonce));

        byte[] paddedPlaintextOne = new byte[cipher.getUpdateOutputSize(input.length - 12)];
        cipher.processBytes(input, 12, input.length - 12, paddedPlaintextOne, 0);

        byte[] paddedPlaintextTwo = new byte[cipher.getOutputSize(0)];
        cipher.doFinal(paddedPlaintextTwo, 0);

        byte[] paddedPlaintext = ByteUtil.combine(paddedPlaintextOne, paddedPlaintextTwo);
        int plaintextLength = 0;

        for (int i = paddedPlaintext.length - 1; i >= 0; i--) {
            if (paddedPlaintext[i] != (byte) 0x00) {
                plaintextLength = i + 1;
                break;
            }
        }

        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(paddedPlaintext, 0, plaintext, 0, plaintextLength);

        return plaintext;
    } catch (InvalidCipherTextException e) {
        throw new InvalidCiphertextException(e);
    }
}
 
Example 9
Source File: IdentityKeyUtil.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public static ECKeyPair rebuildIdentityKeys(@NonNull AccountContext accountContext, byte[] privateKeyBytes) throws Exception {

        ECPrivateKey ecPrivateKey = Curve.decodePrivatePoint(privateKeyBytes);
        byte[] publicKeyBytes = ByteUtil.combine(new byte[]{Curve.DJB_TYPE}, BCMPrivateKeyUtils.INSTANCE.generatePublicKey(ecPrivateKey.serialize()));
        save(accountContext, IDENTITY_PUBLIC_KEY_PREF, Base64.encodeBytes(publicKeyBytes));
        save(accountContext, IDENTITY_PRIVATE_KEY_PREF, Base64.encodeBytes(ecPrivateKey.serialize()));

        return new ECKeyPair(Curve.decodePoint(publicKeyBytes, 0), ecPrivateKey);
    }
 
Example 10
Source File: RemoteAttestationKeys.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public RemoteAttestationKeys(Curve25519KeyPair keyPair, byte[] serverPublicEphemeral, byte[] serverPublicStatic) {
  byte[] ephemeralToEphemeral = Curve25519.getInstance(Curve25519.BEST).calculateAgreement(serverPublicEphemeral, keyPair.getPrivateKey());
  byte[] ephemeralToStatic    = Curve25519.getInstance(Curve25519.BEST).calculateAgreement(serverPublicStatic, keyPair.getPrivateKey());

  byte[] masterSecret = ByteUtil.combine(ephemeralToEphemeral, ephemeralToStatic                          );
  byte[] publicKeys   = ByteUtil.combine(keyPair.getPublicKey(), serverPublicEphemeral, serverPublicStatic);

  HKDFv3 generator = new HKDFv3();
  byte[] keys      = generator.deriveSecrets(masterSecret, publicKeys, null, clientKey.length + serverKey.length);

  System.arraycopy(keys, 0, clientKey, 0, clientKey.length);
  System.arraycopy(keys, clientKey.length, serverKey, 0, serverKey.length);
}
 
Example 11
Source File: SenderKeyDistributionMessage.java    From libsignal-protocol-java with GNU General Public License v3.0 5 votes vote down vote up
public SenderKeyDistributionMessage(int id, int iteration, byte[] chainKey, ECPublicKey signatureKey) {
  byte[] version = {ByteUtil.intsToByteHighAndLow(CURRENT_VERSION, CURRENT_VERSION)};
  byte[] protobuf = SignalProtos.SenderKeyDistributionMessage.newBuilder()
                                                             .setId(id)
                                                             .setIteration(iteration)
                                                             .setChainKey(ByteString.copyFrom(chainKey))
                                                             .setSigningKey(ByteString.copyFrom(signatureKey.serialize()))
                                                             .build().toByteArray();

  this.id           = id;
  this.iteration    = iteration;
  this.chainKey     = chainKey;
  this.signatureKey = signatureKey;
  this.serialized   = ByteUtil.combine(version, protobuf);
}
 
Example 12
Source File: PreKeySignalMessage.java    From libsignal-protocol-java with GNU General Public License v3.0 5 votes vote down vote up
public PreKeySignalMessage(int messageVersion, int registrationId, Optional<Integer> preKeyId,
                           int signedPreKeyId, ECPublicKey baseKey, IdentityKey identityKey,
                           SignalMessage message)
{
  this.version        = messageVersion;
  this.registrationId = registrationId;
  this.preKeyId       = preKeyId;
  this.signedPreKeyId = signedPreKeyId;
  this.baseKey        = baseKey;
  this.identityKey    = identityKey;
  this.message        = message;

  SignalProtos.PreKeySignalMessage.Builder builder =
      SignalProtos.PreKeySignalMessage.newBuilder()
                                      .setSignedPreKeyId(signedPreKeyId)
                                      .setBaseKey(ByteString.copyFrom(baseKey.serialize()))
                                      .setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
                                      .setMessage(ByteString.copyFrom(message.serialize()))
                                      .setRegistrationId(registrationId);

  if (preKeyId.isPresent()) {
    builder.setPreKeyId(preKeyId.get());
  }

  byte[] versionBytes = {ByteUtil.intsToByteHighAndLow(this.version, CURRENT_VERSION)};
  byte[] messageBytes = builder.build().toByteArray();

  this.serialized = ByteUtil.combine(versionBytes, messageBytes);
}
 
Example 13
Source File: TestHelpers.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
public static byte[] byteArray(int a, int totalLength) {
  byte[] out = new byte[totalLength - 4];
  byte[] val = Conversions.intToByteArray(a);
  return ByteUtil.combine(out, val);
}
 
Example 14
Source File: DjbECPublicKey.java    From libsignal-protocol-java with GNU General Public License v3.0 4 votes vote down vote up
@Override
public byte[] serialize() {
  byte[] type = {Curve.DJB_TYPE};
  return ByteUtil.combine(type, publicKey);
}