Java源码示例:org.whispersystems.libsignal.IdentityKeyPair
示例1
@Override
public void onRun() throws IOException {
if (TextSecurePreferences.isSignedPreKeyRegistered(context)) {
Log.w(TAG, "Signed prekey already registered...");
return;
}
if (!TextSecurePreferences.isPushRegistered(context)) {
Log.w(TAG, "Not yet registered...");
return;
}
SignalServiceAccountManager accountManager = ApplicationDependencies.getSignalServiceAccountManager();
IdentityKeyPair identityKeyPair = IdentityKeyUtil.getIdentityKeyPair(context);
SignedPreKeyRecord signedPreKeyRecord = PreKeyUtil.generateSignedPreKey(context, identityKeyPair, true);
accountManager.setSignedPreKey(signedPreKeyRecord);
TextSecurePreferences.setSignedPreKeyRegistered(context, true);
}
示例2
@Override
public void onRun() throws Exception {
Log.i(TAG, "Rotating signed prekey...");
SignalServiceAccountManager accountManager = ApplicationDependencies.getSignalServiceAccountManager();
IdentityKeyPair identityKey = IdentityKeyUtil.getIdentityKeyPair(context);
SignedPreKeyRecord signedPreKeyRecord = PreKeyUtil.generateSignedPreKey(context, identityKey, false);
accountManager.setSignedPreKey(signedPreKeyRecord);
PreKeyUtil.setActiveSignedPreKeyId(context, signedPreKeyRecord.getId());
TextSecurePreferences.setSignedPreKeyRegistered(context, true);
TextSecurePreferences.setSignedPreKeyFailureCount(context, 0);
ApplicationDependencies.getJobManager().add(new CleanPreKeysJob());
}
示例3
@Override
public void onRun(MasterSecret masterSecret) throws Exception {
Log.w(TAG, "Rotating signed prekey...");
if (AMELogin.INSTANCE.isLogin()) {
IdentityKeyPair identityKey = IdentityKeyUtil.getIdentityKeyPair(accountContext);
SignedPreKeyRecord signedPreKeyRecord = PreKeyUtil.generateSignedPreKey(context, accountContext, identityKey, false);
if (!AmeLoginCore.INSTANCE.refreshSignedPreKey(accountContext, signedPreKeyRecord)) {
throw new Exception("refreshSignedPreKey failed");
}
PreKeyUtil.setActiveSignedPreKeyId(context, accountContext, signedPreKeyRecord.getId());
accountContext.setSignedPreKeyRegistered(true);
accountContext.setSignedPreKeyFailureCount(0);
JobManager manager = AmeModuleCenter.INSTANCE.accountJobMgr(accountContext);
if (manager != null) {
manager.add(new CleanPreKeysJob(context, accountContext));
}
} else {
ALog.w(TAG, "please login first");
}
}
示例4
public static void migrateIdentityKeys(@NonNull AccountContext accountContext,
@NonNull MasterSecret masterSecret) {
if (!hasIdentityKey(accountContext)) {
if (hasLegacyIdentityKeys(accountContext)) {
IdentityKeyPair legacyPair = getLegacyIdentityKeyPair(accountContext, masterSecret);
save(accountContext, IDENTITY_PUBLIC_KEY_PREF, Base64.encodeBytes(legacyPair.getPublicKey().serialize()));
save(accountContext, IDENTITY_PRIVATE_KEY_PREF, Base64.encodeBytes(legacyPair.getPrivateKey().serialize()));
delete(accountContext, IDENTITY_PUBLIC_KEY_CIPHERTEXT_LEGACY_PREF);
delete(accountContext, IDENTITY_PRIVATE_KEY_CIPHERTEXT_LEGACY_PREF);
} else {
generateIdentityKeys(accountContext);
}
}
}
示例5
public static SignedPreKeyRecord generateSignedPreKey(Context context, AccountContext accountContext, IdentityKeyPair identityKeyPair, boolean active) {
try {
SignedPreKeyStore signedPreKeyStore = new TextSecurePreKeyStore(context, accountContext);
int signedPreKeyId = getNextSignedPreKeyId(context, accountContext);
ECKeyPair keyPair = Curve.generateKeyPair();
byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
SignedPreKeyRecord record = new SignedPreKeyRecord(signedPreKeyId, System.currentTimeMillis(), keyPair, signature);
signedPreKeyStore.storeSignedPreKey(signedPreKeyId, record);
setNextSignedPreKeyId(context, accountContext,(signedPreKeyId + 1) % Medium.MAX_VALUE);
if (active) {
setActiveSignedPreKeyId(context, accountContext, signedPreKeyId);
}
return record;
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
示例6
public static SignalAccount create(String dataPath, String username, IdentityKeyPair identityKey, int registrationId, ProfileKey profileKey) throws IOException {
IOUtils.createPrivateDirectories(dataPath);
String fileName = getFileName(dataPath, username);
if (!new File(fileName).exists()) {
IOUtils.createPrivateFile(fileName);
}
final Pair<FileChannel, FileLock> pair = openFileChannel(fileName);
SignalAccount account = new SignalAccount(pair.first(), pair.second());
account.username = username;
account.profileKey = profileKey;
account.signalProtocolStore = new JsonSignalProtocolStore(identityKey, registrationId);
account.groupStore = new JsonGroupStore();
account.contactStore = new JsonContactsStore();
account.recipientStore = new RecipientStore();
account.registered = false;
return account;
}
示例7
public static SignalAccount createLinkedAccount(String dataPath, String username, UUID uuid, String password, int deviceId, IdentityKeyPair identityKey, int registrationId, String signalingKey, ProfileKey profileKey) throws IOException {
IOUtils.createPrivateDirectories(dataPath);
String fileName = getFileName(dataPath, username);
if (!new File(fileName).exists()) {
IOUtils.createPrivateFile(fileName);
}
final Pair<FileChannel, FileLock> pair = openFileChannel(fileName);
SignalAccount account = new SignalAccount(pair.first(), pair.second());
account.username = username;
account.uuid = uuid;
account.password = password;
account.profileKey = profileKey;
account.deviceId = deviceId;
account.signalingKey = signalingKey;
account.signalProtocolStore = new JsonSignalProtocolStore(identityKey, registrationId);
account.groupStore = new JsonGroupStore();
account.contactStore = new JsonContactsStore();
account.recipientStore = new RecipientStore();
account.registered = true;
account.isMultiDevice = true;
return account;
}
示例8
/**
* Initiate a new session by sending an initial KeyExchangeMessage to the recipient.
*
* @return the KeyExchangeMessage to deliver.
*/
public KeyExchangeMessage process() {
synchronized (SessionCipher.SESSION_LOCK) {
try {
int sequence = KeyHelper.getRandomSequence(65534) + 1;
int flags = KeyExchangeMessage.INITIATE_FLAG;
ECKeyPair baseKey = Curve.generateKeyPair();
ECKeyPair ratchetKey = Curve.generateKeyPair();
IdentityKeyPair identityKey = identityKeyStore.getIdentityKeyPair();
byte[] baseKeySignature = Curve.calculateSignature(identityKey.getPrivateKey(), baseKey.getPublicKey().serialize());
SessionRecord sessionRecord = sessionStore.loadSession(remoteAddress);
sessionRecord.getSessionState().setPendingKeyExchange(sequence, baseKey, ratchetKey, identityKey);
sessionStore.storeSession(remoteAddress, sessionRecord);
return new KeyExchangeMessage(CiphertextMessage.CURRENT_VERSION,
sequence, flags, baseKey.getPublicKey(), baseKeySignature,
ratchetKey.getPublicKey(), identityKey.getPublicKey());
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
}
示例9
public static IdentityKeyPair getIdentityKeyPair(Context context,
MasterSecret masterSecret,
int subscriptionId)
{
if (!hasIdentityKey(context, subscriptionId))
return null;
try {
MasterCipher masterCipher = new MasterCipher(masterSecret);
IdentityKey publicKey = getIdentityKey(context, subscriptionId);
ECPrivateKey privateKey = masterCipher.decryptKey(Base64.decode(retrieve(context, getIdentityPrivateKeyDjbPref(subscriptionId))));
return new IdentityKeyPair(publicKey, privateKey);
} catch (IOException | InvalidKeyException e) {
throw new AssertionError(e);
}
}
示例10
public DeviceConsistencyMessage(DeviceConsistencyCommitment commitment, IdentityKeyPair identityKeyPair) {
try {
byte[] signatureBytes = Curve.calculateVrfSignature(identityKeyPair.getPrivateKey(), commitment.toByteArray());
byte[] vrfOutputBytes = Curve.verifyVrfSignature(identityKeyPair.getPublicKey().getPublicKey(), commitment.toByteArray(), signatureBytes);
this.generation = commitment.getGeneration();
this.signature = new DeviceConsistencySignature(signatureBytes, vrfOutputBytes);
this.serialized = SignalProtos.DeviceConsistencyCodeMessage.newBuilder()
.setGeneration(commitment.getGeneration())
.setSignature(ByteString.copyFrom(signature.getSignature()))
.build()
.toByteArray();
} catch (InvalidKeyException | VrfSignatureVerificationFailedException e) {
throw new AssertionError(e);
}
}
示例11
public void setPendingKeyExchange(int sequence,
ECKeyPair ourBaseKey,
ECKeyPair ourRatchetKey,
IdentityKeyPair ourIdentityKey)
{
PendingKeyExchange structure =
PendingKeyExchange.newBuilder()
.setSequence(sequence)
.setLocalBaseKey(ByteString.copyFrom(ourBaseKey.getPublicKey().serialize()))
.setLocalBaseKeyPrivate(ByteString.copyFrom(ourBaseKey.getPrivateKey().serialize()))
.setLocalRatchetKey(ByteString.copyFrom(ourRatchetKey.getPublicKey().serialize()))
.setLocalRatchetKeyPrivate(ByteString.copyFrom(ourRatchetKey.getPrivateKey().serialize()))
.setLocalIdentityKey(ByteString.copyFrom(ourIdentityKey.getPublicKey().serialize()))
.setLocalIdentityKeyPrivate(ByteString.copyFrom(ourIdentityKey.getPrivateKey().serialize()))
.build();
this.sessionStructure = this.sessionStructure.toBuilder()
.setPendingKeyExchange(structure)
.build();
}
示例12
BobSignalProtocolParameters(IdentityKeyPair ourIdentityKey, ECKeyPair ourSignedPreKey,
ECKeyPair ourRatchetKey, Optional<ECKeyPair> ourOneTimePreKey,
IdentityKey theirIdentityKey, ECPublicKey theirBaseKey)
{
this.ourIdentityKey = ourIdentityKey;
this.ourSignedPreKey = ourSignedPreKey;
this.ourRatchetKey = ourRatchetKey;
this.ourOneTimePreKey = ourOneTimePreKey;
this.theirIdentityKey = theirIdentityKey;
this.theirBaseKey = theirBaseKey;
if (ourIdentityKey == null || ourSignedPreKey == null || ourRatchetKey == null ||
ourOneTimePreKey == null || theirIdentityKey == null || theirBaseKey == null)
{
throw new IllegalArgumentException("Null value!");
}
}
示例13
private AliceSignalProtocolParameters(IdentityKeyPair ourIdentityKey, ECKeyPair ourBaseKey,
IdentityKey theirIdentityKey, ECPublicKey theirSignedPreKey,
ECPublicKey theirRatchetKey, Optional<ECPublicKey> theirOneTimePreKey)
{
this.ourIdentityKey = ourIdentityKey;
this.ourBaseKey = ourBaseKey;
this.theirIdentityKey = theirIdentityKey;
this.theirSignedPreKey = theirSignedPreKey;
this.theirRatchetKey = theirRatchetKey;
this.theirOneTimePreKey = theirOneTimePreKey;
if (ourIdentityKey == null || ourBaseKey == null || theirIdentityKey == null ||
theirSignedPreKey == null || theirRatchetKey == null || theirOneTimePreKey == null)
{
throw new IllegalArgumentException("Null values!");
}
}
示例14
public void addDevice(String deviceIdentifier,
ECPublicKey deviceKey,
IdentityKeyPair identityKeyPair,
Optional<byte[]> profileKey,
String code)
throws InvalidKeyException, IOException
{
ProvisioningCipher cipher = new ProvisioningCipher(deviceKey);
ProvisionMessage.Builder message = ProvisionMessage.newBuilder()
.setIdentityKeyPublic(ByteString.copyFrom(identityKeyPair.getPublicKey().serialize()))
.setIdentityKeyPrivate(ByteString.copyFrom(identityKeyPair.getPrivateKey().serialize()))
.setProvisioningCode(code)
.setProvisioningVersion(ProvisioningVersion.CURRENT_VALUE);
String e164 = credentials.getE164();
UUID uuid = credentials.getUuid();
if (e164 != null) {
message.setNumber(e164);
} else {
throw new AssertionError("Missing phone number!");
}
if (uuid != null) {
message.setUuid(uuid.toString());
} else {
Log.w(TAG, "[addDevice] Missing UUID.");
}
if (profileKey.isPresent()) {
message.setProfileKey(ByteString.copyFrom(profileKey.get()));
}
byte[] ciphertext = cipher.encrypt(message.build());
this.pushServiceSocket.sendProvisioningMessage(deviceIdentifier, ciphertext);
}
示例15
public static @NonNull IdentityKeyPair getIdentityKeyPair(@NonNull Context context) {
if (!hasIdentityKey(context)) throw new AssertionError("There isn't one!");
try {
IdentityKey publicKey = getIdentityKey(context);
ECPrivateKey privateKey = Curve.decodePrivatePoint(Base64.decode(retrieve(context, IDENTITY_PRIVATE_KEY_PREF)));
return new IdentityKeyPair(publicKey, privateKey);
} catch (IOException e) {
throw new AssertionError(e);
}
}
示例16
@Test
public void getFingerprintTest() {
IdentityKeyPair ikp = keyUtil.generateOmemoIdentityKeyPair();
IdentityKey ik = ikp.getPublicKey();
assertTrue("Length of fingerprint must be 64.",
keyUtil.getFingerprintOfIdentityKey(ik).length() == 64);
}
示例17
SignalOmemoRatchet(OmemoManager omemoManager,
OmemoStore<IdentityKeyPair, IdentityKey, PreKeyRecord, SignedPreKeyRecord,
SessionRecord, SignalProtocolAddress, ECPublicKey, PreKeyBundle,
SessionCipher> store) {
super(omemoManager, store);
this.storeConnector = new SignalOmemoStoreConnector(omemoManager, store);
}
示例18
@Override
public void onRun() throws IOException {
if (!TextSecurePreferences.isPushRegistered(context)) {
Log.w(TAG, "Not registered. Skipping.");
return;
}
SignalServiceAccountManager accountManager = ApplicationDependencies.getSignalServiceAccountManager();
int availableKeys = accountManager.getPreKeysCount();
Log.i(TAG, "Available keys: " + availableKeys);
if (availableKeys >= PREKEY_MINIMUM && TextSecurePreferences.isSignedPreKeyRegistered(context)) {
Log.i(TAG, "Available keys sufficient.");
SignalStore.setLastPrekeyRefreshTime(System.currentTimeMillis());
return;
}
List<PreKeyRecord> preKeyRecords = PreKeyUtil.generatePreKeys(context);
IdentityKeyPair identityKey = IdentityKeyUtil.getIdentityKeyPair(context);
SignedPreKeyRecord signedPreKeyRecord = PreKeyUtil.generateSignedPreKey(context, identityKey, false);
Log.i(TAG, "Registering new prekeys...");
accountManager.setPreKeys(identityKey.getPublicKey(), signedPreKeyRecord, preKeyRecords);
PreKeyUtil.setActiveSignedPreKeyId(context, signedPreKeyRecord.getId());
TextSecurePreferences.setSignedPreKeyRegistered(context, true);
ApplicationDependencies.getJobManager().add(new CleanPreKeysJob());
SignalStore.setLastPrekeyRefreshTime(System.currentTimeMillis());
Log.i(TAG, "Successfully refreshed prekeys.");
}
示例19
@Override
public void onRun(MasterSecret masterSecret) throws IOException {
if (accountContext.isSignedPreKeyRegistered()) {
Log.w(TAG, "Signed prekey already registered...");
return;
}
IdentityKeyPair identityKeyPair = IdentityKeyUtil.getIdentityKeyPair(accountContext);
SignedPreKeyRecord signedPreKeyRecord = PreKeyUtil.generateSignedPreKey(context, accountContext, identityKeyPair, true);
AmeLoginCore.INSTANCE.refreshSignedPreKey(accountContext, signedPreKeyRecord);
AmeModuleCenter.INSTANCE.login().setSignedPreKeyRegistered(accountContext.getUid(), true);
}
示例20
@Override
public void onRun(MasterSecret masterSecret) throws IOException {
int availableKeys = AmeLoginCore.INSTANCE.getAvailablePreKeys(accountContext);
if (availableKeys < 0) {
throw new IOException("fetch prekey params failed");
}
if (availableKeys >= PREKEY_MINIMUM && accountContext.isSignedPreKeyRegistered()) {
Log.w(TAG, "Available keys sufficient: " + availableKeys);
return;
}
List<PreKeyRecord> preKeyRecords = PreKeyUtil.generatePreKeys(context, accountContext);
IdentityKeyPair identityKey = IdentityKeyUtil.getIdentityKeyPair(accountContext);
SignedPreKeyRecord signedPreKeyRecord = PreKeyUtil.generateSignedPreKey(context, accountContext,identityKey, false);
Log.w(TAG, "Registering new prekeys...");
if (!AmeLoginCore.INSTANCE.refreshPreKeys(accountContext, identityKey.getPublicKey(), signedPreKeyRecord, preKeyRecords)) {
throw new IOException("upload prekey failed");
}
PreKeyUtil.setActiveSignedPreKeyId(context, accountContext, signedPreKeyRecord.getId());
accountContext.setSignedPreKeyRegistered(true);
JobManager jobManager = AmeModuleCenter.INSTANCE.accountJobMgr(accountContext);
if (jobManager != null) {
jobManager.add(new CleanPreKeysJob(context, accountContext));
}
}
示例21
public static @NonNull
IdentityKeyPair getIdentityKeyPair(@NonNull AccountContext accountContext) {
if (!hasIdentityKey(accountContext)) {
throw new IllegalStateException("There isn't one!");
}
try {
IdentityKey publicKey = getIdentityKey(accountContext);
ECPrivateKey privateKey = Curve.decodePrivatePoint(Base64.decode(retrieve(accountContext, IDENTITY_PRIVATE_KEY_PREF)));
return new IdentityKeyPair(publicKey, privateKey);
} catch (IOException e) {
throw new AssertionError(e);
}
}
示例22
private static IdentityKeyPair getLegacyIdentityKeyPair(@NonNull AccountContext accountContext,
@NonNull MasterSecret masterSecret) {
try {
MasterCipher masterCipher = new MasterCipher(masterSecret);
byte[] publicKeyBytes = Base64.decode(retrieve(accountContext, IDENTITY_PUBLIC_KEY_CIPHERTEXT_LEGACY_PREF));
IdentityKey identityKey = new IdentityKey(publicKeyBytes, 0);
ECPrivateKey privateKey = masterCipher.decryptKey(Base64.decode(retrieve(accountContext, IDENTITY_PRIVATE_KEY_CIPHERTEXT_LEGACY_PREF)));
return new IdentityKeyPair(identityKey, privateKey);
} catch (IOException | InvalidKeyException e) {
throw new AssertionError(e);
}
}
示例23
public void listen() throws IOException, InvalidKeyException {
String username = prefs.get("LOCAL_USERNAME", null);
String password = prefs.get("LOCAL_PASSWORD", null);
logger.info("Generating keys for " + username + "...");
IdentityKeyPair identityKeyPair = KeyHelper.generateIdentityKeyPair();
int registrationId = prefs.getInt("REGISTRATION_ID", -1);
this.protocolStore = new InMemorySignalProtocolStore(identityKeyPair, registrationId);
accountManager = new SignalServiceAccountManager(config, username, password, USER_AGENT);
refreshPreKeys(identityKeyPair);
logger.info("Starting message listener...");
messageRetrieverThread.start();
// TODO refresh keys job
}
示例24
private void refreshPreKeys(IdentityKeyPair identityKeyPair) throws IOException, InvalidKeyException {
int initialPreKeyId = new SecureRandom().nextInt(Medium.MAX_VALUE);
List<PreKeyRecord> records = KeyHelper.generatePreKeys(initialPreKeyId, BATCH_SIZE);
records.forEach((v) -> this.protocolStore.storePreKey(v.getId(), v));
int signedPreKeyId = new SecureRandom().nextInt(Medium.MAX_VALUE);
SignedPreKeyRecord signedPreKey = KeyHelper.generateSignedPreKey(identityKeyPair, signedPreKeyId);
this.protocolStore.storeSignedPreKey(signedPreKey.getId(), signedPreKey);
this.accountManager.setPreKeys(identityKeyPair.getPublicKey(), signedPreKey, records);
}
示例25
public void addDevice(String deviceIdentifier,
ECPublicKey deviceKey,
IdentityKeyPair identityKeyPair,
Optional<byte[]> profileKey,
String code)
throws InvalidKeyException, IOException
{
ProvisioningCipher cipher = new ProvisioningCipher(deviceKey);
ProvisionMessage.Builder message = ProvisionMessage.newBuilder()
.setIdentityKeyPublic(ByteString.copyFrom(identityKeyPair.getPublicKey().serialize()))
.setIdentityKeyPrivate(ByteString.copyFrom(identityKeyPair.getPrivateKey().serialize()))
.setProvisioningCode(code)
.setProvisioningVersion(ProvisioningVersion.CURRENT_VALUE);
if (userE164 != null) {
message.setNumber(userE164);
}
if (userUuid != null) {
message.setUuid(userUuid.toString());
}
if (profileKey.isPresent()) {
message.setProfileKey(ByteString.copyFrom(profileKey.get()));
}
byte[] ciphertext = cipher.encrypt(message.build());
this.pushServiceSocket.sendProvisioningMessage(deviceIdentifier, ciphertext);
}
示例26
private void addDevice(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
IdentityKeyPair identityKeyPair = getIdentityKeyPair();
String verificationCode = accountManager.getNewDeviceVerificationCode();
accountManager.addDevice(deviceIdentifier, deviceKey, identityKeyPair, Optional.of(account.getProfileKey().serialize()), verificationCode);
account.setMultiDevice(true);
account.save();
}
示例27
private SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair) {
try {
ECKeyPair keyPair = Curve.generateKeyPair();
byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
SignedPreKeyRecord record = new SignedPreKeyRecord(account.getNextSignedPreKeyId(), System.currentTimeMillis(), keyPair, signature);
account.addSignedPreKey(record);
account.save();
return record;
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
示例28
void refreshPreKeys() throws IOException {
List<PreKeyRecord> oneTimePreKeys = generatePreKeys();
final IdentityKeyPair identityKeyPair = getIdentityKeyPair();
SignedPreKeyRecord signedPreKeyRecord = generateSignedPreKey(identityKeyPair);
accountManager.setPreKeys(identityKeyPair.getPublicKey(), signedPreKeyRecord, oneTimePreKeys);
}
示例29
/**
* Get the local client's identity key pair.
*
* @return The local client's persistent identity key pair.
*/
@Override
public IdentityKeyPair getIdentityKeyPair() {
if (identityKeyPair == null) {
identityKeyPair = loadIdentityKeyPair();
}
return identityKeyPair;
}
示例30
private IdentityKeyPair loadIdentityKeyPair() {
synchronized (mXmppConnectionService) {
IdentityKeyPair ownKey = mXmppConnectionService.databaseBackend.loadOwnIdentityKeyPair(account);
if (ownKey != null) {
return ownKey;
} else {
Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Could not retrieve own IdentityKeyPair");
ownKey = generateIdentityKeyPair();
mXmppConnectionService.databaseBackend.storeOwnIdentityKeyPair(account, ownKey);
}
return ownKey;
}
}