mirror of
https://github.com/oxen-io/session-android.git
synced 2024-11-21 15:05:19 +00:00
session-android-service is merged under the "service" module.
This commit is contained in:
parent
9052431bf8
commit
1c5e62a2de
10
build.gradle
10
build.gradle
@ -7,9 +7,9 @@ buildscript {
|
||||
}
|
||||
dependencies {
|
||||
classpath "com.android.tools.build:gradle:4.0.1"
|
||||
classpath files('libs/gradle-witness.jar')
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
|
||||
classpath "com.google.gms:google-services:4.3.3"
|
||||
classpath files('libs/gradle-witness.jar')
|
||||
}
|
||||
}
|
||||
|
||||
@ -56,4 +56,10 @@ allprojects {
|
||||
jcenter()
|
||||
maven { url "https://jitpack.io" }
|
||||
}
|
||||
|
||||
project.ext {
|
||||
androidBuildToolsVersion = '29.0.3'
|
||||
androidCompileSdkVersion = 29
|
||||
androidMinSdkVersion = 21
|
||||
}
|
||||
}
|
@ -2,5 +2,9 @@ android.useAndroidX=true
|
||||
android.enableJetifier=true
|
||||
org.gradle.jvmargs=-Xmx2048m
|
||||
|
||||
kotlin_version=1.4.0
|
||||
kovenant_version=3.3.0
|
||||
kotlinVersion=1.4.0
|
||||
kovenantVersion=3.3.0
|
||||
curve25519Version=0.5.0
|
||||
protobufVersion=2.5.0
|
||||
okhttpVersion=3.12.1
|
||||
jacksonDatabindVersion=2.9.8
|
@ -93,18 +93,18 @@ dependencies {
|
||||
}
|
||||
// Loki
|
||||
// Local:
|
||||
implementation "org.whispersystems:signal-service-android:2.13.2" // Run ./gradlew install from session-android-service to install
|
||||
implementation "org.whispersystems:curve25519-java:0.5.0"
|
||||
implementation project(":service:android")
|
||||
// Remote:
|
||||
implementation "org.whispersystems:curve25519-java:$curve25519Version"
|
||||
implementation "com.goterl.lazycode:lazysodium-android:4.2.0@aar"
|
||||
implementation "net.java.dev.jna:jna:5.5.0@aar"
|
||||
implementation "com.google.protobuf:protobuf-java:2.5.0"
|
||||
implementation "com.fasterxml.jackson.core:jackson-databind:2.9.8"
|
||||
implementation "com.squareup.okhttp3:okhttp:3.12.1"
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
|
||||
implementation "com.google.protobuf:protobuf-java:$protobufVersion"
|
||||
implementation "com.fasterxml.jackson.core:jackson-databind:$jacksonDatabindVersion"
|
||||
implementation "com.squareup.okhttp3:okhttp:$okhttpVersion"
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion"
|
||||
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'
|
||||
implementation "nl.komponents.kovenant:kovenant:$kovenant_version"
|
||||
implementation "nl.komponents.kovenant:kovenant-android:$kovenant_version"
|
||||
implementation "nl.komponents.kovenant:kovenant:$kovenantVersion"
|
||||
implementation "nl.komponents.kovenant:kovenant-android:$kovenantVersion"
|
||||
implementation "com.github.lelloman:android-identicons:v11"
|
||||
implementation "com.prof.rssparser:rssparser:2.0.4"
|
||||
implementation "com.jakewharton.rxbinding3:rxbinding:3.1.0"
|
||||
@ -147,8 +147,8 @@ def abiPostFix = ['armeabi-v7a' : 1,
|
||||
|
||||
android {
|
||||
flavorDimensions "none"
|
||||
compileSdkVersion 29
|
||||
buildToolsVersion '29.0.3'
|
||||
compileSdkVersion androidCompileSdkVersion
|
||||
buildToolsVersion androidBuildToolsVersion
|
||||
useLibrary 'org.apache.http.legacy'
|
||||
|
||||
dexOptions {
|
||||
@ -159,8 +159,9 @@ android {
|
||||
versionCode canonicalVersionCode * postFixSize
|
||||
versionName canonicalVersionName
|
||||
|
||||
minSdkVersion 21
|
||||
targetSdkVersion 29
|
||||
minSdkVersion androidMinSdkVersion
|
||||
targetSdkVersion androidCompileSdkVersion
|
||||
|
||||
multiDexEnabled true // Even though we're running API 21+, this is still needed for release builds
|
||||
|
||||
vectorDrawables.useSupportLibrary = true
|
||||
@ -310,15 +311,6 @@ android {
|
||||
buildFeatures {
|
||||
dataBinding true
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = '1.8'
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
|
10
service/.editorconfig
Normal file
10
service/.editorconfig
Normal file
@ -0,0 +1,10 @@
|
||||
# indicate this is the root of the project
|
||||
root = true
|
||||
|
||||
[*.{kt,java,xml,gradle,md}]
|
||||
charset = utf-8
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
end_of_line = lf
|
674
service/LICENSE
Normal file
674
service/LICENSE
Normal file
@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
125
service/android/build.gradle
Normal file
125
service/android/build.gradle
Normal file
@ -0,0 +1,125 @@
|
||||
apply plugin: 'com.android.library'
|
||||
apply plugin: 'maven'
|
||||
apply plugin: 'signing'
|
||||
|
||||
archivesBaseName = "signal-service-android"
|
||||
version = versionNumber
|
||||
group = groupName
|
||||
|
||||
repositories {
|
||||
mavenLocal()
|
||||
google()
|
||||
jcenter()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
configurations.all {
|
||||
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api (project(':service:java')) {
|
||||
exclude group: 'org.signal', module: 'signal-metadata-java'
|
||||
exclude group: 'org.apache.httpcomponents', module: 'httpclient'
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
compileSdkVersion androidCompileSdkVersion
|
||||
buildToolsVersion androidBuildToolsVersion
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion androidMinSdkVersion
|
||||
targetSdkVersion androidCompileSdkVersion
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
libraryVariants.all { variant ->
|
||||
variant.outputs.each { output ->
|
||||
def outputFile = output.outputFile
|
||||
if (outputFile != null && outputFile.name.endsWith('.aar')) {
|
||||
def fileName = "${archivesBaseName}-${version}.aar"
|
||||
output.outputFileName = fileName
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.whenTaskAdded { task ->
|
||||
if (task.name.equals("lint")) {
|
||||
task.enabled = false
|
||||
}
|
||||
}
|
||||
|
||||
def isReleaseBuild() {
|
||||
return version.contains("SNAPSHOT") == false
|
||||
}
|
||||
|
||||
def getReleaseRepositoryUrl() {
|
||||
return ""
|
||||
}
|
||||
|
||||
def getRepositoryUsername() {
|
||||
return ""
|
||||
}
|
||||
|
||||
def getRepositoryPassword() {
|
||||
return ""
|
||||
}
|
||||
|
||||
signing {
|
||||
required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
|
||||
sign configurations.archives
|
||||
}
|
||||
|
||||
uploadArchives {
|
||||
configuration = configurations.archives
|
||||
repositories.mavenDeployer {
|
||||
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
|
||||
|
||||
repository(url: getReleaseRepositoryUrl()) {
|
||||
authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
|
||||
}
|
||||
|
||||
pom.project {
|
||||
name 'signal-service-android'
|
||||
packaging 'aar'
|
||||
description 'Signal service communication library for Android'
|
||||
url 'https://github.com/loki-project/session-android-service'
|
||||
|
||||
scm {
|
||||
url 'scm:git@github.com:loki-project/session-android-service.git'
|
||||
connection 'scm:git@github.com:loki-project/session-android-service.git'
|
||||
developerConnection 'scm:git@github.com:loki-project/session-android-service.git'
|
||||
}
|
||||
|
||||
licenses {
|
||||
license {
|
||||
name 'GPLv3'
|
||||
url 'https://www.gnu.org/licenses/gpl-3.0.txt'
|
||||
distribution 'repo'
|
||||
}
|
||||
}
|
||||
|
||||
developers {
|
||||
developer {
|
||||
name 'Niels Andriesse'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
task installArchives(type: Upload) {
|
||||
description "Installs the artifacts to the local Maven repository."
|
||||
configuration = configurations['archives']
|
||||
repositories {
|
||||
mavenDeployer {
|
||||
repository url: "file://${System.properties['user.home']}/.m2/repository"
|
||||
}
|
||||
}
|
||||
}
|
7
service/android/src/main/AndroidManifest.xml
Normal file
7
service/android/src/main/AndroidManifest.xml
Normal file
@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="org.whispersystems.signalservice"
|
||||
android:versionCode="1"
|
||||
android:versionName="0.1">
|
||||
<application />
|
||||
</manifest>
|
@ -0,0 +1,89 @@
|
||||
package org.whispersystems.signalservice.api.util;
|
||||
|
||||
import android.app.AlarmManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.os.Build;
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
|
||||
import org.whispersystems.signalservice.api.util.SleepTimer;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* A sleep timer that is based on elapsed realtime, so
|
||||
* that it works properly, even in low-power sleep modes.
|
||||
*
|
||||
*/
|
||||
public class RealtimeSleepTimer implements SleepTimer {
|
||||
private static final String TAG = RealtimeSleepTimer.class.getSimpleName();
|
||||
|
||||
private final AlarmReceiver alarmReceiver;
|
||||
private final Context context;
|
||||
|
||||
public RealtimeSleepTimer(Context context) {
|
||||
this.context = context;
|
||||
alarmReceiver = new RealtimeSleepTimer.AlarmReceiver();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sleep(long millis) {
|
||||
context.registerReceiver(alarmReceiver,
|
||||
new IntentFilter(AlarmReceiver.WAKE_UP_THREAD_ACTION));
|
||||
|
||||
final long startTime = System.currentTimeMillis();
|
||||
alarmReceiver.setAlarm(millis);
|
||||
|
||||
while (System.currentTimeMillis() - startTime < millis) {
|
||||
try {
|
||||
synchronized (this) {
|
||||
wait(millis - System.currentTimeMillis() + startTime);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Log.w(TAG, e);
|
||||
}
|
||||
}
|
||||
|
||||
context.unregisterReceiver(alarmReceiver);
|
||||
}
|
||||
|
||||
private class AlarmReceiver extends BroadcastReceiver {
|
||||
private static final String WAKE_UP_THREAD_ACTION = "org.whispersystems.signalservice.api.util.RealtimeSleepTimer.AlarmReceiver.WAKE_UP_THREAD";
|
||||
|
||||
private void setAlarm(long millis) {
|
||||
final Intent intent = new Intent(WAKE_UP_THREAD_ACTION);
|
||||
final PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
|
||||
final AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
|
||||
|
||||
Log.w(TAG, "Setting alarm to wake up in " + millis + "ms.");
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
|
||||
SystemClock.elapsedRealtime() + millis,
|
||||
pendingIntent);
|
||||
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
|
||||
alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
|
||||
SystemClock.elapsedRealtime() + millis,
|
||||
pendingIntent);
|
||||
} else {
|
||||
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
|
||||
SystemClock.elapsedRealtime() + millis,
|
||||
pendingIntent);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
Log.w(TAG, "Waking up.");
|
||||
|
||||
synchronized (RealtimeSleepTimer.this) {
|
||||
RealtimeSleepTimer.this.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
14
service/build.gradle
Normal file
14
service/build.gradle
Normal file
@ -0,0 +1,14 @@
|
||||
apply plugin: "maven"
|
||||
|
||||
subprojects {
|
||||
ext.versionNumber = "2.13.2"
|
||||
ext.groupName = "org.whispersystems"
|
||||
|
||||
if (JavaVersion.current().isJava8Compatible()) {
|
||||
allprojects {
|
||||
tasks.withType(Javadoc) {
|
||||
options.addStringOption('Xdoclint:none', '-quiet')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
132
service/java/build.gradle
Normal file
132
service/java/build.gradle
Normal file
@ -0,0 +1,132 @@
|
||||
apply plugin: "java-library"
|
||||
apply plugin: "kotlin"
|
||||
apply plugin: "maven"
|
||||
apply plugin: "signing"
|
||||
|
||||
sourceCompatibility = 8
|
||||
targetCompatibility = 8
|
||||
archivesBaseName = "signal-service-java"
|
||||
version = versionNumber
|
||||
group = groupName
|
||||
|
||||
repositories {
|
||||
mavenLocal()
|
||||
google()
|
||||
jcenter()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
configurations.all {
|
||||
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation "com.google.protobuf:protobuf-java:$protobufVersion"
|
||||
implementation "com.googlecode.libphonenumber:libphonenumber:8.10.7"
|
||||
implementation "com.fasterxml.jackson.core:jackson-databind:$jacksonDatabindVersion"
|
||||
|
||||
implementation "org.whispersystems:curve25519-java:$curve25519Version"
|
||||
implementation "com.squareup.okhttp3:okhttp:$okhttpVersion"
|
||||
implementation "org.threeten:threetenbp:1.3.6"
|
||||
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion"
|
||||
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion"
|
||||
//FIXME AC: If we want to keep this library to target pure Java,
|
||||
// we should remove Android related dependencies.
|
||||
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9"
|
||||
implementation "nl.komponents.kovenant:kovenant:$kovenantVersion"
|
||||
|
||||
testImplementation "junit:junit:3.8.2"
|
||||
testImplementation "org.assertj:assertj-core:1.7.1"
|
||||
testImplementation "org.conscrypt:conscrypt-openjdk-uber:2.0.0"
|
||||
}
|
||||
|
||||
tasks.whenTaskAdded { task ->
|
||||
if (task.name.equals("lint")) {
|
||||
task.enabled = false
|
||||
}
|
||||
}
|
||||
|
||||
def isReleaseBuild() {
|
||||
return version.contains("SNAPSHOT") == false
|
||||
}
|
||||
|
||||
def getReleaseRepositoryUrl() {
|
||||
return ""
|
||||
}
|
||||
|
||||
def getRepositoryUsername() {
|
||||
return ""
|
||||
}
|
||||
|
||||
def getRepositoryPassword() {
|
||||
return ""
|
||||
}
|
||||
|
||||
signing {
|
||||
required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
|
||||
sign configurations.archives
|
||||
}
|
||||
|
||||
uploadArchives {
|
||||
configuration = configurations.archives
|
||||
repositories.mavenDeployer {
|
||||
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
|
||||
|
||||
repository(url: getReleaseRepositoryUrl()) {
|
||||
authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
|
||||
}
|
||||
|
||||
pom.project {
|
||||
name "signal-service-java"
|
||||
packaging "jar"
|
||||
description "Signal Service communication library for Java"
|
||||
url 'https://github.com/loki-project/loki-messenger-android-core'
|
||||
|
||||
scm {
|
||||
url 'scm:git@github.com:loki-project/loki-messenger-android-core.git'
|
||||
connection 'scm:git@github.com:loki-project/loki-messenger-android-core.git'
|
||||
developerConnection 'scm:git@github.com:loki-project/loki-messenger-android-core.git'
|
||||
}
|
||||
|
||||
licenses {
|
||||
license {
|
||||
name "GPLv3"
|
||||
url "https://www.gnu.org/licenses/gpl-3.0.txt"
|
||||
distribution "repo"
|
||||
}
|
||||
}
|
||||
|
||||
developers {
|
||||
developer {
|
||||
name "Niels Andriesse"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
task installArchives(type: Upload) {
|
||||
description "Installs the artifacts to the local Maven repository."
|
||||
configuration = configurations["archives"]
|
||||
repositories {
|
||||
mavenDeployer {
|
||||
repository url: "file://${System.properties["user.home"]}/.m2/repository"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
task packageJavadoc(type: Jar, dependsOn: "javadoc") {
|
||||
from javadoc.destinationDir
|
||||
classifier = "javadoc"
|
||||
}
|
||||
|
||||
task packageSources(type: Jar) {
|
||||
from sourceSets.main.allSource
|
||||
classifier = "sources"
|
||||
}
|
||||
|
||||
artifacts {
|
||||
archives packageJavadoc
|
||||
archives packageSources
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package org.signal.libsignal.metadata;
|
||||
|
||||
|
||||
public class InvalidMetadataMessageException extends Exception {
|
||||
public InvalidMetadataMessageException(String s) {
|
||||
super(s);
|
||||
}
|
||||
|
||||
public InvalidMetadataMessageException(Exception s) {
|
||||
super(s);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package org.signal.libsignal.metadata;
|
||||
|
||||
|
||||
public class InvalidMetadataVersionException extends Exception {
|
||||
public InvalidMetadataVersionException(String s) {
|
||||
super(s);
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package org.signal.libsignal.metadata;
|
||||
|
||||
|
||||
public class ProtocolDuplicateMessageException extends ProtocolException {
|
||||
public ProtocolDuplicateMessageException(Exception e, String sender, int senderDevice) {
|
||||
super(e, sender, senderDevice);
|
||||
}
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package org.signal.libsignal.metadata;
|
||||
|
||||
|
||||
public abstract class ProtocolException extends Exception {
|
||||
|
||||
private final String sender;
|
||||
private final int senderDevice;
|
||||
|
||||
public ProtocolException(Exception e, String sender, int senderDevice) {
|
||||
super(e);
|
||||
this.sender = sender;
|
||||
this.senderDevice = senderDevice;
|
||||
}
|
||||
|
||||
public String getSender() {
|
||||
return sender;
|
||||
}
|
||||
|
||||
public int getSenderDevice() {
|
||||
return senderDevice;
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package org.signal.libsignal.metadata;
|
||||
|
||||
|
||||
import org.whispersystems.libsignal.InvalidKeyException;
|
||||
|
||||
public class ProtocolInvalidKeyException extends ProtocolException {
|
||||
public ProtocolInvalidKeyException(InvalidKeyException e, String sender, int senderDevice) {
|
||||
super(e, sender, senderDevice);
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package org.signal.libsignal.metadata;
|
||||
|
||||
|
||||
public class ProtocolInvalidKeyIdException extends ProtocolException {
|
||||
public ProtocolInvalidKeyIdException(Exception e, String sender, int senderDevice) {
|
||||
super(e, sender, senderDevice);
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package org.signal.libsignal.metadata;
|
||||
|
||||
|
||||
import org.whispersystems.libsignal.InvalidMessageException;
|
||||
|
||||
public class ProtocolInvalidMessageException extends ProtocolException {
|
||||
public ProtocolInvalidMessageException(InvalidMessageException e, String sender, int senderDevice) {
|
||||
super(e, sender, senderDevice);
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package org.signal.libsignal.metadata;
|
||||
|
||||
|
||||
import org.whispersystems.libsignal.InvalidVersionException;
|
||||
|
||||
public class ProtocolInvalidVersionException extends ProtocolException {
|
||||
public ProtocolInvalidVersionException(InvalidVersionException e, String sender, int senderDevice) {
|
||||
super(e, sender, senderDevice);
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package org.signal.libsignal.metadata;
|
||||
|
||||
|
||||
import org.whispersystems.libsignal.LegacyMessageException;
|
||||
|
||||
public class ProtocolLegacyMessageException extends ProtocolException {
|
||||
public ProtocolLegacyMessageException(LegacyMessageException e, String sender, int senderDeviceId) {
|
||||
super(e, sender, senderDeviceId);
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package org.signal.libsignal.metadata;
|
||||
|
||||
|
||||
import org.whispersystems.libsignal.NoSessionException;
|
||||
|
||||
public class ProtocolNoSessionException extends ProtocolException {
|
||||
public ProtocolNoSessionException(NoSessionException e, String sender, int senderDevice) {
|
||||
super(e, sender, senderDevice);
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package org.signal.libsignal.metadata;
|
||||
|
||||
|
||||
import org.whispersystems.libsignal.UntrustedIdentityException;
|
||||
|
||||
public class ProtocolUntrustedIdentityException extends ProtocolException {
|
||||
public ProtocolUntrustedIdentityException(UntrustedIdentityException e, String sender, int senderDevice) {
|
||||
super(e, sender, senderDevice);
|
||||
}
|
||||
}
|
@ -0,0 +1,305 @@
|
||||
package org.signal.libsignal.metadata;
|
||||
|
||||
import org.signal.libsignal.metadata.certificate.CertificateValidator;
|
||||
import org.signal.libsignal.metadata.certificate.InvalidCertificateException;
|
||||
import org.signal.libsignal.metadata.certificate.SenderCertificate;
|
||||
import org.signal.libsignal.metadata.protocol.UnidentifiedSenderMessage;
|
||||
import org.signal.libsignal.metadata.protocol.UnidentifiedSenderMessageContent;
|
||||
import org.whispersystems.libsignal.DuplicateMessageException;
|
||||
import org.whispersystems.libsignal.IdentityKey;
|
||||
import org.whispersystems.libsignal.IdentityKeyPair;
|
||||
import org.whispersystems.libsignal.InvalidKeyException;
|
||||
import org.whispersystems.libsignal.InvalidKeyIdException;
|
||||
import org.whispersystems.libsignal.InvalidMacException;
|
||||
import org.whispersystems.libsignal.InvalidMessageException;
|
||||
import org.whispersystems.libsignal.InvalidVersionException;
|
||||
import org.whispersystems.libsignal.LegacyMessageException;
|
||||
import org.whispersystems.libsignal.NoSessionException;
|
||||
import org.whispersystems.libsignal.SessionCipher;
|
||||
import org.whispersystems.libsignal.SignalProtocolAddress;
|
||||
import org.whispersystems.libsignal.UntrustedIdentityException;
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
import org.whispersystems.libsignal.ecc.ECKeyPair;
|
||||
import org.whispersystems.libsignal.ecc.ECPrivateKey;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.kdf.HKDFv3;
|
||||
import org.whispersystems.libsignal.loki.FallbackSessionCipher;
|
||||
import org.whispersystems.libsignal.loki.LokiSessionCipher;
|
||||
import org.whispersystems.libsignal.loki.SessionResetProtocol;
|
||||
import org.whispersystems.libsignal.protocol.CiphertextMessage;
|
||||
import org.whispersystems.libsignal.protocol.PreKeySignalMessage;
|
||||
import org.whispersystems.libsignal.protocol.SignalMessage;
|
||||
import org.whispersystems.libsignal.state.SignalProtocolStore;
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
import org.whispersystems.libsignal.util.Hex;
|
||||
import org.whispersystems.libsignal.util.Pair;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.text.ParseException;
|
||||
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.IllegalBlockSizeException;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public class SealedSessionCipher {
|
||||
|
||||
private final SignalProtocolStore signalProtocolStore;
|
||||
private final SessionResetProtocol sessionResetProtocol;
|
||||
private final SignalProtocolAddress localAddress;
|
||||
|
||||
public SealedSessionCipher(SignalProtocolStore signalProtocolStore,
|
||||
SessionResetProtocol sessionResetProtocol,
|
||||
SignalProtocolAddress localAddress)
|
||||
{
|
||||
this.signalProtocolStore = signalProtocolStore;
|
||||
this.sessionResetProtocol = sessionResetProtocol;
|
||||
this.localAddress = localAddress;
|
||||
}
|
||||
|
||||
public byte[] encrypt(SignalProtocolAddress destinationAddress, SenderCertificate senderCertificate, byte[] paddedPlaintext)
|
||||
throws InvalidKeyException, UntrustedIdentityException
|
||||
{
|
||||
CiphertextMessage message = new SessionCipher(signalProtocolStore, destinationAddress).encrypt(paddedPlaintext);
|
||||
return encrypt(destinationAddress, senderCertificate, message);
|
||||
}
|
||||
|
||||
public byte[] encrypt(SignalProtocolAddress destinationAddress, SenderCertificate senderCertificate, CiphertextMessage message)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
try {
|
||||
IdentityKeyPair ourIdentity = signalProtocolStore.getIdentityKeyPair();
|
||||
byte[] theirPublicKey = Hex.fromStringCondensed(destinationAddress.getName());
|
||||
ECPublicKey theirIdentity = new IdentityKey(theirPublicKey, 0).getPublicKey();
|
||||
|
||||
ECKeyPair ephemeral = Curve.generateKeyPair();
|
||||
byte[] ephemeralSalt = ByteUtil.combine("UnidentifiedDelivery".getBytes(), theirIdentity.serialize(), ephemeral.getPublicKey().serialize());
|
||||
EphemeralKeys ephemeralKeys = calculateEphemeralKeys(theirIdentity, ephemeral.getPrivateKey(), ephemeralSalt);
|
||||
byte[] staticKeyCiphertext = encrypt(ephemeralKeys.cipherKey, ephemeralKeys.macKey, ourIdentity.getPublicKey().serialize());
|
||||
|
||||
byte[] staticSalt = ByteUtil.combine(ephemeralKeys.chainKey, staticKeyCiphertext);
|
||||
StaticKeys staticKeys = calculateStaticKeys(theirIdentity, ourIdentity.getPrivateKey(), staticSalt);
|
||||
UnidentifiedSenderMessageContent content = new UnidentifiedSenderMessageContent(message.getType(), senderCertificate, message.serialize());
|
||||
byte[] messageBytes = encrypt(staticKeys.cipherKey, staticKeys.macKey, content.getSerialized());
|
||||
|
||||
return new UnidentifiedSenderMessage(ephemeral.getPublicKey(), staticKeyCiphertext, messageBytes).getSerialized();
|
||||
} catch (IOException e) {
|
||||
throw new InvalidKeyException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt a sealed session message.
|
||||
* This will return a Pair<Integer, byte[]> which is the CipherTextMessage type and the decrypted message content
|
||||
*/
|
||||
public Pair<SignalProtocolAddress, Pair<Integer, byte[]>> decrypt(CertificateValidator validator, byte[] ciphertext, long timestamp, String prefixedPublicKey)
|
||||
throws
|
||||
InvalidMetadataMessageException, InvalidMetadataVersionException,
|
||||
ProtocolInvalidMessageException, ProtocolInvalidKeyException,
|
||||
ProtocolNoSessionException, ProtocolLegacyMessageException,
|
||||
ProtocolInvalidVersionException, ProtocolDuplicateMessageException,
|
||||
ProtocolInvalidKeyIdException, ProtocolUntrustedIdentityException,
|
||||
SelfSendException, IOException
|
||||
{
|
||||
UnidentifiedSenderMessageContent content;
|
||||
|
||||
try {
|
||||
IdentityKeyPair ourIdentity = signalProtocolStore.getIdentityKeyPair();
|
||||
UnidentifiedSenderMessage wrapper = new UnidentifiedSenderMessage(ciphertext);
|
||||
byte[] ephemeralSalt = ByteUtil.combine("UnidentifiedDelivery".getBytes(), ourIdentity.getPublicKey().serialize(), wrapper.getEphemeral().serialize());
|
||||
EphemeralKeys ephemeralKeys = calculateEphemeralKeys(wrapper.getEphemeral(), ourIdentity.getPrivateKey(), ephemeralSalt);
|
||||
byte[] staticKeyBytes = decrypt(ephemeralKeys.cipherKey, ephemeralKeys.macKey, wrapper.getEncryptedStatic());
|
||||
|
||||
ECPublicKey staticKey = Curve.decodePoint(staticKeyBytes, 0);
|
||||
byte[] staticSalt = ByteUtil.combine(ephemeralKeys.chainKey, wrapper.getEncryptedStatic());
|
||||
StaticKeys staticKeys = calculateStaticKeys(staticKey, ourIdentity.getPrivateKey(), staticSalt);
|
||||
byte[] messageBytes = decrypt(staticKeys.cipherKey, staticKeys.macKey, wrapper.getEncryptedMessage());
|
||||
|
||||
content = new UnidentifiedSenderMessageContent(messageBytes);
|
||||
validator.validate(content.getSenderCertificate(), timestamp);
|
||||
|
||||
if (content.getSenderCertificate().getSender().equals(localAddress.getName()) &&
|
||||
content.getSenderCertificate().getSenderDeviceId() == localAddress.getDeviceId())
|
||||
{
|
||||
throw new SelfSendException();
|
||||
}
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new InvalidMetadataMessageException(e);
|
||||
} catch (InvalidMacException e) {
|
||||
throw new InvalidMetadataMessageException(e);
|
||||
} catch (InvalidCertificateException e) {
|
||||
throw new InvalidMetadataMessageException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
Pair<Integer, byte[]> dataPair = new Pair<>(content.getType(), decrypt(content));
|
||||
return new Pair<>(
|
||||
new SignalProtocolAddress(content.getSenderCertificate().getSender(), content.getSenderCertificate().getSenderDeviceId()),
|
||||
dataPair
|
||||
);
|
||||
} catch (InvalidMessageException e) {
|
||||
throw new ProtocolInvalidMessageException(e, content.getSenderCertificate().getSender(), content.getSenderCertificate().getSenderDeviceId());
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new ProtocolInvalidKeyException(e, content.getSenderCertificate().getSender(), content.getSenderCertificate().getSenderDeviceId());
|
||||
} catch (NoSessionException e) {
|
||||
throw new ProtocolNoSessionException(e, content.getSenderCertificate().getSender(), content.getSenderCertificate().getSenderDeviceId());
|
||||
} catch (LegacyMessageException e) {
|
||||
throw new ProtocolLegacyMessageException(e, content.getSenderCertificate().getSender(), content.getSenderCertificate().getSenderDeviceId());
|
||||
} catch (InvalidVersionException e) {
|
||||
throw new ProtocolInvalidVersionException(e, content.getSenderCertificate().getSender(), content.getSenderCertificate().getSenderDeviceId());
|
||||
} catch (DuplicateMessageException e) {
|
||||
throw new ProtocolDuplicateMessageException(e, content.getSenderCertificate().getSender(), content.getSenderCertificate().getSenderDeviceId());
|
||||
} catch (InvalidKeyIdException e) {
|
||||
throw new ProtocolInvalidKeyIdException(e, content.getSenderCertificate().getSender(), content.getSenderCertificate().getSenderDeviceId());
|
||||
} catch (UntrustedIdentityException e) {
|
||||
throw new ProtocolUntrustedIdentityException(e, content.getSenderCertificate().getSender(), content.getSenderCertificate().getSenderDeviceId());
|
||||
}
|
||||
}
|
||||
|
||||
public int getSessionVersion(SignalProtocolAddress remoteAddress) {
|
||||
return new SessionCipher(signalProtocolStore, remoteAddress).getSessionVersion();
|
||||
}
|
||||
|
||||
public int getRemoteRegistrationId(SignalProtocolAddress remoteAddress) {
|
||||
return new SessionCipher(signalProtocolStore, remoteAddress).getRemoteRegistrationId();
|
||||
}
|
||||
|
||||
private EphemeralKeys calculateEphemeralKeys(ECPublicKey ephemeralPublic, ECPrivateKey ephemeralPrivate, byte[] salt) throws InvalidKeyException {
|
||||
try {
|
||||
byte[] ephemeralSecret = Curve.calculateAgreement(ephemeralPublic, ephemeralPrivate);
|
||||
byte[] ephemeralDerived = new HKDFv3().deriveSecrets(ephemeralSecret, salt, new byte[0], 96);
|
||||
byte[][] ephemeralDerivedParts = ByteUtil.split(ephemeralDerived, 32, 32, 32);
|
||||
|
||||
return new EphemeralKeys(ephemeralDerivedParts[0], ephemeralDerivedParts[1], ephemeralDerivedParts[2]);
|
||||
} catch (ParseException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private StaticKeys calculateStaticKeys(ECPublicKey staticPublic, ECPrivateKey staticPrivate, byte[] salt) throws InvalidKeyException {
|
||||
try {
|
||||
byte[] staticSecret = Curve.calculateAgreement(staticPublic, staticPrivate);
|
||||
byte[] staticDerived = new HKDFv3().deriveSecrets(staticSecret, salt, new byte[0], 96);
|
||||
byte[][] staticDerivedParts = ByteUtil.split(staticDerived, 32, 32, 32);
|
||||
|
||||
return new StaticKeys(staticDerivedParts[1], staticDerivedParts[2]);
|
||||
} catch (ParseException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] decrypt(UnidentifiedSenderMessageContent message)
|
||||
throws InvalidVersionException, InvalidMessageException, InvalidKeyException, DuplicateMessageException, InvalidKeyIdException, UntrustedIdentityException, LegacyMessageException, NoSessionException
|
||||
{
|
||||
|
||||
SignalProtocolAddress sender = new SignalProtocolAddress(message.getSenderCertificate().getSender(), message.getSenderCertificate().getSenderDeviceId());
|
||||
|
||||
switch (message.getType()) {
|
||||
case CiphertextMessage.WHISPER_TYPE: return new LokiSessionCipher(signalProtocolStore, sessionResetProtocol, sender).decrypt(new SignalMessage(message.getContent()));
|
||||
case CiphertextMessage.PREKEY_TYPE: return new LokiSessionCipher(signalProtocolStore, sessionResetProtocol, sender).decrypt(new PreKeySignalMessage(message.getContent()));
|
||||
case CiphertextMessage.FALLBACK_MESSAGE_TYPE: {
|
||||
try {
|
||||
byte[] privateKey = signalProtocolStore.getIdentityKeyPair().getPrivateKey().serialize();
|
||||
return new FallbackSessionCipher(privateKey, sender.getName()).decrypt(message.getContent());
|
||||
} catch (Exception e) {
|
||||
throw new InvalidMessageException("Failed to decrypt fallback message.");
|
||||
}
|
||||
}
|
||||
default: throw new InvalidMessageException("Unknown type: " + message.getType());
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] encrypt(SecretKeySpec cipherKey, SecretKeySpec macKey, byte[] plaintext) {
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, cipherKey, new IvParameterSpec(new byte[16]));
|
||||
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(macKey);
|
||||
|
||||
byte[] ciphertext = cipher.doFinal(plaintext);
|
||||
byte[] ourFullMac = mac.doFinal(ciphertext);
|
||||
byte[] ourMac = ByteUtil.trim(ourFullMac, 10);
|
||||
|
||||
return ByteUtil.combine(ciphertext, ourMac);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (NoSuchPaddingException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (java.security.InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (BadPaddingException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (IllegalBlockSizeException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (InvalidAlgorithmParameterException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] decrypt(SecretKeySpec cipherKey, SecretKeySpec macKey, byte[] ciphertext) throws InvalidMacException {
|
||||
try {
|
||||
if (ciphertext.length < 10) {
|
||||
throw new InvalidMacException("Ciphertext not long enough for MAC!");
|
||||
}
|
||||
|
||||
byte[][] ciphertextParts = ByteUtil.split(ciphertext, ciphertext.length - 10, 10);
|
||||
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(macKey);
|
||||
|
||||
byte[] digest = mac.doFinal(ciphertextParts[0]);
|
||||
byte[] ourMac = ByteUtil.trim(digest, 10);
|
||||
byte[] theirMac = ciphertextParts[1];
|
||||
|
||||
if (!MessageDigest.isEqual(ourMac, theirMac)) {
|
||||
throw new InvalidMacException("Bad mac!");
|
||||
}
|
||||
|
||||
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, cipherKey, new IvParameterSpec(new byte[16]));
|
||||
|
||||
return cipher.doFinal(ciphertextParts[0]);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (java.security.InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (NoSuchPaddingException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (InvalidAlgorithmParameterException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (IllegalBlockSizeException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (BadPaddingException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static class EphemeralKeys {
|
||||
private final byte[] chainKey;
|
||||
private final SecretKeySpec cipherKey;
|
||||
private final SecretKeySpec macKey;
|
||||
|
||||
private EphemeralKeys(byte[] chainKey, byte[] cipherKey, byte[] macKey) {
|
||||
this.chainKey = chainKey;
|
||||
this.cipherKey = new SecretKeySpec(cipherKey, "AES");
|
||||
this.macKey = new SecretKeySpec(macKey, "HmacSHA256");
|
||||
}
|
||||
}
|
||||
|
||||
private static class StaticKeys {
|
||||
private final SecretKeySpec cipherKey;
|
||||
private final SecretKeySpec macKey;
|
||||
|
||||
private StaticKeys(byte[] cipherKey, byte[] macKey) {
|
||||
this.cipherKey = new SecretKeySpec(cipherKey, "AES");
|
||||
this.macKey = new SecretKeySpec(macKey, "HmacSHA256");
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
package org.signal.libsignal.metadata;
|
||||
|
||||
public class SelfSendException extends Exception { }
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,24 @@
|
||||
package org.signal.libsignal.metadata.certificate;
|
||||
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class CertificateValidator {
|
||||
|
||||
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
|
||||
private static final Set<Integer> REVOKED = new HashSet<Integer>() {{
|
||||
|
||||
}};
|
||||
|
||||
public void validate(SenderCertificate certificate, long validationTime) throws InvalidCertificateException {
|
||||
if (certificate.getSender() == null || certificate.getSenderDeviceId() <= 0) {
|
||||
throw new InvalidCertificateException("Sender or sender device id is invalid");
|
||||
}
|
||||
}
|
||||
|
||||
// VisibleForTesting
|
||||
void validate(ServerCertificate certificate) throws InvalidCertificateException {
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,12 @@
|
||||
package org.signal.libsignal.metadata.certificate;
|
||||
|
||||
|
||||
public class InvalidCertificateException extends Exception {
|
||||
public InvalidCertificateException(String s) {
|
||||
super(s);
|
||||
}
|
||||
|
||||
public InvalidCertificateException(Exception e) {
|
||||
super(e);
|
||||
}
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package org.signal.libsignal.metadata.certificate;
|
||||
|
||||
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
|
||||
import org.signal.libsignal.metadata.SignalProtos;
|
||||
|
||||
|
||||
public class SenderCertificate {
|
||||
|
||||
private final int senderDeviceId;
|
||||
private final String sender;
|
||||
|
||||
private final byte[] serialized;
|
||||
private final byte[] certificate;
|
||||
|
||||
public SenderCertificate(byte[] serialized) throws InvalidCertificateException {
|
||||
try {
|
||||
SignalProtos.SenderCertificate certificate = SignalProtos.SenderCertificate.parseFrom(serialized);
|
||||
|
||||
if (!certificate.hasSenderDevice() || !certificate.hasSender()) {
|
||||
throw new InvalidCertificateException("Missing fields");
|
||||
}
|
||||
|
||||
this.sender = certificate.getSender();
|
||||
this.senderDeviceId = certificate.getSenderDevice();
|
||||
|
||||
this.serialized = serialized;
|
||||
this.certificate = certificate.toByteArray();
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new InvalidCertificateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public int getSenderDeviceId() {
|
||||
return senderDeviceId;
|
||||
}
|
||||
|
||||
public String getSender() {
|
||||
return sender;
|
||||
}
|
||||
|
||||
public byte[] getSerialized() {
|
||||
return serialized;
|
||||
}
|
||||
|
||||
public byte[] getCertificate() {
|
||||
return certificate;
|
||||
}
|
||||
}
|
@ -0,0 +1,66 @@
|
||||
package org.signal.libsignal.metadata.certificate;
|
||||
|
||||
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
|
||||
import org.signal.libsignal.metadata.SignalProtos;
|
||||
import org.whispersystems.libsignal.InvalidKeyException;
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
|
||||
public class ServerCertificate {
|
||||
|
||||
private final int keyId;
|
||||
private final ECPublicKey key;
|
||||
|
||||
private final byte[] serialized;
|
||||
private final byte[] certificate;
|
||||
private final byte[] signature;
|
||||
|
||||
public ServerCertificate(byte[] serialized) throws InvalidCertificateException {
|
||||
try {
|
||||
SignalProtos.ServerCertificate wrapper = SignalProtos.ServerCertificate.parseFrom(serialized);
|
||||
|
||||
if (!wrapper.hasCertificate() || !wrapper.hasSignature()) {
|
||||
throw new InvalidCertificateException("Missing fields");
|
||||
}
|
||||
|
||||
SignalProtos.ServerCertificate.Certificate certificate = SignalProtos.ServerCertificate.Certificate.parseFrom(wrapper.getCertificate());
|
||||
|
||||
if (!certificate.hasId() || !certificate.hasKey()) {
|
||||
throw new InvalidCertificateException("Missing fields");
|
||||
}
|
||||
|
||||
this.keyId = certificate.getId();
|
||||
this.key = Curve.decodePoint(certificate.getKey().toByteArray(), 0);
|
||||
this.serialized = serialized;
|
||||
this.certificate = wrapper.getCertificate().toByteArray();
|
||||
this.signature = wrapper.getSignature().toByteArray();
|
||||
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new InvalidCertificateException(e);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new InvalidCertificateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public int getKeyId() {
|
||||
return keyId;
|
||||
}
|
||||
|
||||
public ECPublicKey getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public byte[] getSerialized() {
|
||||
return serialized;
|
||||
}
|
||||
|
||||
public byte[] getCertificate() {
|
||||
return certificate;
|
||||
}
|
||||
|
||||
public byte[] getSignature() {
|
||||
return signature;
|
||||
}
|
||||
}
|
@ -0,0 +1,89 @@
|
||||
package org.signal.libsignal.metadata.protocol;
|
||||
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
|
||||
import org.signal.libsignal.metadata.InvalidMetadataMessageException;
|
||||
import org.signal.libsignal.metadata.InvalidMetadataVersionException;
|
||||
import org.signal.libsignal.metadata.SignalProtos;
|
||||
import org.whispersystems.libsignal.InvalidKeyException;
|
||||
import org.whispersystems.libsignal.InvalidMessageException;
|
||||
import org.whispersystems.libsignal.InvalidVersionException;
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
|
||||
public class UnidentifiedSenderMessage {
|
||||
|
||||
private static final int CIPHERTEXT_VERSION = 1;
|
||||
|
||||
private final int version;
|
||||
private final ECPublicKey ephemeral;
|
||||
private final byte[] encryptedStatic;
|
||||
private final byte[] encryptedMessage;
|
||||
private final byte[] serialized;
|
||||
|
||||
public UnidentifiedSenderMessage(byte[] serialized)
|
||||
throws InvalidMetadataMessageException, InvalidMetadataVersionException
|
||||
{
|
||||
try {
|
||||
this.version = ByteUtil.highBitsToInt(serialized[0]);
|
||||
|
||||
if (version > CIPHERTEXT_VERSION) {
|
||||
throw new InvalidMetadataVersionException("Unknown version: " + this.version);
|
||||
}
|
||||
|
||||
SignalProtos.UnidentifiedSenderMessage unidentifiedSenderMessage = SignalProtos.UnidentifiedSenderMessage.parseFrom(ByteString.copyFrom(serialized, 1, serialized.length - 1));
|
||||
|
||||
if (!unidentifiedSenderMessage.hasEphemeralPublic() ||
|
||||
!unidentifiedSenderMessage.hasEncryptedStatic() ||
|
||||
!unidentifiedSenderMessage.hasEncryptedMessage())
|
||||
{
|
||||
throw new InvalidMetadataMessageException("Missing fields");
|
||||
}
|
||||
|
||||
this.ephemeral = Curve.decodePoint(unidentifiedSenderMessage.getEphemeralPublic().toByteArray(), 0);
|
||||
this.encryptedStatic = unidentifiedSenderMessage.getEncryptedStatic().toByteArray();
|
||||
this.encryptedMessage = unidentifiedSenderMessage.getEncryptedMessage().toByteArray();
|
||||
this.serialized = serialized;
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new InvalidMetadataMessageException(e);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new InvalidMetadataMessageException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public UnidentifiedSenderMessage(ECPublicKey ephemeral, byte[] encryptedStatic, byte[] encryptedMessage) {
|
||||
this.version = CIPHERTEXT_VERSION;
|
||||
this.ephemeral = ephemeral;
|
||||
this.encryptedStatic = encryptedStatic;
|
||||
this.encryptedMessage = encryptedMessage;
|
||||
|
||||
byte[] versionBytes = {ByteUtil.intsToByteHighAndLow(CIPHERTEXT_VERSION, CIPHERTEXT_VERSION)};
|
||||
byte[] messageBytes = SignalProtos.UnidentifiedSenderMessage.newBuilder()
|
||||
.setEncryptedMessage(ByteString.copyFrom(encryptedMessage))
|
||||
.setEncryptedStatic(ByteString.copyFrom(encryptedStatic))
|
||||
.setEphemeralPublic(ByteString.copyFrom(ephemeral.serialize()))
|
||||
.build()
|
||||
.toByteArray();
|
||||
|
||||
this.serialized = ByteUtil.combine(versionBytes, messageBytes);
|
||||
}
|
||||
|
||||
public ECPublicKey getEphemeral() {
|
||||
return ephemeral;
|
||||
}
|
||||
|
||||
public byte[] getEncryptedStatic() {
|
||||
return encryptedStatic;
|
||||
}
|
||||
|
||||
public byte[] getEncryptedMessage() {
|
||||
return encryptedMessage;
|
||||
}
|
||||
|
||||
public byte[] getSerialized() {
|
||||
return serialized;
|
||||
}
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
package org.signal.libsignal.metadata.protocol;
|
||||
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
|
||||
import org.signal.libsignal.metadata.InvalidMetadataMessageException;
|
||||
import org.signal.libsignal.metadata.SignalProtos;
|
||||
import org.signal.libsignal.metadata.certificate.InvalidCertificateException;
|
||||
import org.signal.libsignal.metadata.certificate.SenderCertificate;
|
||||
import org.whispersystems.libsignal.protocol.CiphertextMessage;
|
||||
|
||||
public class UnidentifiedSenderMessageContent {
|
||||
|
||||
private final int type;
|
||||
private final SenderCertificate senderCertificate;
|
||||
private final byte[] content;
|
||||
private final byte[] serialized;
|
||||
|
||||
public UnidentifiedSenderMessageContent(byte[] serialized) throws InvalidMetadataMessageException, InvalidCertificateException {
|
||||
try {
|
||||
SignalProtos.UnidentifiedSenderMessage.Message message = SignalProtos.UnidentifiedSenderMessage.Message.parseFrom(serialized);
|
||||
|
||||
if (!message.hasType() || !message.hasSenderCertificate() || !message.hasContent()) {
|
||||
throw new InvalidMetadataMessageException("Missing fields");
|
||||
}
|
||||
|
||||
switch (message.getType()) {
|
||||
case MESSAGE: this.type = CiphertextMessage.WHISPER_TYPE; break;
|
||||
case PREKEY_MESSAGE: this.type = CiphertextMessage.PREKEY_TYPE; break;
|
||||
case FALLBACK_MESSAGE: this.type = CiphertextMessage.FALLBACK_MESSAGE_TYPE; break;
|
||||
default: throw new InvalidMetadataMessageException("Unknown type: " + message.getType().getNumber());
|
||||
}
|
||||
|
||||
this.senderCertificate = new SenderCertificate(message.getSenderCertificate().toByteArray());
|
||||
this.content = message.getContent().toByteArray();
|
||||
this.serialized = serialized;
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new InvalidMetadataMessageException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public UnidentifiedSenderMessageContent(int type, SenderCertificate senderCertificate, byte[] content) {
|
||||
try {
|
||||
this.serialized = SignalProtos.UnidentifiedSenderMessage.Message.newBuilder()
|
||||
.setType(SignalProtos.UnidentifiedSenderMessage.Message.Type.valueOf(getProtoType(type)))
|
||||
.setSenderCertificate(SignalProtos.SenderCertificate.parseFrom(senderCertificate.getSerialized()))
|
||||
.setContent(ByteString.copyFrom(content))
|
||||
.build()
|
||||
.toByteArray();
|
||||
|
||||
this.type = type;
|
||||
this.senderCertificate = senderCertificate;
|
||||
this.content = content;
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public int getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public SenderCertificate getSenderCertificate() {
|
||||
return senderCertificate;
|
||||
}
|
||||
|
||||
public byte[] getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public byte[] getSerialized() {
|
||||
return serialized;
|
||||
}
|
||||
|
||||
private int getProtoType(int type) {
|
||||
switch (type) {
|
||||
case CiphertextMessage.WHISPER_TYPE: return SignalProtos.UnidentifiedSenderMessage.Message.Type.MESSAGE_VALUE;
|
||||
case CiphertextMessage.PREKEY_TYPE: return SignalProtos.UnidentifiedSenderMessage.Message.Type.PREKEY_MESSAGE_VALUE;
|
||||
case CiphertextMessage.FALLBACK_MESSAGE_TYPE: return SignalProtos.UnidentifiedSenderMessage.Message.Type.FALLBACK_MESSAGE_VALUE;
|
||||
default: throw new AssertionError(type);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
public interface DecryptionCallback {
|
||||
public void handlePlaintext(byte[] plaintext);
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
public class DuplicateMessageException extends Exception {
|
||||
public DuplicateMessageException(String s) {
|
||||
super(s);
|
||||
}
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.util.Hex;
|
||||
|
||||
/**
|
||||
* A class for representing an identity key.
|
||||
*
|
||||
* @author Moxie Marlinspike
|
||||
*/
|
||||
|
||||
public class IdentityKey {
|
||||
|
||||
private final ECPublicKey publicKey;
|
||||
|
||||
public IdentityKey(ECPublicKey publicKey) {
|
||||
this.publicKey = publicKey;
|
||||
}
|
||||
|
||||
public IdentityKey(byte[] bytes, int offset) throws InvalidKeyException {
|
||||
this.publicKey = Curve.decodePoint(bytes, offset);
|
||||
}
|
||||
|
||||
public ECPublicKey getPublicKey() {
|
||||
return publicKey;
|
||||
}
|
||||
|
||||
public byte[] serialize() {
|
||||
return publicKey.serialize();
|
||||
}
|
||||
|
||||
public String getFingerprint() {
|
||||
return Hex.toString(publicKey.serialize());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (other == null) return false;
|
||||
if (!(other instanceof IdentityKey)) return false;
|
||||
|
||||
return publicKey.equals(((IdentityKey) other).getPublicKey());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return publicKey.hashCode();
|
||||
}
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
import org.whispersystems.libsignal.ecc.ECPrivateKey;
|
||||
|
||||
import static org.whispersystems.libsignal.state.StorageProtos.IdentityKeyPairStructure;
|
||||
|
||||
/**
|
||||
* Holder for public and private identity key pair.
|
||||
*
|
||||
* @author Moxie Marlinspike
|
||||
*/
|
||||
public class IdentityKeyPair {
|
||||
|
||||
private final IdentityKey publicKey;
|
||||
private final ECPrivateKey privateKey;
|
||||
|
||||
public IdentityKeyPair(IdentityKey publicKey, ECPrivateKey privateKey) {
|
||||
this.publicKey = publicKey;
|
||||
this.privateKey = privateKey;
|
||||
}
|
||||
|
||||
public IdentityKeyPair(byte[] serialized) throws InvalidKeyException {
|
||||
try {
|
||||
IdentityKeyPairStructure structure = IdentityKeyPairStructure.parseFrom(serialized);
|
||||
this.publicKey = new IdentityKey(structure.getPublicKey().toByteArray(), 0);
|
||||
this.privateKey = Curve.decodePrivatePoint(structure.getPrivateKey().toByteArray());
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new InvalidKeyException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public IdentityKey getPublicKey() {
|
||||
return publicKey;
|
||||
}
|
||||
|
||||
public ECPrivateKey getPrivateKey() {
|
||||
return privateKey;
|
||||
}
|
||||
|
||||
public byte[] serialize() {
|
||||
return IdentityKeyPairStructure.newBuilder()
|
||||
.setPublicKey(ByteString.copyFrom(publicKey.serialize()))
|
||||
.setPrivateKey(ByteString.copyFrom(privateKey.serialize()))
|
||||
.build().toByteArray();
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
public class InvalidKeyException extends Exception {
|
||||
|
||||
public InvalidKeyException() {}
|
||||
|
||||
public InvalidKeyException(String detailMessage) {
|
||||
super(detailMessage);
|
||||
}
|
||||
|
||||
public InvalidKeyException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
|
||||
public InvalidKeyException(String detailMessage, Throwable throwable) {
|
||||
super(detailMessage, throwable);
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
public class InvalidKeyIdException extends Exception {
|
||||
public InvalidKeyIdException(String detailMessage) {
|
||||
super(detailMessage);
|
||||
}
|
||||
|
||||
public InvalidKeyIdException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
public class InvalidMacException extends Exception {
|
||||
|
||||
public InvalidMacException(String detailMessage) {
|
||||
super(detailMessage);
|
||||
}
|
||||
|
||||
public InvalidMacException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class InvalidMessageException extends Exception {
|
||||
|
||||
public InvalidMessageException() {}
|
||||
|
||||
public InvalidMessageException(String detailMessage) {
|
||||
super(detailMessage);
|
||||
}
|
||||
|
||||
public InvalidMessageException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
|
||||
public InvalidMessageException(String detailMessage, Throwable throwable) {
|
||||
super(detailMessage, throwable);
|
||||
}
|
||||
|
||||
public InvalidMessageException(String detailMessage, List<Exception> exceptions) {
|
||||
super(detailMessage, exceptions.get(0));
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
public class InvalidVersionException extends Exception {
|
||||
public InvalidVersionException(String detailMessage) {
|
||||
super(detailMessage);
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
public class LegacyMessageException extends Exception {
|
||||
public LegacyMessageException(String s) {
|
||||
super(s);
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
public class NoSessionException extends Exception {
|
||||
public NoSessionException(String s) {
|
||||
super(s);
|
||||
}
|
||||
|
||||
public NoSessionException(Exception nested) {
|
||||
super(nested);
|
||||
}
|
||||
}
|
@ -0,0 +1,212 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
import org.whispersystems.libsignal.ecc.ECKeyPair;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.logging.Log;
|
||||
import org.whispersystems.libsignal.protocol.PreKeySignalMessage;
|
||||
import org.whispersystems.libsignal.protocol.SignalMessage;
|
||||
import org.whispersystems.libsignal.ratchet.AliceSignalProtocolParameters;
|
||||
import org.whispersystems.libsignal.ratchet.BobSignalProtocolParameters;
|
||||
import org.whispersystems.libsignal.ratchet.RatchetingSession;
|
||||
import org.whispersystems.libsignal.state.IdentityKeyStore;
|
||||
import org.whispersystems.libsignal.state.PreKeyBundle;
|
||||
import org.whispersystems.libsignal.state.PreKeyStore;
|
||||
import org.whispersystems.libsignal.state.SessionRecord;
|
||||
import org.whispersystems.libsignal.state.SessionStore;
|
||||
import org.whispersystems.libsignal.state.SignalProtocolStore;
|
||||
import org.whispersystems.libsignal.state.SignedPreKeyStore;
|
||||
import org.whispersystems.libsignal.util.guava.Optional;
|
||||
|
||||
/**
|
||||
* SessionBuilder is responsible for setting up encrypted sessions.
|
||||
* Once a session has been established, {@link org.whispersystems.libsignal.SessionCipher}
|
||||
* can be used to encrypt/decrypt messages in that session.
|
||||
* <p>
|
||||
* Sessions are built from one of three different possible vectors:
|
||||
* <ol>
|
||||
* <li>A {@link org.whispersystems.libsignal.state.PreKeyBundle} retrieved from a server.</li>
|
||||
* <li>A {@link PreKeySignalMessage} received from a client.</li>
|
||||
* </ol>
|
||||
*
|
||||
* Sessions are constructed per recipientId + deviceId tuple. Remote logical users are identified
|
||||
* by their recipientId, and each logical recipientId can have multiple physical devices.
|
||||
*
|
||||
* @author Moxie Marlinspike
|
||||
*/
|
||||
public class SessionBuilder {
|
||||
|
||||
private static final String TAG = SessionBuilder.class.getSimpleName();
|
||||
|
||||
private final SessionStore sessionStore;
|
||||
private final PreKeyStore preKeyStore;
|
||||
private final SignedPreKeyStore signedPreKeyStore;
|
||||
private final IdentityKeyStore identityKeyStore;
|
||||
private final SignalProtocolAddress remoteAddress;
|
||||
|
||||
/**
|
||||
* Constructs a SessionBuilder.
|
||||
*
|
||||
* @param sessionStore The {@link org.whispersystems.libsignal.state.SessionStore} to store the constructed session in.
|
||||
* @param preKeyStore The {@link org.whispersystems.libsignal.state.PreKeyStore} where the client's local {@link org.whispersystems.libsignal.state.PreKeyRecord}s are stored.
|
||||
* @param identityKeyStore The {@link org.whispersystems.libsignal.state.IdentityKeyStore} containing the client's identity key information.
|
||||
* @param remoteAddress The address of the remote user to build a session with.
|
||||
*/
|
||||
public SessionBuilder(SessionStore sessionStore,
|
||||
PreKeyStore preKeyStore,
|
||||
SignedPreKeyStore signedPreKeyStore,
|
||||
IdentityKeyStore identityKeyStore,
|
||||
SignalProtocolAddress remoteAddress)
|
||||
{
|
||||
this.sessionStore = sessionStore;
|
||||
this.preKeyStore = preKeyStore;
|
||||
this.signedPreKeyStore = signedPreKeyStore;
|
||||
this.identityKeyStore = identityKeyStore;
|
||||
this.remoteAddress = remoteAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a SessionBuilder
|
||||
* @param store The {@link SignalProtocolStore} to store all state information in.
|
||||
* @param remoteAddress The address of the remote user to build a session with.
|
||||
*/
|
||||
public SessionBuilder(SignalProtocolStore store, SignalProtocolAddress remoteAddress) {
|
||||
this(store, store, store, store, remoteAddress);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a new session from a received {@link PreKeySignalMessage}.
|
||||
*
|
||||
* After a session is constructed in this way, the embedded {@link SignalMessage}
|
||||
* can be decrypted.
|
||||
*
|
||||
* @param message The received {@link PreKeySignalMessage}.
|
||||
* @throws org.whispersystems.libsignal.InvalidKeyIdException when there is no local
|
||||
* {@link org.whispersystems.libsignal.state.PreKeyRecord}
|
||||
* that corresponds to the PreKey ID in
|
||||
* the message.
|
||||
* @throws org.whispersystems.libsignal.InvalidKeyException when the message is formatted incorrectly.
|
||||
* @throws org.whispersystems.libsignal.UntrustedIdentityException when the {@link IdentityKey} of the sender is untrusted.
|
||||
*/
|
||||
/*package*/ Optional<Integer> process(SessionRecord sessionRecord, PreKeySignalMessage message)
|
||||
throws InvalidKeyIdException, InvalidKeyException, UntrustedIdentityException
|
||||
{
|
||||
IdentityKey theirIdentityKey = message.getIdentityKey();
|
||||
|
||||
if (!identityKeyStore.isTrustedIdentity(remoteAddress, theirIdentityKey, IdentityKeyStore.Direction.RECEIVING)) {
|
||||
throw new UntrustedIdentityException(remoteAddress.getName(), theirIdentityKey);
|
||||
}
|
||||
|
||||
Optional<Integer> unsignedPreKeyId = processV3(sessionRecord, message);
|
||||
|
||||
identityKeyStore.saveIdentity(remoteAddress, theirIdentityKey);
|
||||
|
||||
return unsignedPreKeyId;
|
||||
}
|
||||
|
||||
private Optional<Integer> processV3(SessionRecord sessionRecord, PreKeySignalMessage message)
|
||||
throws UntrustedIdentityException, InvalidKeyIdException, InvalidKeyException
|
||||
{
|
||||
|
||||
if (sessionRecord.hasSessionState(message.getMessageVersion(), message.getBaseKey().serialize())) {
|
||||
Log.w(TAG, "We've already setup a session for this V3 message, letting bundled message fall through...");
|
||||
return Optional.absent();
|
||||
}
|
||||
|
||||
ECKeyPair ourSignedPreKey = signedPreKeyStore.loadSignedPreKey(message.getSignedPreKeyId()).getKeyPair();
|
||||
|
||||
BobSignalProtocolParameters.Builder parameters = BobSignalProtocolParameters.newBuilder();
|
||||
|
||||
parameters.setTheirBaseKey(message.getBaseKey())
|
||||
.setTheirIdentityKey(message.getIdentityKey())
|
||||
.setOurIdentityKey(identityKeyStore.getIdentityKeyPair())
|
||||
.setOurSignedPreKey(ourSignedPreKey)
|
||||
.setOurRatchetKey(ourSignedPreKey);
|
||||
|
||||
if (message.getPreKeyId().isPresent()) {
|
||||
parameters.setOurOneTimePreKey(Optional.of(preKeyStore.loadPreKey(message.getPreKeyId().get()).getKeyPair()));
|
||||
} else {
|
||||
parameters.setOurOneTimePreKey(Optional.<ECKeyPair>absent());
|
||||
}
|
||||
|
||||
if (!sessionRecord.isFresh()) sessionRecord.archiveCurrentState();
|
||||
|
||||
RatchetingSession.initializeSession(sessionRecord.getSessionState(), parameters.create());
|
||||
|
||||
sessionRecord.getSessionState().setLocalRegistrationId(identityKeyStore.getLocalRegistrationId());
|
||||
sessionRecord.getSessionState().setRemoteRegistrationId(message.getRegistrationId());
|
||||
sessionRecord.getSessionState().setAliceBaseKey(message.getBaseKey().serialize());
|
||||
|
||||
if (message.getPreKeyId().isPresent()) {
|
||||
return message.getPreKeyId();
|
||||
} else {
|
||||
return Optional.absent();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a new session from a {@link org.whispersystems.libsignal.state.PreKeyBundle} retrieved from
|
||||
* a server.
|
||||
*
|
||||
* @param preKey A PreKey for the destination recipient, retrieved from a server.
|
||||
* @throws InvalidKeyException when the {@link org.whispersystems.libsignal.state.PreKeyBundle} is
|
||||
* badly formatted.
|
||||
* @throws org.whispersystems.libsignal.UntrustedIdentityException when the sender's
|
||||
* {@link IdentityKey} is not
|
||||
* trusted.
|
||||
*/
|
||||
public void process(PreKeyBundle preKey) throws InvalidKeyException, UntrustedIdentityException {
|
||||
synchronized (SessionCipher.SESSION_LOCK) {
|
||||
if (!identityKeyStore.isTrustedIdentity(remoteAddress, preKey.getIdentityKey(), IdentityKeyStore.Direction.SENDING)) {
|
||||
throw new UntrustedIdentityException(remoteAddress.getName(), preKey.getIdentityKey());
|
||||
}
|
||||
|
||||
if (preKey.getSignedPreKey() != null &&
|
||||
!Curve.verifySignature(preKey.getIdentityKey().getPublicKey(),
|
||||
preKey.getSignedPreKey().serialize(),
|
||||
preKey.getSignedPreKeySignature()))
|
||||
{
|
||||
throw new InvalidKeyException("Invalid signature on device key!");
|
||||
}
|
||||
|
||||
if (preKey.getSignedPreKey() == null) {
|
||||
throw new InvalidKeyException("No signed prekey!");
|
||||
}
|
||||
|
||||
SessionRecord sessionRecord = sessionStore.loadSession(remoteAddress);
|
||||
ECKeyPair ourBaseKey = Curve.generateKeyPair();
|
||||
ECPublicKey theirSignedPreKey = preKey.getSignedPreKey();
|
||||
Optional<ECPublicKey> theirOneTimePreKey = Optional.fromNullable(preKey.getPreKey());
|
||||
Optional<Integer> theirOneTimePreKeyId = theirOneTimePreKey.isPresent() ? Optional.of(preKey.getPreKeyId()) :
|
||||
Optional.<Integer>absent();
|
||||
|
||||
AliceSignalProtocolParameters.Builder parameters = AliceSignalProtocolParameters.newBuilder();
|
||||
|
||||
parameters.setOurBaseKey(ourBaseKey)
|
||||
.setOurIdentityKey(identityKeyStore.getIdentityKeyPair())
|
||||
.setTheirIdentityKey(preKey.getIdentityKey())
|
||||
.setTheirSignedPreKey(theirSignedPreKey)
|
||||
.setTheirRatchetKey(theirSignedPreKey)
|
||||
.setTheirOneTimePreKey(theirOneTimePreKey);
|
||||
|
||||
if (!sessionRecord.isFresh()) sessionRecord.archiveCurrentState();
|
||||
|
||||
RatchetingSession.initializeSession(sessionRecord.getSessionState(), parameters.create());
|
||||
|
||||
sessionRecord.getSessionState().setUnacknowledgedPreKeyMessage(theirOneTimePreKeyId, preKey.getSignedPreKeyId(), ourBaseKey.getPublicKey());
|
||||
sessionRecord.getSessionState().setLocalRegistrationId(identityKeyStore.getLocalRegistrationId());
|
||||
sessionRecord.getSessionState().setRemoteRegistrationId(preKey.getRegistrationId());
|
||||
sessionRecord.getSessionState().setAliceBaseKey(ourBaseKey.getPublicKey().serialize());
|
||||
|
||||
identityKeyStore.saveIdentity(remoteAddress, preKey.getIdentityKey());
|
||||
sessionStore.storeSession(remoteAddress, sessionRecord);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,440 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
import org.whispersystems.libsignal.ecc.ECKeyPair;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.loki.FallbackSessionCipher;
|
||||
import org.whispersystems.libsignal.protocol.CiphertextMessage;
|
||||
import org.whispersystems.libsignal.protocol.PreKeySignalMessage;
|
||||
import org.whispersystems.libsignal.protocol.SignalMessage;
|
||||
import org.whispersystems.libsignal.ratchet.ChainKey;
|
||||
import org.whispersystems.libsignal.ratchet.MessageKeys;
|
||||
import org.whispersystems.libsignal.ratchet.RootKey;
|
||||
import org.whispersystems.libsignal.state.IdentityKeyStore;
|
||||
import org.whispersystems.libsignal.state.PreKeyStore;
|
||||
import org.whispersystems.libsignal.state.SessionRecord;
|
||||
import org.whispersystems.libsignal.state.SessionState;
|
||||
import org.whispersystems.libsignal.state.SessionStore;
|
||||
import org.whispersystems.libsignal.state.SignalProtocolStore;
|
||||
import org.whispersystems.libsignal.state.SignedPreKeyStore;
|
||||
import org.whispersystems.libsignal.util.Pair;
|
||||
import org.whispersystems.libsignal.util.guava.Optional;
|
||||
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.IllegalBlockSizeException;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import static org.whispersystems.libsignal.state.SessionState.UnacknowledgedPreKeyMessageItems;
|
||||
|
||||
/**
|
||||
* The main entry point for Signal Protocol encrypt/decrypt operations.
|
||||
*
|
||||
* Once a session has been established with {@link SessionBuilder},
|
||||
* this class can be used for all encrypt/decrypt operations within
|
||||
* that session.
|
||||
*
|
||||
* @author Moxie Marlinspike
|
||||
*/
|
||||
public class SessionCipher {
|
||||
|
||||
public static final Object SESSION_LOCK = new Object();
|
||||
|
||||
private final SessionStore sessionStore;
|
||||
private final IdentityKeyStore identityKeyStore;
|
||||
private final SessionBuilder sessionBuilder;
|
||||
private final PreKeyStore preKeyStore;
|
||||
private final SignalProtocolAddress remoteAddress;
|
||||
|
||||
/**
|
||||
* Construct a SessionCipher for encrypt/decrypt operations on a session.
|
||||
* In order to use SessionCipher, a session must have already been created
|
||||
* and stored using {@link SessionBuilder}.
|
||||
*
|
||||
* @param sessionStore The {@link SessionStore} that contains a session for this recipient.
|
||||
* @param remoteAddress The remote address that messages will be encrypted to or decrypted from.
|
||||
*/
|
||||
public SessionCipher(SessionStore sessionStore, PreKeyStore preKeyStore,
|
||||
SignedPreKeyStore signedPreKeyStore, IdentityKeyStore identityKeyStore,
|
||||
SignalProtocolAddress remoteAddress)
|
||||
{
|
||||
this.sessionStore = sessionStore;
|
||||
this.preKeyStore = preKeyStore;
|
||||
this.identityKeyStore = identityKeyStore;
|
||||
this.remoteAddress = remoteAddress;
|
||||
this.sessionBuilder = new SessionBuilder(sessionStore, preKeyStore, signedPreKeyStore,
|
||||
identityKeyStore, remoteAddress);
|
||||
}
|
||||
|
||||
public SessionCipher(SignalProtocolStore store, SignalProtocolAddress remoteAddress) {
|
||||
this(store, store, store, store, remoteAddress);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt a message.
|
||||
*
|
||||
* @param paddedMessage The plaintext message bytes, optionally padded to a constant multiple.
|
||||
* @return A ciphertext message encrypted to the recipient+device tuple.
|
||||
*/
|
||||
public CiphertextMessage encrypt(byte[] paddedMessage) throws UntrustedIdentityException {
|
||||
synchronized (SESSION_LOCK) {
|
||||
SessionRecord sessionRecord = sessionStore.loadSession(remoteAddress);
|
||||
SessionState sessionState = sessionRecord.getSessionState();
|
||||
ChainKey chainKey = sessionState.getSenderChainKey();
|
||||
MessageKeys messageKeys = chainKey.getMessageKeys();
|
||||
ECPublicKey senderEphemeral = sessionState.getSenderRatchetKey();
|
||||
int previousCounter = sessionState.getPreviousCounter();
|
||||
int sessionVersion = sessionState.getSessionVersion();
|
||||
|
||||
byte[] ciphertextBody = getCiphertext(messageKeys, paddedMessage);
|
||||
CiphertextMessage ciphertextMessage = new SignalMessage(sessionVersion, messageKeys.getMacKey(),
|
||||
senderEphemeral, chainKey.getIndex(),
|
||||
previousCounter, ciphertextBody,
|
||||
sessionState.getLocalIdentityKey(),
|
||||
sessionState.getRemoteIdentityKey());
|
||||
|
||||
if (sessionState.hasUnacknowledgedPreKeyMessage()) {
|
||||
UnacknowledgedPreKeyMessageItems items = sessionState.getUnacknowledgedPreKeyMessageItems();
|
||||
int localRegistrationId = sessionState.getLocalRegistrationId();
|
||||
|
||||
ciphertextMessage = new PreKeySignalMessage(sessionVersion, localRegistrationId, items.getPreKeyId(),
|
||||
items.getSignedPreKeyId(), items.getBaseKey(),
|
||||
sessionState.getLocalIdentityKey(),
|
||||
(SignalMessage) ciphertextMessage);
|
||||
}
|
||||
|
||||
sessionState.setSenderChainKey(chainKey.getNextChainKey());
|
||||
|
||||
if (!identityKeyStore.isTrustedIdentity(remoteAddress, sessionState.getRemoteIdentityKey(), IdentityKeyStore.Direction.SENDING)) {
|
||||
throw new UntrustedIdentityException(remoteAddress.getName(), sessionState.getRemoteIdentityKey());
|
||||
}
|
||||
|
||||
identityKeyStore.saveIdentity(remoteAddress, sessionState.getRemoteIdentityKey());
|
||||
sessionStore.storeSession(remoteAddress, sessionRecord);
|
||||
return ciphertextMessage;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt a message.
|
||||
*
|
||||
* @param ciphertext The {@link PreKeySignalMessage} to decrypt.
|
||||
*
|
||||
* @return The plaintext.
|
||||
* @throws InvalidMessageException if the input is not valid ciphertext.
|
||||
* @throws DuplicateMessageException if the input is a message that has already been received.
|
||||
* @throws LegacyMessageException if the input is a message formatted by a protocol version that
|
||||
* is no longer supported.
|
||||
* @throws InvalidKeyIdException when there is no local {@link org.whispersystems.libsignal.state.PreKeyRecord}
|
||||
* that corresponds to the PreKey ID in the message.
|
||||
* @throws InvalidKeyException when the message is formatted incorrectly.
|
||||
* @throws UntrustedIdentityException when the {@link IdentityKey} of the sender is untrusted.
|
||||
*/
|
||||
public byte[] decrypt(PreKeySignalMessage ciphertext)
|
||||
throws DuplicateMessageException, LegacyMessageException, InvalidMessageException,
|
||||
InvalidKeyIdException, InvalidKeyException, UntrustedIdentityException
|
||||
{
|
||||
return decrypt(ciphertext, new NullDecryptionCallback());
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt a message.
|
||||
*
|
||||
* @param ciphertext The {@link PreKeySignalMessage} to decrypt.
|
||||
* @param callback A callback that is triggered after decryption is complete,
|
||||
* but before the updated session state has been committed to the session
|
||||
* DB. This allows some implementations to store the committed plaintext
|
||||
* to a DB first, in case they are concerned with a crash happening between
|
||||
* the time the session state is updated but before they're able to store
|
||||
* the plaintext to disk.
|
||||
*
|
||||
* @return The plaintext.
|
||||
* @throws InvalidMessageException if the input is not valid ciphertext.
|
||||
* @throws DuplicateMessageException if the input is a message that has already been received.
|
||||
* @throws LegacyMessageException if the input is a message formatted by a protocol version that
|
||||
* is no longer supported.
|
||||
* @throws InvalidKeyIdException when there is no local {@link org.whispersystems.libsignal.state.PreKeyRecord}
|
||||
* that corresponds to the PreKey ID in the message.
|
||||
* @throws InvalidKeyException when the message is formatted incorrectly.
|
||||
* @throws UntrustedIdentityException when the {@link IdentityKey} of the sender is untrusted.
|
||||
*/
|
||||
public byte[] decrypt(PreKeySignalMessage ciphertext, DecryptionCallback callback)
|
||||
throws DuplicateMessageException, LegacyMessageException, InvalidMessageException,
|
||||
InvalidKeyIdException, InvalidKeyException, UntrustedIdentityException
|
||||
{
|
||||
synchronized (SESSION_LOCK) {
|
||||
SessionRecord sessionRecord = sessionStore.loadSession(remoteAddress);
|
||||
Optional<Integer> unsignedPreKeyId = sessionBuilder.process(sessionRecord, ciphertext);
|
||||
byte[] plaintext = decrypt(sessionRecord, ciphertext.getWhisperMessage());
|
||||
|
||||
callback.handlePlaintext(plaintext);
|
||||
|
||||
sessionStore.storeSession(remoteAddress, sessionRecord);
|
||||
|
||||
if (unsignedPreKeyId.isPresent()) {
|
||||
preKeyStore.removePreKey(unsignedPreKeyId.get());
|
||||
}
|
||||
|
||||
return plaintext;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt a message.
|
||||
*
|
||||
* @param ciphertext The {@link SignalMessage} to decrypt.
|
||||
*
|
||||
* @return The plaintext.
|
||||
* @throws InvalidMessageException if the input is not valid ciphertext.
|
||||
* @throws DuplicateMessageException if the input is a message that has already been received.
|
||||
* @throws LegacyMessageException if the input is a message formatted by a protocol version that
|
||||
* is no longer supported.
|
||||
* @throws NoSessionException if there is no established session for this contact.
|
||||
*/
|
||||
public byte[] decrypt(SignalMessage ciphertext)
|
||||
throws InvalidMessageException, DuplicateMessageException, LegacyMessageException,
|
||||
NoSessionException, UntrustedIdentityException
|
||||
{
|
||||
return decrypt(ciphertext, new NullDecryptionCallback());
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt a message.
|
||||
*
|
||||
* @param ciphertext The {@link SignalMessage} to decrypt.
|
||||
* @param callback A callback that is triggered after decryption is complete,
|
||||
* but before the updated session state has been committed to the session
|
||||
* DB. This allows some implementations to store the committed plaintext
|
||||
* to a DB first, in case they are concerned with a crash happening between
|
||||
* the time the session state is updated but before they're able to store
|
||||
* the plaintext to disk.
|
||||
*
|
||||
* @return The plaintext.
|
||||
* @throws InvalidMessageException if the input is not valid ciphertext.
|
||||
* @throws DuplicateMessageException if the input is a message that has already been received.
|
||||
* @throws LegacyMessageException if the input is a message formatted by a protocol version that
|
||||
* is no longer supported.
|
||||
* @throws NoSessionException if there is no established session for this contact.
|
||||
*/
|
||||
public byte[] decrypt(SignalMessage ciphertext, DecryptionCallback callback)
|
||||
throws InvalidMessageException, DuplicateMessageException, LegacyMessageException,
|
||||
NoSessionException, UntrustedIdentityException
|
||||
{
|
||||
synchronized (SESSION_LOCK) {
|
||||
|
||||
if (!sessionStore.containsSession(remoteAddress)) {
|
||||
throw new NoSessionException("No session for: " + remoteAddress);
|
||||
}
|
||||
|
||||
SessionRecord sessionRecord = sessionStore.loadSession(remoteAddress);
|
||||
byte[] plaintext = decrypt(sessionRecord, ciphertext);
|
||||
|
||||
if (!identityKeyStore.isTrustedIdentity(remoteAddress, sessionRecord.getSessionState().getRemoteIdentityKey(), IdentityKeyStore.Direction.RECEIVING)) {
|
||||
throw new UntrustedIdentityException(remoteAddress.getName(), sessionRecord.getSessionState().getRemoteIdentityKey());
|
||||
}
|
||||
|
||||
identityKeyStore.saveIdentity(remoteAddress, sessionRecord.getSessionState().getRemoteIdentityKey());
|
||||
|
||||
callback.handlePlaintext(plaintext);
|
||||
|
||||
sessionStore.storeSession(remoteAddress, sessionRecord);
|
||||
|
||||
return plaintext;
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] decrypt(SessionRecord sessionRecord, SignalMessage ciphertext)
|
||||
throws DuplicateMessageException, LegacyMessageException, InvalidMessageException
|
||||
{
|
||||
synchronized (SESSION_LOCK) {
|
||||
Iterator<SessionState> previousStates = sessionRecord.getPreviousSessionStates().iterator();
|
||||
List<Exception> exceptions = new LinkedList<Exception>();
|
||||
|
||||
try {
|
||||
SessionState sessionState = new SessionState(sessionRecord.getSessionState());
|
||||
byte[] plaintext = decrypt(sessionState, ciphertext);
|
||||
|
||||
sessionRecord.setState(sessionState);
|
||||
return plaintext;
|
||||
} catch (InvalidMessageException e) {
|
||||
exceptions.add(e);
|
||||
}
|
||||
|
||||
while (previousStates.hasNext()) {
|
||||
try {
|
||||
SessionState promotedState = new SessionState(previousStates.next());
|
||||
byte[] plaintext = decrypt(promotedState, ciphertext);
|
||||
|
||||
previousStates.remove();
|
||||
sessionRecord.promoteState(promotedState);
|
||||
|
||||
return plaintext;
|
||||
} catch (InvalidMessageException e) {
|
||||
exceptions.add(e);
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidMessageException("No valid sessions.", exceptions);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] decrypt(SessionState sessionState, SignalMessage ciphertextMessage)
|
||||
throws InvalidMessageException, DuplicateMessageException, LegacyMessageException
|
||||
{
|
||||
if (!sessionState.hasSenderChain()) {
|
||||
throw new InvalidMessageException("Uninitialized session!");
|
||||
}
|
||||
|
||||
if (ciphertextMessage.getMessageVersion() != sessionState.getSessionVersion()) {
|
||||
throw new InvalidMessageException(String.format("Message version %d, but session version %d",
|
||||
ciphertextMessage.getMessageVersion(),
|
||||
sessionState.getSessionVersion()));
|
||||
}
|
||||
|
||||
ECPublicKey theirEphemeral = ciphertextMessage.getSenderRatchetKey();
|
||||
int counter = ciphertextMessage.getCounter();
|
||||
ChainKey chainKey = getOrCreateChainKey(sessionState, theirEphemeral);
|
||||
MessageKeys messageKeys = getOrCreateMessageKeys(sessionState, theirEphemeral,
|
||||
chainKey, counter);
|
||||
|
||||
ciphertextMessage.verifyMac(sessionState.getRemoteIdentityKey(),
|
||||
sessionState.getLocalIdentityKey(),
|
||||
messageKeys.getMacKey());
|
||||
|
||||
byte[] plaintext = getPlaintext(messageKeys, ciphertextMessage.getBody());
|
||||
|
||||
sessionState.clearUnacknowledgedPreKeyMessage();
|
||||
|
||||
return plaintext;
|
||||
}
|
||||
|
||||
public int getRemoteRegistrationId() {
|
||||
synchronized (SESSION_LOCK) {
|
||||
SessionRecord record = sessionStore.loadSession(remoteAddress);
|
||||
return record.getSessionState().getRemoteRegistrationId();
|
||||
}
|
||||
}
|
||||
|
||||
public int getSessionVersion() {
|
||||
synchronized (SESSION_LOCK) {
|
||||
if (!sessionStore.containsSession(remoteAddress)) {
|
||||
// Loki - If we have no session then we must be using the FallbackSessionCipher
|
||||
return FallbackSessionCipher.getSessionVersion();
|
||||
}
|
||||
|
||||
SessionRecord record = sessionStore.loadSession(remoteAddress);
|
||||
return record.getSessionState().getSessionVersion();
|
||||
}
|
||||
}
|
||||
|
||||
private ChainKey getOrCreateChainKey(SessionState sessionState, ECPublicKey theirEphemeral)
|
||||
throws InvalidMessageException
|
||||
{
|
||||
try {
|
||||
if (sessionState.hasReceiverChain(theirEphemeral)) {
|
||||
return sessionState.getReceiverChainKey(theirEphemeral);
|
||||
} else {
|
||||
RootKey rootKey = sessionState.getRootKey();
|
||||
ECKeyPair ourEphemeral = sessionState.getSenderRatchetKeyPair();
|
||||
Pair<RootKey, ChainKey> receiverChain = rootKey.createChain(theirEphemeral, ourEphemeral);
|
||||
ECKeyPair ourNewEphemeral = Curve.generateKeyPair();
|
||||
Pair<RootKey, ChainKey> senderChain = receiverChain.first().createChain(theirEphemeral, ourNewEphemeral);
|
||||
|
||||
sessionState.setRootKey(senderChain.first());
|
||||
sessionState.addReceiverChain(theirEphemeral, receiverChain.second());
|
||||
sessionState.setPreviousCounter(Math.max(sessionState.getSenderChainKey().getIndex()-1, 0));
|
||||
sessionState.setSenderChain(ourNewEphemeral, senderChain.second());
|
||||
|
||||
return receiverChain.second();
|
||||
}
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private MessageKeys getOrCreateMessageKeys(SessionState sessionState,
|
||||
ECPublicKey theirEphemeral,
|
||||
ChainKey chainKey, int counter)
|
||||
throws InvalidMessageException, DuplicateMessageException
|
||||
{
|
||||
if (chainKey.getIndex() > counter) {
|
||||
if (sessionState.hasMessageKeys(theirEphemeral, counter)) {
|
||||
return sessionState.removeMessageKeys(theirEphemeral, counter);
|
||||
} else {
|
||||
throw new DuplicateMessageException("Received message with old counter: " +
|
||||
chainKey.getIndex() + " , " + counter);
|
||||
}
|
||||
}
|
||||
|
||||
if (counter - chainKey.getIndex() > 2000) {
|
||||
throw new InvalidMessageException("Over 2000 messages into the future!");
|
||||
}
|
||||
|
||||
while (chainKey.getIndex() < counter) {
|
||||
MessageKeys messageKeys = chainKey.getMessageKeys();
|
||||
sessionState.setMessageKeys(theirEphemeral, messageKeys);
|
||||
chainKey = chainKey.getNextChainKey();
|
||||
}
|
||||
|
||||
sessionState.setReceiverChainKey(theirEphemeral, chainKey.getNextChainKey());
|
||||
return chainKey.getMessageKeys();
|
||||
}
|
||||
|
||||
private byte[] getCiphertext(MessageKeys messageKeys, byte[] plaintext) {
|
||||
try {
|
||||
Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, messageKeys.getCipherKey(), messageKeys.getIv());
|
||||
return cipher.doFinal(plaintext);
|
||||
} catch (IllegalBlockSizeException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (BadPaddingException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] getPlaintext(MessageKeys messageKeys, byte[] cipherText)
|
||||
throws InvalidMessageException
|
||||
{
|
||||
try {
|
||||
Cipher cipher = getCipher(Cipher.DECRYPT_MODE, messageKeys.getCipherKey(), messageKeys.getIv());
|
||||
return cipher.doFinal(cipherText);
|
||||
} catch (IllegalBlockSizeException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
} catch (BadPaddingException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Cipher getCipher(int mode, SecretKeySpec key, IvParameterSpec iv) {
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||
cipher.init(mode, key, iv);
|
||||
return cipher;
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (NoSuchPaddingException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (java.security.InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (InvalidAlgorithmParameterException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static class NullDecryptionCallback implements DecryptionCallback {
|
||||
@Override
|
||||
public void handlePlaintext(byte[] plaintext) {}
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
public class SignalProtocolAddress {
|
||||
|
||||
private final String name;
|
||||
private final int deviceId;
|
||||
|
||||
public SignalProtocolAddress(String name, int deviceId) {
|
||||
this.name = name;
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getDeviceId() {
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return name + ":" + deviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (other == null) return false;
|
||||
if (!(other instanceof SignalProtocolAddress)) return false;
|
||||
|
||||
SignalProtocolAddress that = (SignalProtocolAddress)other;
|
||||
return this.name.equals(that.name) && this.deviceId == that.deviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return this.name.hashCode() ^ this.deviceId;
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
public class StaleKeyExchangeException extends Throwable {
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal;
|
||||
|
||||
public class UntrustedIdentityException extends Exception {
|
||||
|
||||
private final String name;
|
||||
private final IdentityKey key;
|
||||
|
||||
public UntrustedIdentityException(String name, IdentityKey key) {
|
||||
this.name = name;
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
public IdentityKey getUntrustedIdentity() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
package org.whispersystems.libsignal.devices;
|
||||
|
||||
import org.whispersystems.libsignal.util.ByteArrayComparator;
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
public class DeviceConsistencyCodeGenerator {
|
||||
|
||||
private static final int CODE_VERSION = 0;
|
||||
|
||||
public static String generateFor(DeviceConsistencyCommitment commitment,
|
||||
List<DeviceConsistencySignature> signatures)
|
||||
{
|
||||
try {
|
||||
ArrayList<DeviceConsistencySignature> sortedSignatures = new ArrayList<DeviceConsistencySignature>(signatures);
|
||||
Collections.sort(sortedSignatures, new SignatureComparator());
|
||||
|
||||
MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
|
||||
messageDigest.update(ByteUtil.shortToByteArray(CODE_VERSION));
|
||||
messageDigest.update(commitment.toByteArray());
|
||||
|
||||
for (DeviceConsistencySignature signature : sortedSignatures) {
|
||||
messageDigest.update(signature.getVrfOutput());
|
||||
}
|
||||
|
||||
byte[] hash = messageDigest.digest();
|
||||
|
||||
String digits = getEncodedChunk(hash, 0) + getEncodedChunk(hash, 5);
|
||||
return digits.substring(0, 6);
|
||||
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String getEncodedChunk(byte[] hash, int offset) {
|
||||
long chunk = ByteUtil.byteArray5ToLong(hash, offset) % 100000;
|
||||
return String.format("%05d", chunk);
|
||||
}
|
||||
|
||||
|
||||
private static class SignatureComparator extends ByteArrayComparator implements Comparator<DeviceConsistencySignature> {
|
||||
@Override
|
||||
public int compare(DeviceConsistencySignature first, DeviceConsistencySignature second) {
|
||||
return compare(first.getVrfOutput(), second.getVrfOutput());
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package org.whispersystems.libsignal.devices;
|
||||
|
||||
import org.whispersystems.libsignal.IdentityKey;
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
import org.whispersystems.libsignal.util.IdentityKeyComparator;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class DeviceConsistencyCommitment {
|
||||
|
||||
private static final String VERSION = "DeviceConsistencyCommitment_V0";
|
||||
|
||||
private final int generation;
|
||||
private final byte[] serialized;
|
||||
|
||||
public DeviceConsistencyCommitment(int generation, List<IdentityKey> identityKeys) {
|
||||
try {
|
||||
ArrayList<IdentityKey> sortedIdentityKeys = new ArrayList<IdentityKey>(identityKeys);
|
||||
Collections.sort(sortedIdentityKeys, new IdentityKeyComparator());
|
||||
|
||||
MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
|
||||
messageDigest.update(VERSION.getBytes());
|
||||
messageDigest.update(ByteUtil.intToByteArray(generation));
|
||||
|
||||
for (IdentityKey commitment : sortedIdentityKeys) {
|
||||
messageDigest.update(commitment.getPublicKey().serialize());
|
||||
}
|
||||
|
||||
this.generation = generation;
|
||||
this.serialized = messageDigest.digest();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] toByteArray() {
|
||||
return serialized;
|
||||
}
|
||||
|
||||
public int getGeneration() {
|
||||
return generation;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package org.whispersystems.libsignal.devices;
|
||||
|
||||
public class DeviceConsistencySignature {
|
||||
|
||||
private final byte[] signature;
|
||||
private final byte[] vrfOutput;
|
||||
|
||||
public DeviceConsistencySignature(byte[] signature, byte[] vrfOutput) {
|
||||
this.signature = signature;
|
||||
this.vrfOutput = vrfOutput;
|
||||
}
|
||||
|
||||
public byte[] getVrfOutput() {
|
||||
return vrfOutput;
|
||||
}
|
||||
|
||||
public byte[] getSignature() {
|
||||
return signature;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,144 @@
|
||||
/**
|
||||
* Copyright (C) 2013-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.ecc;
|
||||
|
||||
import org.whispersystems.curve25519.Curve25519;
|
||||
import org.whispersystems.curve25519.Curve25519KeyPair;
|
||||
import org.whispersystems.curve25519.VrfSignatureVerificationFailedException;
|
||||
import org.whispersystems.libsignal.InvalidKeyException;
|
||||
|
||||
import static org.whispersystems.curve25519.Curve25519.BEST;
|
||||
|
||||
public class Curve {
|
||||
|
||||
public static final int DJB_TYPE = 0x05;
|
||||
|
||||
public static boolean isNative() {
|
||||
return Curve25519.getInstance(BEST).isNative();
|
||||
}
|
||||
|
||||
public static ECKeyPair generateKeyPair(byte[] seed) {
|
||||
Curve25519KeyPair keyPair = Curve25519.getInstance(BEST).generateKeyPair(seed);
|
||||
return new ECKeyPair(new DjbECPublicKey(keyPair.getPublicKey()), new DjbECPrivateKey(keyPair.getPrivateKey()));
|
||||
}
|
||||
|
||||
public static ECKeyPair generateKeyPair() {
|
||||
Curve25519KeyPair keyPair = Curve25519.getInstance(BEST).generateKeyPair();
|
||||
return new ECKeyPair(new DjbECPublicKey(keyPair.getPublicKey()), new DjbECPrivateKey(keyPair.getPrivateKey()));
|
||||
}
|
||||
|
||||
public static ECPublicKey decodePoint(byte[] bytes, int offset)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
if (bytes == null || bytes.length - offset < 1) {
|
||||
throw new InvalidKeyException("No key type identifier");
|
||||
}
|
||||
|
||||
int type = bytes[offset] & 0xFF;
|
||||
|
||||
switch (type) {
|
||||
case Curve.DJB_TYPE:
|
||||
if (bytes.length - offset < 33) {
|
||||
throw new InvalidKeyException("Bad key length: " + bytes.length);
|
||||
}
|
||||
|
||||
byte[] keyBytes = new byte[32];
|
||||
System.arraycopy(bytes, offset+1, keyBytes, 0, keyBytes.length);
|
||||
return new DjbECPublicKey(keyBytes);
|
||||
default:
|
||||
throw new InvalidKeyException("Bad key type: " + type);
|
||||
}
|
||||
}
|
||||
|
||||
public static ECPrivateKey decodePrivatePoint(byte[] bytes) {
|
||||
return new DjbECPrivateKey(bytes);
|
||||
}
|
||||
|
||||
public static byte[] calculateAgreement(ECPublicKey publicKey, ECPrivateKey privateKey)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
if (publicKey == null) {
|
||||
throw new InvalidKeyException("public value is null");
|
||||
}
|
||||
|
||||
if (privateKey == null) {
|
||||
throw new InvalidKeyException("private value is null");
|
||||
}
|
||||
|
||||
if (publicKey.getType() != privateKey.getType()) {
|
||||
throw new InvalidKeyException("Public and private keys must be of the same type!");
|
||||
}
|
||||
|
||||
if (publicKey.getType() == DJB_TYPE) {
|
||||
return Curve25519.getInstance(BEST)
|
||||
.calculateAgreement(((DjbECPublicKey) publicKey).getPublicKey(),
|
||||
((DjbECPrivateKey) privateKey).getPrivateKey());
|
||||
} else {
|
||||
throw new InvalidKeyException("Unknown type: " + publicKey.getType());
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean verifySignature(ECPublicKey signingKey, byte[] message, byte[] signature)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
if (signingKey == null || message == null || signature == null) {
|
||||
throw new InvalidKeyException("Values must not be null");
|
||||
}
|
||||
|
||||
if (signingKey.getType() == DJB_TYPE) {
|
||||
return Curve25519.getInstance(BEST)
|
||||
.verifySignature(((DjbECPublicKey) signingKey).getPublicKey(), message, signature);
|
||||
} else {
|
||||
throw new InvalidKeyException("Unknown type: " + signingKey.getType());
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] calculateSignature(ECPrivateKey signingKey, byte[] message)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
if (signingKey == null || message == null) {
|
||||
throw new InvalidKeyException("Values must not be null");
|
||||
}
|
||||
|
||||
if (signingKey.getType() == DJB_TYPE) {
|
||||
return Curve25519.getInstance(BEST)
|
||||
.calculateSignature(((DjbECPrivateKey) signingKey).getPrivateKey(), message);
|
||||
} else {
|
||||
throw new InvalidKeyException("Unknown type: " + signingKey.getType());
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] calculateVrfSignature(ECPrivateKey signingKey, byte[] message)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
if (signingKey == null || message == null) {
|
||||
throw new InvalidKeyException("Values must not be null");
|
||||
}
|
||||
|
||||
if (signingKey.getType() == DJB_TYPE) {
|
||||
return Curve25519.getInstance(BEST)
|
||||
.calculateVrfSignature(((DjbECPrivateKey)signingKey).getPrivateKey(), message);
|
||||
} else {
|
||||
throw new InvalidKeyException("Unknown type: " + signingKey.getType());
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] verifyVrfSignature(ECPublicKey signingKey, byte[] message, byte[] signature)
|
||||
throws InvalidKeyException, VrfSignatureVerificationFailedException
|
||||
{
|
||||
if (signingKey == null || message == null || signature == null) {
|
||||
throw new InvalidKeyException("Values must not be null");
|
||||
}
|
||||
|
||||
if (signingKey.getType() == DJB_TYPE) {
|
||||
return Curve25519.getInstance(BEST)
|
||||
.verifyVrfSignature(((DjbECPublicKey) signingKey).getPublicKey(), message, signature);
|
||||
} else {
|
||||
throw new InvalidKeyException("Unknown type: " + signingKey.getType());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Copyright (C) 2013-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
|
||||
package org.whispersystems.libsignal.ecc;
|
||||
|
||||
public class DjbECPrivateKey implements ECPrivateKey {
|
||||
|
||||
private final byte[] privateKey;
|
||||
|
||||
public DjbECPrivateKey(byte[] privateKey) {
|
||||
this.privateKey = privateKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] serialize() {
|
||||
return privateKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getType() {
|
||||
return Curve.DJB_TYPE;
|
||||
}
|
||||
|
||||
public byte[] getPrivateKey() {
|
||||
return privateKey;
|
||||
}
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Copyright (C) 2013-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
|
||||
package org.whispersystems.libsignal.ecc;
|
||||
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class DjbECPublicKey implements ECPublicKey {
|
||||
|
||||
private final byte[] publicKey;
|
||||
|
||||
public DjbECPublicKey(byte[] publicKey) {
|
||||
this.publicKey = publicKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] serialize() {
|
||||
byte[] type = {Curve.DJB_TYPE};
|
||||
return ByteUtil.combine(type, publicKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getType() {
|
||||
return Curve.DJB_TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (other == null) return false;
|
||||
if (!(other instanceof DjbECPublicKey)) return false;
|
||||
|
||||
DjbECPublicKey that = (DjbECPublicKey)other;
|
||||
return Arrays.equals(this.publicKey, that.publicKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Arrays.hashCode(publicKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(ECPublicKey another) {
|
||||
return new BigInteger(publicKey).compareTo(new BigInteger(((DjbECPublicKey)another).publicKey));
|
||||
}
|
||||
|
||||
public byte[] getPublicKey() {
|
||||
return publicKey;
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Copyright (C) 2013-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.ecc;
|
||||
|
||||
public class ECKeyPair {
|
||||
|
||||
private final ECPublicKey publicKey;
|
||||
private final ECPrivateKey privateKey;
|
||||
|
||||
public ECKeyPair(ECPublicKey publicKey, ECPrivateKey privateKey) {
|
||||
this.publicKey = publicKey;
|
||||
this.privateKey = privateKey;
|
||||
}
|
||||
|
||||
public ECPublicKey getPublicKey() {
|
||||
return publicKey;
|
||||
}
|
||||
|
||||
public ECPrivateKey getPrivateKey() {
|
||||
return privateKey;
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Copyright (C) 2013-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
|
||||
package org.whispersystems.libsignal.ecc;
|
||||
|
||||
public interface ECPrivateKey {
|
||||
public byte[] serialize();
|
||||
public int getType();
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Copyright (C) 2013-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
|
||||
package org.whispersystems.libsignal.ecc;
|
||||
|
||||
public interface ECPublicKey extends Comparable<ECPublicKey> {
|
||||
|
||||
public static final int KEY_SIZE = 33;
|
||||
|
||||
public byte[] serialize();
|
||||
|
||||
public int getType();
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Copyright (C) 2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.fingerprint;
|
||||
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
|
||||
public class DisplayableFingerprint {
|
||||
|
||||
private final String localFingerprintNumbers;
|
||||
private final String remoteFingerprintNumbers;
|
||||
|
||||
DisplayableFingerprint(byte[] localFingerprint, byte[] remoteFingerprint)
|
||||
{
|
||||
this.localFingerprintNumbers = getDisplayStringFor(localFingerprint);
|
||||
this.remoteFingerprintNumbers = getDisplayStringFor(remoteFingerprint);
|
||||
}
|
||||
|
||||
public String getDisplayText() {
|
||||
if (localFingerprintNumbers.compareTo(remoteFingerprintNumbers) <= 0) {
|
||||
return localFingerprintNumbers + remoteFingerprintNumbers;
|
||||
} else {
|
||||
return remoteFingerprintNumbers + localFingerprintNumbers;
|
||||
}
|
||||
}
|
||||
|
||||
private String getDisplayStringFor(byte[] fingerprint) {
|
||||
return getEncodedChunk(fingerprint, 0) +
|
||||
getEncodedChunk(fingerprint, 5) +
|
||||
getEncodedChunk(fingerprint, 10) +
|
||||
getEncodedChunk(fingerprint, 15) +
|
||||
getEncodedChunk(fingerprint, 20) +
|
||||
getEncodedChunk(fingerprint, 25);
|
||||
}
|
||||
|
||||
private String getEncodedChunk(byte[] hash, int offset) {
|
||||
long chunk = ByteUtil.byteArray5ToLong(hash, offset) % 100000;
|
||||
return String.format("%05d", chunk);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Copyright (C) 2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.fingerprint;
|
||||
|
||||
public class Fingerprint {
|
||||
|
||||
private final DisplayableFingerprint displayableFingerprint;
|
||||
private final ScannableFingerprint scannableFingerprint;
|
||||
|
||||
public Fingerprint(DisplayableFingerprint displayableFingerprint,
|
||||
ScannableFingerprint scannableFingerprint)
|
||||
{
|
||||
this.displayableFingerprint = displayableFingerprint;
|
||||
this.scannableFingerprint = scannableFingerprint;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A text fingerprint that can be displayed and compared remotely.
|
||||
*/
|
||||
public DisplayableFingerprint getDisplayableFingerprint() {
|
||||
return displayableFingerprint;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A scannable fingerprint that can be scanned anc compared locally.
|
||||
*/
|
||||
public ScannableFingerprint getScannableFingerprint() {
|
||||
return scannableFingerprint;
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Copyright (C) 2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.fingerprint;
|
||||
|
||||
import org.whispersystems.libsignal.IdentityKey;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface FingerprintGenerator {
|
||||
public Fingerprint createFor(String localStableIdentifier, IdentityKey localIdentityKey,
|
||||
String remoteStableIdentifier, IdentityKey remoteIdentityKey);
|
||||
|
||||
public Fingerprint createFor(String localStableIdentifier, List<IdentityKey> localIdentityKey,
|
||||
String remoteStableIdentifier, List<IdentityKey> remoteIdentityKey);
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Copyright (C) 2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.fingerprint;
|
||||
|
||||
public class FingerprintIdentifierMismatchException extends Exception {
|
||||
|
||||
private final String localIdentifier;
|
||||
private final String remoteIdentifier;
|
||||
private final String scannedLocalIdentifier;
|
||||
private final String scannedRemoteIdentifier;
|
||||
|
||||
public FingerprintIdentifierMismatchException(String localIdentifier, String remoteIdentifier,
|
||||
String scannedLocalIdentifier, String scannedRemoteIdentifier)
|
||||
{
|
||||
this.localIdentifier = localIdentifier;
|
||||
this.remoteIdentifier = remoteIdentifier;
|
||||
this.scannedLocalIdentifier = scannedLocalIdentifier;
|
||||
this.scannedRemoteIdentifier = scannedRemoteIdentifier;
|
||||
}
|
||||
|
||||
public String getScannedRemoteIdentifier() {
|
||||
return scannedRemoteIdentifier;
|
||||
}
|
||||
|
||||
public String getScannedLocalIdentifier() {
|
||||
return scannedLocalIdentifier;
|
||||
}
|
||||
|
||||
public String getRemoteIdentifier() {
|
||||
return remoteIdentifier;
|
||||
}
|
||||
|
||||
public String getLocalIdentifier() {
|
||||
return localIdentifier;
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Copyright (C) 2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.fingerprint;
|
||||
|
||||
public class FingerprintParsingException extends Exception {
|
||||
|
||||
public FingerprintParsingException(Exception nested) {
|
||||
super(nested);
|
||||
}
|
||||
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Copyright (C) 2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.fingerprint;
|
||||
|
||||
public class FingerprintVersionMismatchException extends Exception {
|
||||
|
||||
private final int theirVersion;
|
||||
private final int ourVersion;
|
||||
|
||||
public FingerprintVersionMismatchException(int theirVersion, int ourVersion) {
|
||||
super();
|
||||
this.theirVersion = theirVersion;
|
||||
this.ourVersion = ourVersion;
|
||||
}
|
||||
|
||||
public int getTheirVersion() {
|
||||
return theirVersion;
|
||||
}
|
||||
|
||||
public int getOurVersion() {
|
||||
return ourVersion;
|
||||
}
|
||||
}
|
@ -0,0 +1,127 @@
|
||||
/**
|
||||
* Copyright (C) 2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.fingerprint;
|
||||
|
||||
import org.whispersystems.libsignal.IdentityKey;
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
import org.whispersystems.libsignal.util.IdentityKeyComparator;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class NumericFingerprintGenerator implements FingerprintGenerator {
|
||||
|
||||
private static final int FINGERPRINT_VERSION = 0;
|
||||
|
||||
private final int iterations;
|
||||
|
||||
/**
|
||||
* Construct a fingerprint generator for 60 digit numerics.
|
||||
*
|
||||
* @param iterations The number of internal iterations to perform in the process of
|
||||
* generating a fingerprint. This needs to be constant, and synchronized
|
||||
* across all clients.
|
||||
*
|
||||
* The higher the iteration count, the higher the security level:
|
||||
*
|
||||
* - 1024 ~ 109.7 bits
|
||||
* - 1400 > 110 bits
|
||||
* - 5200 > 112 bits
|
||||
*/
|
||||
public NumericFingerprintGenerator(int iterations) {
|
||||
this.iterations = iterations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a scannable and displayble fingerprint.
|
||||
*
|
||||
* @param localStableIdentifier The client's "stable" identifier.
|
||||
* @param localIdentityKey The client's identity key.
|
||||
* @param remoteStableIdentifier The remote party's "stable" identifier.
|
||||
* @param remoteIdentityKey The remote party's identity key.
|
||||
* @return A unique fingerprint for this conversation.
|
||||
*/
|
||||
@Override
|
||||
public Fingerprint createFor(String localStableIdentifier, final IdentityKey localIdentityKey,
|
||||
String remoteStableIdentifier, final IdentityKey remoteIdentityKey)
|
||||
{
|
||||
return createFor(localStableIdentifier,
|
||||
new LinkedList<IdentityKey>() {{
|
||||
add(localIdentityKey);
|
||||
}},
|
||||
remoteStableIdentifier,
|
||||
new LinkedList<IdentityKey>() {{
|
||||
add(remoteIdentityKey);
|
||||
}});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a scannable and displayble fingerprint for logical identities that have multiple
|
||||
* physical keys.
|
||||
*
|
||||
* Do not trust the output of this unless you've been through the device consistency process
|
||||
* for the provided localIdentityKeys.
|
||||
*
|
||||
* @param localStableIdentifier The client's "stable" identifier.
|
||||
* @param localIdentityKeys The client's collection of physical identity keys.
|
||||
* @param remoteStableIdentifier The remote party's "stable" identifier.
|
||||
* @param remoteIdentityKeys The remote party's collection of physical identity key.
|
||||
* @return A unique fingerprint for this conversation.
|
||||
*/
|
||||
public Fingerprint createFor(String localStableIdentifier, List<IdentityKey> localIdentityKeys,
|
||||
String remoteStableIdentifier, List<IdentityKey> remoteIdentityKeys)
|
||||
{
|
||||
byte[] localFingerprint = getFingerprint(iterations, localStableIdentifier, localIdentityKeys);
|
||||
byte[] remoteFingerprint = getFingerprint(iterations, remoteStableIdentifier, remoteIdentityKeys);
|
||||
|
||||
DisplayableFingerprint displayableFingerprint = new DisplayableFingerprint(localFingerprint,
|
||||
remoteFingerprint);
|
||||
|
||||
ScannableFingerprint scannableFingerprint = new ScannableFingerprint(localFingerprint,
|
||||
remoteFingerprint);
|
||||
|
||||
return new Fingerprint(displayableFingerprint, scannableFingerprint);
|
||||
}
|
||||
|
||||
private byte[] getFingerprint(int iterations, String 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.getBytes());
|
||||
|
||||
for (int i=0;i<iterations;i++) {
|
||||
digest.update(hash);
|
||||
hash = digest.digest(publicKey);
|
||||
}
|
||||
|
||||
return hash;
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] getLogicalKeyBytes(List<IdentityKey> identityKeys) {
|
||||
ArrayList<IdentityKey> sortedIdentityKeys = new ArrayList<IdentityKey>(identityKeys);
|
||||
Collections.sort(sortedIdentityKeys, new IdentityKeyComparator());
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
|
||||
for (IdentityKey identityKey : sortedIdentityKeys) {
|
||||
byte[] publicKeyBytes = identityKey.getPublicKey().serialize();
|
||||
baos.write(publicKeyBytes, 0, publicKeyBytes.length);
|
||||
}
|
||||
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Copyright (C) 2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.fingerprint;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
|
||||
import org.whispersystems.libsignal.fingerprint.FingerprintProtos.CombinedFingerprints;
|
||||
import org.whispersystems.libsignal.fingerprint.FingerprintProtos.LogicalFingerprint;
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
|
||||
public class ScannableFingerprint {
|
||||
|
||||
private static final int VERSION = 1;
|
||||
|
||||
private final CombinedFingerprints fingerprints;
|
||||
|
||||
ScannableFingerprint(byte[] localFingerprintData, byte[] remoteFingerprintData)
|
||||
{
|
||||
LogicalFingerprint localFingerprint = LogicalFingerprint.newBuilder()
|
||||
.setContent(ByteString.copyFrom(ByteUtil.trim(localFingerprintData, 32)))
|
||||
.build();
|
||||
|
||||
LogicalFingerprint remoteFingerprint = LogicalFingerprint.newBuilder()
|
||||
.setContent(ByteString.copyFrom(ByteUtil.trim(remoteFingerprintData, 32)))
|
||||
.build();
|
||||
|
||||
this.fingerprints = CombinedFingerprints.newBuilder()
|
||||
.setVersion(VERSION)
|
||||
.setLocalFingerprint(localFingerprint)
|
||||
.setRemoteFingerprint(remoteFingerprint)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A byte string to be displayed in a QR code.
|
||||
*/
|
||||
public byte[] getSerialized() {
|
||||
return fingerprints.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare a scanned QR code with what we expect.
|
||||
*
|
||||
* @param scannedFingerprintData The scanned data
|
||||
* @return True if matching, otehrwise false.
|
||||
* @throws FingerprintVersionMismatchException if the scanned fingerprint is the wrong version.
|
||||
*/
|
||||
public boolean compareTo(byte[] scannedFingerprintData)
|
||||
throws FingerprintVersionMismatchException,
|
||||
FingerprintParsingException
|
||||
{
|
||||
try {
|
||||
CombinedFingerprints scanned = CombinedFingerprints.parseFrom(scannedFingerprintData);
|
||||
|
||||
if (!scanned.hasRemoteFingerprint() || !scanned.hasLocalFingerprint() ||
|
||||
!scanned.hasVersion() || scanned.getVersion() != VERSION)
|
||||
{
|
||||
throw new FingerprintVersionMismatchException(scanned.getVersion(), VERSION);
|
||||
}
|
||||
|
||||
return MessageDigest.isEqual(fingerprints.getLocalFingerprint().getContent().toByteArray(), scanned.getRemoteFingerprint().getContent().toByteArray()) &&
|
||||
MessageDigest.isEqual(fingerprints.getRemoteFingerprint().getContent().toByteArray(), scanned.getLocalFingerprint().getContent().toByteArray());
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new FingerprintParsingException(e);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,228 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.groups;
|
||||
|
||||
import org.whispersystems.libsignal.DecryptionCallback;
|
||||
import org.whispersystems.libsignal.DuplicateMessageException;
|
||||
import org.whispersystems.libsignal.InvalidKeyIdException;
|
||||
import org.whispersystems.libsignal.InvalidMessageException;
|
||||
import org.whispersystems.libsignal.LegacyMessageException;
|
||||
import org.whispersystems.libsignal.NoSessionException;
|
||||
import org.whispersystems.libsignal.groups.ratchet.SenderChainKey;
|
||||
import org.whispersystems.libsignal.groups.ratchet.SenderMessageKey;
|
||||
import org.whispersystems.libsignal.groups.state.SenderKeyRecord;
|
||||
import org.whispersystems.libsignal.groups.state.SenderKeyState;
|
||||
import org.whispersystems.libsignal.groups.state.SenderKeyStore;
|
||||
import org.whispersystems.libsignal.protocol.SenderKeyMessage;
|
||||
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.IllegalBlockSizeException;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
/**
|
||||
* The main entry point for Signal Protocol group encrypt/decrypt operations.
|
||||
*
|
||||
* Once a session has been established with {@link org.whispersystems.libsignal.groups.GroupSessionBuilder}
|
||||
* and a {@link org.whispersystems.libsignal.protocol.SenderKeyDistributionMessage} has been
|
||||
* distributed to each member of the group, this class can be used for all subsequent encrypt/decrypt
|
||||
* operations within that session (ie: until group membership changes).
|
||||
*
|
||||
* @author Moxie Marlinspike
|
||||
*/
|
||||
public class GroupCipher {
|
||||
|
||||
static final Object LOCK = new Object();
|
||||
|
||||
private final SenderKeyStore senderKeyStore;
|
||||
private final SenderKeyName senderKeyId;
|
||||
|
||||
public GroupCipher(SenderKeyStore senderKeyStore, SenderKeyName senderKeyId) {
|
||||
this.senderKeyStore = senderKeyStore;
|
||||
this.senderKeyId = senderKeyId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt a message.
|
||||
*
|
||||
* @param paddedPlaintext The plaintext message bytes, optionally padded.
|
||||
* @return Ciphertext.
|
||||
* @throws NoSessionException
|
||||
*/
|
||||
public byte[] encrypt(byte[] paddedPlaintext) throws NoSessionException {
|
||||
synchronized (LOCK) {
|
||||
try {
|
||||
SenderKeyRecord record = senderKeyStore.loadSenderKey(senderKeyId);
|
||||
SenderKeyState senderKeyState = record.getSenderKeyState();
|
||||
SenderMessageKey senderKey = senderKeyState.getSenderChainKey().getSenderMessageKey();
|
||||
byte[] ciphertext = getCipherText(senderKey.getIv(), senderKey.getCipherKey(), paddedPlaintext);
|
||||
|
||||
SenderKeyMessage senderKeyMessage = new SenderKeyMessage(senderKeyState.getKeyId(),
|
||||
senderKey.getIteration(),
|
||||
ciphertext,
|
||||
senderKeyState.getSigningKeyPrivate());
|
||||
|
||||
senderKeyState.setSenderChainKey(senderKeyState.getSenderChainKey().getNext());
|
||||
|
||||
senderKeyStore.storeSenderKey(senderKeyId, record);
|
||||
|
||||
return senderKeyMessage.serialize();
|
||||
} catch (InvalidKeyIdException e) {
|
||||
throw new NoSessionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt a SenderKey group message.
|
||||
*
|
||||
* @param senderKeyMessageBytes The received ciphertext.
|
||||
* @return Plaintext
|
||||
* @throws LegacyMessageException
|
||||
* @throws InvalidMessageException
|
||||
* @throws DuplicateMessageException
|
||||
*/
|
||||
public byte[] decrypt(byte[] senderKeyMessageBytes)
|
||||
throws LegacyMessageException, DuplicateMessageException, InvalidMessageException, NoSessionException
|
||||
{
|
||||
return decrypt(senderKeyMessageBytes, new NullDecryptionCallback());
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt a SenderKey group message.
|
||||
*
|
||||
* @param senderKeyMessageBytes The received ciphertext.
|
||||
* @param callback A callback that is triggered after decryption is complete,
|
||||
* but before the updated session state has been committed to the session
|
||||
* DB. This allows some implementations to store the committed plaintext
|
||||
* to a DB first, in case they are concerned with a crash happening between
|
||||
* the time the session state is updated but before they're able to store
|
||||
* the plaintext to disk.
|
||||
* @return Plaintext
|
||||
* @throws LegacyMessageException
|
||||
* @throws InvalidMessageException
|
||||
* @throws DuplicateMessageException
|
||||
*/
|
||||
public byte[] decrypt(byte[] senderKeyMessageBytes, DecryptionCallback callback)
|
||||
throws LegacyMessageException, InvalidMessageException, DuplicateMessageException,
|
||||
NoSessionException
|
||||
{
|
||||
synchronized (LOCK) {
|
||||
try {
|
||||
SenderKeyRecord record = senderKeyStore.loadSenderKey(senderKeyId);
|
||||
|
||||
if (record.isEmpty()) {
|
||||
throw new NoSessionException("No sender key for: " + senderKeyId);
|
||||
}
|
||||
|
||||
SenderKeyMessage senderKeyMessage = new SenderKeyMessage(senderKeyMessageBytes);
|
||||
SenderKeyState senderKeyState = record.getSenderKeyState(senderKeyMessage.getKeyId());
|
||||
|
||||
senderKeyMessage.verifySignature(senderKeyState.getSigningKeyPublic());
|
||||
|
||||
SenderMessageKey senderKey = getSenderKey(senderKeyState, senderKeyMessage.getIteration());
|
||||
|
||||
byte[] plaintext = getPlainText(senderKey.getIv(), senderKey.getCipherKey(), senderKeyMessage.getCipherText());
|
||||
|
||||
callback.handlePlaintext(plaintext);
|
||||
|
||||
senderKeyStore.storeSenderKey(senderKeyId, record);
|
||||
|
||||
return plaintext;
|
||||
} catch (org.whispersystems.libsignal.InvalidKeyException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
} catch (InvalidKeyIdException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private SenderMessageKey getSenderKey(SenderKeyState senderKeyState, int iteration)
|
||||
throws DuplicateMessageException, InvalidMessageException
|
||||
{
|
||||
SenderChainKey senderChainKey = senderKeyState.getSenderChainKey();
|
||||
|
||||
if (senderChainKey.getIteration() > iteration) {
|
||||
if (senderKeyState.hasSenderMessageKey(iteration)) {
|
||||
return senderKeyState.removeSenderMessageKey(iteration);
|
||||
} else {
|
||||
throw new DuplicateMessageException("Received message with old counter: " +
|
||||
senderChainKey.getIteration() + " , " + iteration);
|
||||
}
|
||||
}
|
||||
|
||||
if (iteration - senderChainKey.getIteration() > 2000) {
|
||||
throw new InvalidMessageException("Over 2000 messages into the future!");
|
||||
}
|
||||
|
||||
while (senderChainKey.getIteration() < iteration) {
|
||||
senderKeyState.addSenderMessageKey(senderChainKey.getSenderMessageKey());
|
||||
senderChainKey = senderChainKey.getNext();
|
||||
}
|
||||
|
||||
senderKeyState.setSenderChainKey(senderChainKey.getNext());
|
||||
return senderChainKey.getSenderMessageKey();
|
||||
}
|
||||
|
||||
private byte[] getPlainText(byte[] iv, byte[] key, byte[] ciphertext)
|
||||
throws InvalidMessageException
|
||||
{
|
||||
try {
|
||||
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), ivParameterSpec);
|
||||
|
||||
return cipher.doFinal(ciphertext);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (NoSuchPaddingException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch(java.security.InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (InvalidAlgorithmParameterException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (IllegalBlockSizeException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
} catch (BadPaddingException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] getCipherText(byte[] iv, byte[] key, byte[] plaintext) {
|
||||
try {
|
||||
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||
|
||||
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), ivParameterSpec);
|
||||
|
||||
return cipher.doFinal(plaintext);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (NoSuchPaddingException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (InvalidAlgorithmParameterException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (IllegalBlockSizeException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (BadPaddingException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (java.security.InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static class NullDecryptionCallback implements DecryptionCallback {
|
||||
@Override
|
||||
public void handlePlaintext(byte[] plaintext) {}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.groups;
|
||||
|
||||
import org.whispersystems.libsignal.InvalidKeyException;
|
||||
import org.whispersystems.libsignal.InvalidKeyIdException;
|
||||
import org.whispersystems.libsignal.groups.state.SenderKeyRecord;
|
||||
import org.whispersystems.libsignal.groups.state.SenderKeyState;
|
||||
import org.whispersystems.libsignal.groups.state.SenderKeyStore;
|
||||
import org.whispersystems.libsignal.protocol.SenderKeyDistributionMessage;
|
||||
import org.whispersystems.libsignal.util.KeyHelper;
|
||||
|
||||
/**
|
||||
* GroupSessionBuilder is responsible for setting up group SenderKey encrypted sessions.
|
||||
*
|
||||
* Once a session has been established, {@link org.whispersystems.libsignal.groups.GroupCipher}
|
||||
* can be used to encrypt/decrypt messages in that session.
|
||||
* <p>
|
||||
* The built sessions are unidirectional: they can be used either for sending or for receiving,
|
||||
* but not both.
|
||||
*
|
||||
* Sessions are constructed per (groupId + senderId + deviceId) tuple. Remote logical users
|
||||
* are identified by their senderId, and each logical recipientId can have multiple physical
|
||||
* devices.
|
||||
*
|
||||
* @author Moxie Marlinspike
|
||||
*/
|
||||
|
||||
public class GroupSessionBuilder {
|
||||
|
||||
private final SenderKeyStore senderKeyStore;
|
||||
|
||||
public GroupSessionBuilder(SenderKeyStore senderKeyStore) {
|
||||
this.senderKeyStore = senderKeyStore;
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a group session for receiving messages from senderKeyName.
|
||||
*
|
||||
* @param senderKeyName The (groupId, senderId, deviceId) tuple associated with the SenderKeyDistributionMessage.
|
||||
* @param senderKeyDistributionMessage A received SenderKeyDistributionMessage.
|
||||
*/
|
||||
public void process(SenderKeyName senderKeyName, SenderKeyDistributionMessage senderKeyDistributionMessage) {
|
||||
synchronized (GroupCipher.LOCK) {
|
||||
SenderKeyRecord senderKeyRecord = senderKeyStore.loadSenderKey(senderKeyName);
|
||||
senderKeyRecord.addSenderKeyState(senderKeyDistributionMessage.getId(),
|
||||
senderKeyDistributionMessage.getIteration(),
|
||||
senderKeyDistributionMessage.getChainKey(),
|
||||
senderKeyDistributionMessage.getSignatureKey());
|
||||
senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a group session for sending messages.
|
||||
*
|
||||
* @param senderKeyName The (groupId, senderId, deviceId) tuple. In this case, 'senderId' should be the caller.
|
||||
* @return A SenderKeyDistributionMessage that is individually distributed to each member of the group.
|
||||
*/
|
||||
public SenderKeyDistributionMessage create(SenderKeyName senderKeyName) {
|
||||
synchronized (GroupCipher.LOCK) {
|
||||
try {
|
||||
SenderKeyRecord senderKeyRecord = senderKeyStore.loadSenderKey(senderKeyName);
|
||||
|
||||
if (senderKeyRecord.isEmpty()) {
|
||||
senderKeyRecord.setSenderKeyState(KeyHelper.generateSenderKeyId(),
|
||||
0,
|
||||
KeyHelper.generateSenderKey(),
|
||||
KeyHelper.generateSenderSigningKey());
|
||||
senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord);
|
||||
}
|
||||
|
||||
SenderKeyState state = senderKeyRecord.getSenderKeyState();
|
||||
|
||||
return new SenderKeyDistributionMessage(state.getKeyId(),
|
||||
state.getSenderChainKey().getIteration(),
|
||||
state.getSenderChainKey().getSeed(),
|
||||
state.getSigningKeyPublic());
|
||||
|
||||
} catch (InvalidKeyIdException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.groups;
|
||||
|
||||
import org.whispersystems.libsignal.SignalProtocolAddress;
|
||||
|
||||
/**
|
||||
* A representation of a (groupId + senderId + deviceId) tuple.
|
||||
*/
|
||||
public class SenderKeyName {
|
||||
|
||||
private final String groupId;
|
||||
private final SignalProtocolAddress sender;
|
||||
|
||||
public SenderKeyName(String groupId, SignalProtocolAddress sender) {
|
||||
this.groupId = groupId;
|
||||
this.sender = sender;
|
||||
}
|
||||
|
||||
public String getGroupId() {
|
||||
return groupId;
|
||||
}
|
||||
|
||||
public SignalProtocolAddress getSender() {
|
||||
return sender;
|
||||
}
|
||||
|
||||
public String serialize() {
|
||||
return groupId + "::" + sender.getName() + "::" + String.valueOf(sender.getDeviceId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (other == null) return false;
|
||||
if (!(other instanceof SenderKeyName)) return false;
|
||||
|
||||
SenderKeyName that = (SenderKeyName)other;
|
||||
|
||||
return
|
||||
this.groupId.equals(that.groupId) &&
|
||||
this.sender.equals(that.sender);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return this.groupId.hashCode() ^ this.sender.hashCode();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.groups.ratchet;
|
||||
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
/**
|
||||
* Each SenderKey is a "chain" of keys, each derived from the previous.
|
||||
*
|
||||
* At any given point in time, the state of a SenderKey can be represented
|
||||
* as the current chain key value, along with its iteration count. From there,
|
||||
* subsequent iterations can be derived, as well as individual message keys from
|
||||
* each chain key.
|
||||
*
|
||||
* @author Moxie Marlinspike
|
||||
*/
|
||||
public class SenderChainKey {
|
||||
|
||||
private static final byte[] MESSAGE_KEY_SEED = {0x01};
|
||||
private static final byte[] CHAIN_KEY_SEED = {0x02};
|
||||
|
||||
private final int iteration;
|
||||
private final byte[] chainKey;
|
||||
|
||||
public SenderChainKey(int iteration, byte[] chainKey) {
|
||||
this.iteration = iteration;
|
||||
this.chainKey = chainKey;
|
||||
}
|
||||
|
||||
public int getIteration() {
|
||||
return iteration;
|
||||
}
|
||||
|
||||
public SenderMessageKey getSenderMessageKey() {
|
||||
return new SenderMessageKey(iteration, getDerivative(MESSAGE_KEY_SEED, chainKey));
|
||||
}
|
||||
|
||||
public SenderChainKey getNext() {
|
||||
return new SenderChainKey(iteration + 1, getDerivative(CHAIN_KEY_SEED, chainKey));
|
||||
}
|
||||
|
||||
public byte[] getSeed() {
|
||||
return chainKey;
|
||||
}
|
||||
|
||||
private byte[] getDerivative(byte[] seed, byte[] key) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(key, "HmacSHA256"));
|
||||
|
||||
return mac.doFinal(seed);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
|
||||
package org.whispersystems.libsignal.groups.ratchet;
|
||||
|
||||
import org.whispersystems.libsignal.kdf.HKDFv3;
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
|
||||
/**
|
||||
* The final symmetric material (IV and Cipher Key) used for encrypting
|
||||
* individual SenderKey messages.
|
||||
*
|
||||
* @author Moxie Marlinspike
|
||||
*/
|
||||
public class SenderMessageKey {
|
||||
|
||||
private final int iteration;
|
||||
private final byte[] iv;
|
||||
private final byte[] cipherKey;
|
||||
private final byte[] seed;
|
||||
|
||||
public SenderMessageKey(int iteration, byte[] seed) {
|
||||
byte[] derivative = new HKDFv3().deriveSecrets(seed, "WhisperGroup".getBytes(), 48);
|
||||
byte[][] parts = ByteUtil.split(derivative, 16, 32);
|
||||
|
||||
this.iteration = iteration;
|
||||
this.seed = seed;
|
||||
this.iv = parts[0];
|
||||
this.cipherKey = parts[1];
|
||||
}
|
||||
|
||||
public int getIteration() {
|
||||
return iteration;
|
||||
}
|
||||
|
||||
public byte[] getIv() {
|
||||
return iv;
|
||||
}
|
||||
|
||||
public byte[] getCipherKey() {
|
||||
return cipherKey;
|
||||
}
|
||||
|
||||
public byte[] getSeed() {
|
||||
return seed;
|
||||
}
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.groups.state;
|
||||
|
||||
import org.whispersystems.libsignal.InvalidKeyIdException;
|
||||
import org.whispersystems.libsignal.ecc.ECKeyPair;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.state.StorageProtos;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.whispersystems.libsignal.state.StorageProtos.SenderKeyRecordStructure;
|
||||
|
||||
/**
|
||||
* A durable representation of a set of SenderKeyStates for a specific
|
||||
* SenderKeyName.
|
||||
*
|
||||
* @author Moxie Marlisnpike
|
||||
*/
|
||||
public class SenderKeyRecord {
|
||||
|
||||
private static final int MAX_STATES = 5;
|
||||
|
||||
private LinkedList<SenderKeyState> senderKeyStates = new LinkedList<SenderKeyState>();
|
||||
|
||||
public SenderKeyRecord() {}
|
||||
|
||||
public SenderKeyRecord(byte[] serialized) throws IOException {
|
||||
SenderKeyRecordStructure senderKeyRecordStructure = SenderKeyRecordStructure.parseFrom(serialized);
|
||||
|
||||
for (StorageProtos.SenderKeyStateStructure structure : senderKeyRecordStructure.getSenderKeyStatesList()) {
|
||||
this.senderKeyStates.add(new SenderKeyState(structure));
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return senderKeyStates.isEmpty();
|
||||
}
|
||||
|
||||
public SenderKeyState getSenderKeyState() throws InvalidKeyIdException {
|
||||
if (!senderKeyStates.isEmpty()) {
|
||||
return senderKeyStates.get(0);
|
||||
} else {
|
||||
throw new InvalidKeyIdException("No key state in record!");
|
||||
}
|
||||
}
|
||||
|
||||
public SenderKeyState getSenderKeyState(int keyId) throws InvalidKeyIdException {
|
||||
for (SenderKeyState state : senderKeyStates) {
|
||||
if (state.getKeyId() == keyId) {
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidKeyIdException("No keys for: " + keyId);
|
||||
}
|
||||
|
||||
public void addSenderKeyState(int id, int iteration, byte[] chainKey, ECPublicKey signatureKey) {
|
||||
senderKeyStates.addFirst(new SenderKeyState(id, iteration, chainKey, signatureKey));
|
||||
|
||||
if (senderKeyStates.size() > MAX_STATES) {
|
||||
senderKeyStates.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
public void setSenderKeyState(int id, int iteration, byte[] chainKey, ECKeyPair signatureKey) {
|
||||
senderKeyStates.clear();
|
||||
senderKeyStates.add(new SenderKeyState(id, iteration, chainKey, signatureKey));
|
||||
}
|
||||
|
||||
public byte[] serialize() {
|
||||
SenderKeyRecordStructure.Builder recordStructure = SenderKeyRecordStructure.newBuilder();
|
||||
|
||||
for (SenderKeyState senderKeyState : senderKeyStates) {
|
||||
recordStructure.addSenderKeyStates(senderKeyState.getStructure());
|
||||
}
|
||||
|
||||
return recordStructure.build().toByteArray();
|
||||
}
|
||||
}
|
@ -0,0 +1,162 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.groups.state;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
|
||||
import org.whispersystems.libsignal.InvalidKeyException;
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
import org.whispersystems.libsignal.ecc.ECKeyPair;
|
||||
import org.whispersystems.libsignal.ecc.ECPrivateKey;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.groups.ratchet.SenderChainKey;
|
||||
import org.whispersystems.libsignal.groups.ratchet.SenderMessageKey;
|
||||
import org.whispersystems.libsignal.util.guava.Optional;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.whispersystems.libsignal.state.StorageProtos.SenderKeyStateStructure;
|
||||
|
||||
/**
|
||||
* Represents the state of an individual SenderKey ratchet.
|
||||
*
|
||||
* @author Moxie Marlinspike
|
||||
*/
|
||||
public class SenderKeyState {
|
||||
|
||||
private static final int MAX_MESSAGE_KEYS = 2000;
|
||||
|
||||
private SenderKeyStateStructure senderKeyStateStructure;
|
||||
|
||||
public SenderKeyState(int id, int iteration, byte[] chainKey, ECPublicKey signatureKey) {
|
||||
this(id, iteration, chainKey, signatureKey, Optional.<ECPrivateKey>absent());
|
||||
}
|
||||
|
||||
public SenderKeyState(int id, int iteration, byte[] chainKey, ECKeyPair signatureKey) {
|
||||
this(id, iteration, chainKey, signatureKey.getPublicKey(), Optional.of(signatureKey.getPrivateKey()));
|
||||
}
|
||||
|
||||
private SenderKeyState(int id, int iteration, byte[] chainKey,
|
||||
ECPublicKey signatureKeyPublic,
|
||||
Optional<ECPrivateKey> signatureKeyPrivate)
|
||||
{
|
||||
SenderKeyStateStructure.SenderChainKey senderChainKeyStructure =
|
||||
SenderKeyStateStructure.SenderChainKey.newBuilder()
|
||||
.setIteration(iteration)
|
||||
.setSeed(ByteString.copyFrom(chainKey))
|
||||
.build();
|
||||
|
||||
SenderKeyStateStructure.SenderSigningKey.Builder signingKeyStructure =
|
||||
SenderKeyStateStructure.SenderSigningKey.newBuilder()
|
||||
.setPublic(ByteString.copyFrom(signatureKeyPublic.serialize()));
|
||||
|
||||
if (signatureKeyPrivate.isPresent()) {
|
||||
signingKeyStructure.setPrivate(ByteString.copyFrom(signatureKeyPrivate.get().serialize()));
|
||||
}
|
||||
|
||||
this.senderKeyStateStructure = SenderKeyStateStructure.newBuilder()
|
||||
.setSenderKeyId(id)
|
||||
.setSenderChainKey(senderChainKeyStructure)
|
||||
.setSenderSigningKey(signingKeyStructure)
|
||||
.build();
|
||||
}
|
||||
|
||||
public SenderKeyState(SenderKeyStateStructure senderKeyStateStructure) {
|
||||
this.senderKeyStateStructure = senderKeyStateStructure;
|
||||
}
|
||||
|
||||
public int getKeyId() {
|
||||
return senderKeyStateStructure.getSenderKeyId();
|
||||
}
|
||||
|
||||
public SenderChainKey getSenderChainKey() {
|
||||
return new SenderChainKey(senderKeyStateStructure.getSenderChainKey().getIteration(),
|
||||
senderKeyStateStructure.getSenderChainKey().getSeed().toByteArray());
|
||||
}
|
||||
|
||||
public void setSenderChainKey(SenderChainKey chainKey) {
|
||||
SenderKeyStateStructure.SenderChainKey senderChainKeyStructure =
|
||||
SenderKeyStateStructure.SenderChainKey.newBuilder()
|
||||
.setIteration(chainKey.getIteration())
|
||||
.setSeed(ByteString.copyFrom(chainKey.getSeed()))
|
||||
.build();
|
||||
|
||||
this.senderKeyStateStructure = senderKeyStateStructure.toBuilder()
|
||||
.setSenderChainKey(senderChainKeyStructure)
|
||||
.build();
|
||||
}
|
||||
|
||||
public ECPublicKey getSigningKeyPublic() throws InvalidKeyException {
|
||||
return Curve.decodePoint(senderKeyStateStructure.getSenderSigningKey()
|
||||
.getPublic()
|
||||
.toByteArray(), 0);
|
||||
}
|
||||
|
||||
public ECPrivateKey getSigningKeyPrivate() {
|
||||
return Curve.decodePrivatePoint(senderKeyStateStructure.getSenderSigningKey()
|
||||
.getPrivate().toByteArray());
|
||||
}
|
||||
|
||||
public boolean hasSenderMessageKey(int iteration) {
|
||||
for (SenderKeyStateStructure.SenderMessageKey senderMessageKey : senderKeyStateStructure.getSenderMessageKeysList()) {
|
||||
if (senderMessageKey.getIteration() == iteration) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public void addSenderMessageKey(SenderMessageKey senderMessageKey) {
|
||||
SenderKeyStateStructure.SenderMessageKey senderMessageKeyStructure =
|
||||
SenderKeyStateStructure.SenderMessageKey.newBuilder()
|
||||
.setIteration(senderMessageKey.getIteration())
|
||||
.setSeed(ByteString.copyFrom(senderMessageKey.getSeed()))
|
||||
.build();
|
||||
|
||||
SenderKeyStateStructure.Builder builder = this.senderKeyStateStructure.toBuilder();
|
||||
|
||||
builder.addSenderMessageKeys(senderMessageKeyStructure);
|
||||
|
||||
if (builder.getSenderMessageKeysCount() > MAX_MESSAGE_KEYS) {
|
||||
builder.removeSenderMessageKeys(0);
|
||||
}
|
||||
|
||||
this.senderKeyStateStructure = builder.build();
|
||||
}
|
||||
|
||||
public SenderMessageKey removeSenderMessageKey(int iteration) {
|
||||
List<SenderKeyStateStructure.SenderMessageKey> keys = new LinkedList<SenderKeyStateStructure.SenderMessageKey>(senderKeyStateStructure.getSenderMessageKeysList());
|
||||
Iterator<SenderKeyStateStructure.SenderMessageKey> iterator = keys.iterator();
|
||||
|
||||
SenderKeyStateStructure.SenderMessageKey result = null;
|
||||
|
||||
while (iterator.hasNext()) {
|
||||
SenderKeyStateStructure.SenderMessageKey senderMessageKey = iterator.next();
|
||||
|
||||
if (senderMessageKey.getIteration() == iteration) {
|
||||
result = senderMessageKey;
|
||||
iterator.remove();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
this.senderKeyStateStructure = this.senderKeyStateStructure.toBuilder()
|
||||
.clearSenderMessageKeys()
|
||||
.addAllSenderMessageKeys(keys)
|
||||
.build();
|
||||
|
||||
if (result != null) {
|
||||
return new SenderMessageKey(result.getIteration(), result.getSeed().toByteArray());
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public SenderKeyStateStructure getStructure() {
|
||||
return senderKeyStateStructure;
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.groups.state;
|
||||
|
||||
import org.whispersystems.libsignal.groups.SenderKeyName;
|
||||
|
||||
public interface SenderKeyStore {
|
||||
|
||||
/**
|
||||
* Commit to storage the {@link org.whispersystems.libsignal.groups.state.SenderKeyRecord} for a
|
||||
* given (groupId + senderId + deviceId) tuple.
|
||||
*
|
||||
* @param senderKeyName the (groupId + senderId + deviceId) tuple.
|
||||
* @param record the current SenderKeyRecord for the specified senderKeyName.
|
||||
*/
|
||||
public void storeSenderKey(SenderKeyName senderKeyName, SenderKeyRecord record);
|
||||
|
||||
/**
|
||||
* Returns a copy of the {@link org.whispersystems.libsignal.groups.state.SenderKeyRecord}
|
||||
* corresponding to the (groupId + senderId + deviceId) tuple, or a new SenderKeyRecord if
|
||||
* one does not currently exist.
|
||||
* <p>
|
||||
* It is important that implementations return a copy of the current durable information. The
|
||||
* returned SenderKeyRecord may be modified, but those changes should not have an effect on the
|
||||
* durable session state (what is returned by subsequent calls to this method) without the
|
||||
* store method being called here first.
|
||||
*
|
||||
* @param senderKeyName The (groupId + senderId + deviceId) tuple.
|
||||
* @return a copy of the SenderKeyRecord corresponding to the (groupId + senderId + deviceId tuple, or
|
||||
* a new SenderKeyRecord if one does not currently exist.
|
||||
*/
|
||||
|
||||
public SenderKeyRecord loadSenderKey(SenderKeyName senderKeyName);
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
|
||||
package org.whispersystems.libsignal.kdf;
|
||||
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
|
||||
import java.text.ParseException;
|
||||
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public class DerivedMessageSecrets {
|
||||
|
||||
public static final int SIZE = 80;
|
||||
private static final int CIPHER_KEY_LENGTH = 32;
|
||||
private static final int MAC_KEY_LENGTH = 32;
|
||||
private static final int IV_LENGTH = 16;
|
||||
|
||||
private final SecretKeySpec cipherKey;
|
||||
private final SecretKeySpec macKey;
|
||||
private final IvParameterSpec iv;
|
||||
|
||||
public DerivedMessageSecrets(byte[] okm) {
|
||||
try {
|
||||
byte[][] keys = ByteUtil.split(okm, CIPHER_KEY_LENGTH, MAC_KEY_LENGTH, IV_LENGTH);
|
||||
|
||||
this.cipherKey = new SecretKeySpec(keys[0], "AES");
|
||||
this.macKey = new SecretKeySpec(keys[1], "HmacSHA256");
|
||||
this.iv = new IvParameterSpec(keys[2]);
|
||||
} catch (ParseException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public SecretKeySpec getCipherKey() {
|
||||
return cipherKey;
|
||||
}
|
||||
|
||||
public SecretKeySpec getMacKey() {
|
||||
return macKey;
|
||||
}
|
||||
|
||||
public IvParameterSpec getIv() {
|
||||
return iv;
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.kdf;
|
||||
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
|
||||
public class DerivedRootSecrets {
|
||||
|
||||
public static final int SIZE = 64;
|
||||
|
||||
private final byte[] rootKey;
|
||||
private final byte[] chainKey;
|
||||
|
||||
public DerivedRootSecrets(byte[] okm) {
|
||||
byte[][] keys = ByteUtil.split(okm, 32, 32);
|
||||
this.rootKey = keys[0];
|
||||
this.chainKey = keys[1];
|
||||
}
|
||||
|
||||
public byte[] getRootKey() {
|
||||
return rootKey;
|
||||
}
|
||||
|
||||
public byte[] getChainKey() {
|
||||
return chainKey;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Copyright (C) 2013-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
|
||||
package org.whispersystems.libsignal.kdf;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public abstract class HKDF {
|
||||
|
||||
private static final int HASH_OUTPUT_SIZE = 32;
|
||||
|
||||
public static HKDF createFor(int messageVersion) {
|
||||
switch (messageVersion) {
|
||||
case 2: return new HKDFv2();
|
||||
case 3: return new HKDFv3();
|
||||
default: throw new AssertionError("Unknown version: " + messageVersion);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] deriveSecrets(byte[] inputKeyMaterial, byte[] info, int outputLength) {
|
||||
byte[] salt = new byte[HASH_OUTPUT_SIZE];
|
||||
return deriveSecrets(inputKeyMaterial, salt, info, outputLength);
|
||||
}
|
||||
|
||||
public byte[] deriveSecrets(byte[] inputKeyMaterial, byte[] salt, byte[] info, int outputLength) {
|
||||
byte[] prk = extract(salt, inputKeyMaterial);
|
||||
return expand(prk, info, outputLength);
|
||||
}
|
||||
|
||||
private byte[] extract(byte[] salt, byte[] inputKeyMaterial) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(salt, "HmacSHA256"));
|
||||
return mac.doFinal(inputKeyMaterial);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] expand(byte[] prk, byte[] info, int outputSize) {
|
||||
try {
|
||||
int iterations = (int) Math.ceil((double) outputSize / (double) HASH_OUTPUT_SIZE);
|
||||
byte[] mixin = new byte[0];
|
||||
ByteArrayOutputStream results = new ByteArrayOutputStream();
|
||||
int remainingBytes = outputSize;
|
||||
|
||||
for (int i= getIterationStartOffset();i<iterations + getIterationStartOffset();i++) {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(prk, "HmacSHA256"));
|
||||
|
||||
mac.update(mixin);
|
||||
if (info != null) {
|
||||
mac.update(info);
|
||||
}
|
||||
mac.update((byte)i);
|
||||
|
||||
byte[] stepResult = mac.doFinal();
|
||||
int stepSize = Math.min(remainingBytes, stepResult.length);
|
||||
|
||||
results.write(stepResult, 0, stepSize);
|
||||
|
||||
mixin = stepResult;
|
||||
remainingBytes -= stepSize;
|
||||
}
|
||||
|
||||
return results.toByteArray();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract int getIterationStartOffset();
|
||||
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.kdf;
|
||||
|
||||
public class HKDFv2 extends HKDF {
|
||||
@Override
|
||||
protected int getIterationStartOffset() {
|
||||
return 0;
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.kdf;
|
||||
|
||||
public class HKDFv3 extends HKDF {
|
||||
@Override
|
||||
protected int getIterationStartOffset() {
|
||||
return 1;
|
||||
}
|
||||
}
|
@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.logging;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
public class Log {
|
||||
|
||||
private Log() {}
|
||||
|
||||
public static void v(String tag, String msg) {
|
||||
log(SignalProtocolLogger.VERBOSE, tag, msg);
|
||||
}
|
||||
|
||||
public static void v(String tag, String msg, Throwable tr) {
|
||||
log(SignalProtocolLogger.VERBOSE, tag, msg + '\n' + getStackTraceString(tr));
|
||||
}
|
||||
|
||||
public static void d(String tag, String msg) {
|
||||
log(SignalProtocolLogger.DEBUG, tag, msg);
|
||||
}
|
||||
|
||||
public static void d(String tag, String msg, Throwable tr) {
|
||||
log(SignalProtocolLogger.DEBUG, tag, msg + '\n' + getStackTraceString(tr));
|
||||
}
|
||||
|
||||
public static void i(String tag, String msg) {
|
||||
log(SignalProtocolLogger.INFO, tag, msg);
|
||||
}
|
||||
|
||||
public static void i(String tag, String msg, Throwable tr) {
|
||||
log(SignalProtocolLogger.INFO, tag, msg + '\n' + getStackTraceString(tr));
|
||||
}
|
||||
|
||||
public static void w(String tag, String msg) {
|
||||
log(SignalProtocolLogger.WARN, tag, msg);
|
||||
}
|
||||
|
||||
public static void w(String tag, String msg, Throwable tr) {
|
||||
log(SignalProtocolLogger.WARN, tag, msg + '\n' + getStackTraceString(tr));
|
||||
}
|
||||
|
||||
public static void w(String tag, Throwable tr) {
|
||||
log(SignalProtocolLogger.WARN, tag, getStackTraceString(tr));
|
||||
}
|
||||
|
||||
public static void e(String tag, String msg) {
|
||||
log(SignalProtocolLogger.ERROR, tag, msg);
|
||||
}
|
||||
|
||||
public static void e(String tag, String msg, Throwable tr) {
|
||||
log(SignalProtocolLogger.ERROR, tag, msg + '\n' + getStackTraceString(tr));
|
||||
}
|
||||
|
||||
private static String getStackTraceString(Throwable tr) {
|
||||
if (tr == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// This is to reduce the amount of log spew that apps do in the non-error
|
||||
// condition of the network being unavailable.
|
||||
Throwable t = tr;
|
||||
while (t != null) {
|
||||
if (t instanceof UnknownHostException) {
|
||||
return "";
|
||||
}
|
||||
t = t.getCause();
|
||||
}
|
||||
|
||||
StringWriter sw = new StringWriter();
|
||||
PrintWriter pw = new PrintWriter(sw);
|
||||
tr.printStackTrace(pw);
|
||||
pw.flush();
|
||||
return sw.toString();
|
||||
}
|
||||
|
||||
private static void log(int priority, String tag, String msg) {
|
||||
SignalProtocolLogger logger = SignalProtocolLoggerProvider.getProvider();
|
||||
|
||||
if (logger != null) {
|
||||
logger.log(priority, tag, msg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.logging;
|
||||
|
||||
public interface SignalProtocolLogger {
|
||||
|
||||
public static final int VERBOSE = 2;
|
||||
public static final int DEBUG = 3;
|
||||
public static final int INFO = 4;
|
||||
public static final int WARN = 5;
|
||||
public static final int ERROR = 6;
|
||||
public static final int ASSERT = 7;
|
||||
|
||||
public void log(int priority, String tag, String message);
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.logging;
|
||||
|
||||
public class SignalProtocolLoggerProvider {
|
||||
|
||||
private static SignalProtocolLogger provider;
|
||||
|
||||
public static SignalProtocolLogger getProvider() {
|
||||
return provider;
|
||||
}
|
||||
|
||||
public static void setProvider(SignalProtocolLogger provider) {
|
||||
SignalProtocolLoggerProvider.provider = provider;
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package org.whispersystems.libsignal.loki
|
||||
|
||||
import com.google.protobuf.ByteString
|
||||
import org.whispersystems.libsignal.logging.Log
|
||||
import org.whispersystems.libsignal.protocol.CiphertextMessage
|
||||
import org.whispersystems.libsignal.protocol.SignalProtos
|
||||
|
||||
class ClosedGroupCiphertextMessage(val ivAndCiphertext: ByteArray, val senderPublicKey: ByteArray, val keyIndex: Int) : CiphertextMessage {
|
||||
private val serialized: ByteArray
|
||||
|
||||
companion object {
|
||||
|
||||
fun from(serialized: ByteArray): ClosedGroupCiphertextMessage? {
|
||||
try {
|
||||
val proto = SignalProtos.ClosedGroupCiphertextMessage.parseFrom(serialized)
|
||||
return ClosedGroupCiphertextMessage(proto.ciphertext.toByteArray(), proto.senderPublicKey.toByteArray(), proto.keyIndex)
|
||||
} catch (exception: Exception) {
|
||||
Log.d("Loki", "Couldn't parse proto due to error: $exception.")
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
val builder = SignalProtos.ClosedGroupCiphertextMessage.newBuilder()
|
||||
builder.ciphertext = ByteString.copyFrom(ivAndCiphertext)
|
||||
builder.senderPublicKey = ByteString.copyFrom(senderPublicKey)
|
||||
builder.keyIndex = keyIndex
|
||||
serialized = builder.build().toByteArray()
|
||||
}
|
||||
|
||||
override fun getType(): Int {
|
||||
return CiphertextMessage.CLOSED_GROUP_CIPHERTEXT
|
||||
}
|
||||
|
||||
override fun serialize(): ByteArray {
|
||||
return serialized
|
||||
}
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
package org.whispersystems.libsignal.loki
|
||||
|
||||
import org.whispersystems.curve25519.Curve25519
|
||||
import org.whispersystems.signalservice.internal.util.Util
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.spec.IvParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
object DiffieHellman {
|
||||
private val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
|
||||
private val curve = Curve25519.getInstance(Curve25519.BEST)
|
||||
private val ivSize = 16
|
||||
|
||||
@JvmStatic @Throws
|
||||
fun encrypt(plaintext: ByteArray, symmetricKey: ByteArray): ByteArray {
|
||||
val iv = Util.getSecretBytes(ivSize)
|
||||
val ivSpec = IvParameterSpec(iv)
|
||||
val secretKeySpec = SecretKeySpec(symmetricKey, "AES")
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivSpec)
|
||||
val ciphertext = cipher.doFinal(plaintext)
|
||||
return iv + ciphertext
|
||||
}
|
||||
|
||||
@JvmStatic @Throws
|
||||
fun encrypt(plaintext: ByteArray, publicKey: ByteArray, privateKey: ByteArray): ByteArray {
|
||||
val symmetricKey = curve.calculateAgreement(publicKey, privateKey)
|
||||
return encrypt(plaintext, symmetricKey)
|
||||
}
|
||||
|
||||
@JvmStatic @Throws
|
||||
fun decrypt(ivAndCiphertext: ByteArray, symmetricKey: ByteArray): ByteArray {
|
||||
val iv = ivAndCiphertext.sliceArray(0 until ivSize)
|
||||
val ciphertext = ivAndCiphertext.sliceArray(ivSize until ivAndCiphertext.size)
|
||||
val ivSpec = IvParameterSpec(iv)
|
||||
val secretKeySpec = SecretKeySpec(symmetricKey, "AES")
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivSpec)
|
||||
return cipher.doFinal(ciphertext)
|
||||
}
|
||||
|
||||
@JvmStatic @Throws
|
||||
fun decrypt(ivAndCiphertext: ByteArray, publicKey: ByteArray, privateKey: ByteArray): ByteArray {
|
||||
val symmetricKey = curve.calculateAgreement(publicKey, privateKey)
|
||||
return decrypt(ivAndCiphertext, symmetricKey)
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package org.whispersystems.libsignal.loki
|
||||
|
||||
import org.whispersystems.libsignal.protocol.CiphertextMessage
|
||||
|
||||
class FallbackMessage(private val paddedMessageBody: ByteArray) : CiphertextMessage {
|
||||
|
||||
override fun serialize(): ByteArray {
|
||||
return paddedMessageBody
|
||||
}
|
||||
|
||||
override fun getType(): Int {
|
||||
return CiphertextMessage.FALLBACK_MESSAGE_TYPE
|
||||
}
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package org.whispersystems.libsignal.loki
|
||||
|
||||
import org.whispersystems.curve25519.Curve25519
|
||||
import org.whispersystems.libsignal.util.Hex
|
||||
import org.whispersystems.signalservice.loki.utilities.removing05PrefixIfNeeded
|
||||
|
||||
/**
|
||||
* A session cipher that uses the current user's private key along with a contact's public key to encrypt data.
|
||||
*/
|
||||
class FallbackSessionCipher(private val userPrivateKey: ByteArray, private val hexEncodedContactPublicKey: String) {
|
||||
|
||||
private val contactPublicKey by lazy {
|
||||
val hexEncodedContactPublicKey = hexEncodedContactPublicKey.removing05PrefixIfNeeded()
|
||||
Hex.fromStringCondensed(hexEncodedContactPublicKey)
|
||||
}
|
||||
|
||||
private val symmetricKey: ByteArray?
|
||||
get() {
|
||||
try {
|
||||
val curve = Curve25519.getInstance(Curve25519.BEST)
|
||||
return curve.calculateAgreement(contactPublicKey, userPrivateKey)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmStatic val sessionVersion = 3
|
||||
}
|
||||
|
||||
fun encrypt(paddedMessageBody: ByteArray): ByteArray? {
|
||||
val symmetricKey = symmetricKey ?: return null
|
||||
try {
|
||||
return DiffieHellman.encrypt(paddedMessageBody, symmetricKey)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
fun decrypt(bytes: ByteArray): ByteArray? {
|
||||
val symmetricKey = symmetricKey ?: return null
|
||||
try {
|
||||
return DiffieHellman.decrypt(bytes, symmetricKey)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,78 @@
|
||||
package org.whispersystems.libsignal.loki
|
||||
|
||||
import org.whispersystems.libsignal.DecryptionCallback
|
||||
import org.whispersystems.libsignal.SessionCipher
|
||||
import org.whispersystems.libsignal.SignalProtocolAddress
|
||||
import org.whispersystems.libsignal.protocol.PreKeySignalMessage
|
||||
import org.whispersystems.libsignal.protocol.SignalMessage
|
||||
import org.whispersystems.libsignal.state.SessionState
|
||||
import org.whispersystems.libsignal.state.SignalProtocolStore
|
||||
|
||||
/**
|
||||
* A wrapper class for `SessionCipher`.
|
||||
* This applies session reset logic on decryption.
|
||||
*/
|
||||
class LokiSessionCipher(private val protocolStore: SignalProtocolStore, private var sessionResetProtocol: SessionResetProtocol, val address: SignalProtocolAddress) : SessionCipher(protocolStore, address) {
|
||||
|
||||
override fun decrypt(ciphertext: PreKeySignalMessage?, callback: DecryptionCallback?): ByteArray {
|
||||
// Record the current session state as it may change during decryption
|
||||
val activeSession = getCurrentSessionState()
|
||||
if (activeSession == null && ciphertext != null) {
|
||||
sessionResetProtocol.validatePreKeySignalMessage(address.name, ciphertext)
|
||||
}
|
||||
val plainText = super.decrypt(ciphertext, callback)
|
||||
handleSessionResetRequestIfNeeded(activeSession)
|
||||
return plainText
|
||||
}
|
||||
|
||||
override fun decrypt(ciphertext: SignalMessage?, callback: DecryptionCallback?): ByteArray {
|
||||
// Record the current session state as it may change during decryption
|
||||
val activeSession = getCurrentSessionState()
|
||||
val plainText = super.decrypt(ciphertext, callback)
|
||||
handleSessionResetRequestIfNeeded(activeSession)
|
||||
return plainText
|
||||
}
|
||||
|
||||
private fun getCurrentSessionState(): SessionState? {
|
||||
val sessionRecord = protocolStore.loadSession(address)
|
||||
return sessionRecord.sessionState
|
||||
}
|
||||
|
||||
private fun handleSessionResetRequestIfNeeded(oldSession: SessionState?) {
|
||||
if (oldSession == null) { return }
|
||||
val publicKey = address.name
|
||||
val currentSessionResetStatus = sessionResetProtocol.getSessionResetStatus(publicKey)
|
||||
if (currentSessionResetStatus == SessionResetStatus.NONE) return
|
||||
val currentSession = getCurrentSessionState()
|
||||
if (currentSession == null || currentSession.aliceBaseKey?.contentEquals(oldSession.aliceBaseKey) != true) {
|
||||
if (currentSessionResetStatus == SessionResetStatus.REQUEST_RECEIVED) {
|
||||
// The other user used an old session to contact us; wait for them to switch to a new one.
|
||||
restoreSession(oldSession)
|
||||
} else {
|
||||
// Our session reset was successful; we initiated one and got a new session back from the other user.
|
||||
deleteAllSessionsExcept(currentSession)
|
||||
sessionResetProtocol.setSessionResetStatus(publicKey, SessionResetStatus.NONE)
|
||||
sessionResetProtocol.onNewSessionAdopted(publicKey, currentSessionResetStatus)
|
||||
}
|
||||
} else if (currentSessionResetStatus == SessionResetStatus.REQUEST_RECEIVED) {
|
||||
// Our session reset was successful; we received a message with the same session from the other user.
|
||||
deleteAllSessionsExcept(oldSession)
|
||||
sessionResetProtocol.setSessionResetStatus(publicKey, SessionResetStatus.NONE)
|
||||
sessionResetProtocol.onNewSessionAdopted(publicKey, currentSessionResetStatus)
|
||||
}
|
||||
}
|
||||
|
||||
private fun restoreSession(state: SessionState) {
|
||||
val session = protocolStore.loadSession(address)
|
||||
session.previousSessionStates.removeAll { it.aliceBaseKey?.contentEquals(state.aliceBaseKey) ?: false }
|
||||
session.promoteState(state)
|
||||
protocolStore.storeSession(address, session)
|
||||
}
|
||||
|
||||
private fun deleteAllSessionsExcept(state: SessionState?) {
|
||||
val sessionRecord = protocolStore.loadSession(address)
|
||||
sessionRecord.removePreviousSessionStates()
|
||||
sessionRecord.setState(state ?: SessionState())
|
||||
protocolStore.storeSession(address, sessionRecord)
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package org.whispersystems.libsignal.loki
|
||||
|
||||
import org.whispersystems.libsignal.protocol.PreKeySignalMessage
|
||||
|
||||
interface SessionResetProtocol {
|
||||
|
||||
fun getSessionResetStatus(publicKey: String): SessionResetStatus
|
||||
fun setSessionResetStatus(publicKey: String, sessionResetStatus: SessionResetStatus)
|
||||
fun validatePreKeySignalMessage(publicKey: String, message: PreKeySignalMessage)
|
||||
fun onNewSessionAdopted(publicKey: String, oldSessionResetStatus: SessionResetStatus)
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package org.whispersystems.libsignal.loki
|
||||
|
||||
enum class SessionResetStatus(val rawValue: Int) {
|
||||
NONE(0),
|
||||
IN_PROGRESS(1),
|
||||
REQUEST_RECEIVED(2)
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
* <p>
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.protocol;
|
||||
|
||||
public interface CiphertextMessage {
|
||||
|
||||
public static final int CURRENT_VERSION = 3;
|
||||
|
||||
public static final int WHISPER_TYPE = 2;
|
||||
public static final int PREKEY_TYPE = 3;
|
||||
public static final int SENDERKEY_TYPE = 4;
|
||||
public static final int SENDERKEY_DISTRIBUTION_TYPE = 5;
|
||||
public static final int CLOSED_GROUP_CIPHERTEXT = 6;
|
||||
public static final int FALLBACK_MESSAGE_TYPE = 999; // Loki
|
||||
|
||||
// This should be the worst case (worse than V2). So not always accurate, but good enough for padding.
|
||||
public static final int ENCRYPTED_MESSAGE_OVERHEAD = 53;
|
||||
|
||||
public byte[] serialize();
|
||||
|
||||
public int getType();
|
||||
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
package org.whispersystems.libsignal.protocol;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
|
||||
import org.whispersystems.curve25519.VrfSignatureVerificationFailedException;
|
||||
import org.whispersystems.libsignal.IdentityKey;
|
||||
import org.whispersystems.libsignal.IdentityKeyPair;
|
||||
import org.whispersystems.libsignal.InvalidKeyException;
|
||||
import org.whispersystems.libsignal.InvalidMessageException;
|
||||
import org.whispersystems.libsignal.devices.DeviceConsistencyCommitment;
|
||||
import org.whispersystems.libsignal.devices.DeviceConsistencySignature;
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
|
||||
public class DeviceConsistencyMessage {
|
||||
|
||||
private final DeviceConsistencySignature signature;
|
||||
private final int generation;
|
||||
private final byte[] serialized;
|
||||
|
||||
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 e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (VrfSignatureVerificationFailedException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public DeviceConsistencyMessage(DeviceConsistencyCommitment commitment, byte[] serialized, IdentityKey identityKey) throws InvalidMessageException {
|
||||
try {
|
||||
SignalProtos.DeviceConsistencyCodeMessage message = SignalProtos.DeviceConsistencyCodeMessage.parseFrom(serialized);
|
||||
byte[] vrfOutputBytes = Curve.verifyVrfSignature(identityKey.getPublicKey(), commitment.toByteArray(), message.getSignature().toByteArray());
|
||||
|
||||
this.generation = message.getGeneration();
|
||||
this.signature = new DeviceConsistencySignature(message.getSignature().toByteArray(), vrfOutputBytes);
|
||||
this.serialized = serialized;
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
} catch (VrfSignatureVerificationFailedException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] getSerialized() {
|
||||
return serialized;
|
||||
}
|
||||
|
||||
public DeviceConsistencySignature getSignature() {
|
||||
return signature;
|
||||
}
|
||||
|
||||
public int getGeneration() {
|
||||
return generation;
|
||||
}
|
||||
}
|
@ -0,0 +1,143 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.protocol;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
|
||||
import org.whispersystems.libsignal.IdentityKey;
|
||||
import org.whispersystems.libsignal.InvalidKeyException;
|
||||
import org.whispersystems.libsignal.InvalidMessageException;
|
||||
import org.whispersystems.libsignal.InvalidVersionException;
|
||||
import org.whispersystems.libsignal.LegacyMessageException;
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
import org.whispersystems.libsignal.util.guava.Optional;
|
||||
|
||||
|
||||
public class PreKeySignalMessage implements CiphertextMessage {
|
||||
|
||||
private final int version;
|
||||
private final int registrationId;
|
||||
private final Optional<Integer> preKeyId;
|
||||
private final int signedPreKeyId;
|
||||
private final ECPublicKey baseKey;
|
||||
private final IdentityKey identityKey;
|
||||
private final SignalMessage message;
|
||||
private final byte[] serialized;
|
||||
|
||||
public PreKeySignalMessage(byte[] serialized)
|
||||
throws InvalidMessageException, InvalidVersionException
|
||||
{
|
||||
try {
|
||||
this.version = ByteUtil.highBitsToInt(serialized[0]);
|
||||
|
||||
if (this.version > CiphertextMessage.CURRENT_VERSION) {
|
||||
throw new InvalidVersionException("Unknown version: " + this.version);
|
||||
}
|
||||
|
||||
if (this.version < CiphertextMessage.CURRENT_VERSION) {
|
||||
throw new LegacyMessageException("Legacy version: " + this.version);
|
||||
}
|
||||
|
||||
SignalProtos.PreKeySignalMessage preKeyWhisperMessage
|
||||
= SignalProtos.PreKeySignalMessage.parseFrom(ByteString.copyFrom(serialized, 1,
|
||||
serialized.length-1));
|
||||
|
||||
if (!preKeyWhisperMessage.hasSignedPreKeyId() ||
|
||||
!preKeyWhisperMessage.hasBaseKey() ||
|
||||
!preKeyWhisperMessage.hasIdentityKey() ||
|
||||
!preKeyWhisperMessage.hasMessage())
|
||||
{
|
||||
throw new InvalidMessageException("Incomplete message.");
|
||||
}
|
||||
|
||||
this.serialized = serialized;
|
||||
this.registrationId = preKeyWhisperMessage.getRegistrationId();
|
||||
this.preKeyId = preKeyWhisperMessage.hasPreKeyId() ? Optional.of(preKeyWhisperMessage.getPreKeyId()) : Optional.<Integer>absent();
|
||||
this.signedPreKeyId = preKeyWhisperMessage.hasSignedPreKeyId() ? preKeyWhisperMessage.getSignedPreKeyId() : -1;
|
||||
this.baseKey = Curve.decodePoint(preKeyWhisperMessage.getBaseKey().toByteArray(), 0);
|
||||
this.identityKey = new IdentityKey(Curve.decodePoint(preKeyWhisperMessage.getIdentityKey().toByteArray(), 0));
|
||||
this.message = new SignalMessage(preKeyWhisperMessage.getMessage().toByteArray());
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
} catch (LegacyMessageException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public int getMessageVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public IdentityKey getIdentityKey() {
|
||||
return identityKey;
|
||||
}
|
||||
|
||||
public int getRegistrationId() {
|
||||
return registrationId;
|
||||
}
|
||||
|
||||
public Optional<Integer> getPreKeyId() {
|
||||
return preKeyId;
|
||||
}
|
||||
|
||||
public int getSignedPreKeyId() {
|
||||
return signedPreKeyId;
|
||||
}
|
||||
|
||||
public ECPublicKey getBaseKey() {
|
||||
return baseKey;
|
||||
}
|
||||
|
||||
public SignalMessage getWhisperMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] serialize() {
|
||||
return serialized;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getType() {
|
||||
return CiphertextMessage.PREKEY_TYPE;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,103 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.protocol;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
|
||||
import org.whispersystems.libsignal.InvalidKeyException;
|
||||
import org.whispersystems.libsignal.InvalidMessageException;
|
||||
import org.whispersystems.libsignal.LegacyMessageException;
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
|
||||
public class SenderKeyDistributionMessage implements CiphertextMessage {
|
||||
|
||||
private final int id;
|
||||
private final int iteration;
|
||||
private final byte[] chainKey;
|
||||
private final ECPublicKey signatureKey;
|
||||
private final byte[] serialized;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public SenderKeyDistributionMessage(byte[] serialized) throws LegacyMessageException, InvalidMessageException {
|
||||
try {
|
||||
byte[][] messageParts = ByteUtil.split(serialized, 1, serialized.length - 1);
|
||||
byte version = messageParts[0][0];
|
||||
byte[] message = messageParts[1];
|
||||
|
||||
if (ByteUtil.highBitsToInt(version) < CiphertextMessage.CURRENT_VERSION) {
|
||||
throw new LegacyMessageException("Legacy message: " + ByteUtil.highBitsToInt(version));
|
||||
}
|
||||
|
||||
if (ByteUtil.highBitsToInt(version) > CURRENT_VERSION) {
|
||||
throw new InvalidMessageException("Unknown version: " + ByteUtil.highBitsToInt(version));
|
||||
}
|
||||
|
||||
SignalProtos.SenderKeyDistributionMessage distributionMessage = SignalProtos.SenderKeyDistributionMessage.parseFrom(message);
|
||||
|
||||
if (!distributionMessage.hasId() ||
|
||||
!distributionMessage.hasIteration() ||
|
||||
!distributionMessage.hasChainKey() ||
|
||||
!distributionMessage.hasSigningKey())
|
||||
{
|
||||
throw new InvalidMessageException("Incomplete message.");
|
||||
}
|
||||
|
||||
this.serialized = serialized;
|
||||
this.id = distributionMessage.getId();
|
||||
this.iteration = distributionMessage.getIteration();
|
||||
this.chainKey = distributionMessage.getChainKey().toByteArray();
|
||||
this.signatureKey = Curve.decodePoint(distributionMessage.getSigningKey().toByteArray(), 0);
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] serialize() {
|
||||
return serialized;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getType() {
|
||||
return SENDERKEY_DISTRIBUTION_TYPE;
|
||||
}
|
||||
|
||||
public int getIteration() {
|
||||
return iteration;
|
||||
}
|
||||
|
||||
public byte[] getChainKey() {
|
||||
return chainKey;
|
||||
}
|
||||
|
||||
public ECPublicKey getSignatureKey() {
|
||||
return signatureKey;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
@ -0,0 +1,128 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.protocol;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
|
||||
import org.whispersystems.libsignal.InvalidKeyException;
|
||||
import org.whispersystems.libsignal.InvalidMessageException;
|
||||
import org.whispersystems.libsignal.LegacyMessageException;
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
import org.whispersystems.libsignal.ecc.ECPrivateKey;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
|
||||
import java.text.ParseException;
|
||||
|
||||
public class SenderKeyMessage implements CiphertextMessage {
|
||||
|
||||
private static final int SIGNATURE_LENGTH = 64;
|
||||
|
||||
private final int messageVersion;
|
||||
private final int keyId;
|
||||
private final int iteration;
|
||||
private final byte[] ciphertext;
|
||||
private final byte[] serialized;
|
||||
|
||||
public SenderKeyMessage(byte[] serialized) throws InvalidMessageException, LegacyMessageException {
|
||||
try {
|
||||
byte[][] messageParts = ByteUtil.split(serialized, 1, serialized.length - 1 - SIGNATURE_LENGTH, SIGNATURE_LENGTH);
|
||||
byte version = messageParts[0][0];
|
||||
byte[] message = messageParts[1];
|
||||
byte[] signature = messageParts[2];
|
||||
|
||||
if (ByteUtil.highBitsToInt(version) < 3) {
|
||||
throw new LegacyMessageException("Legacy message: " + ByteUtil.highBitsToInt(version));
|
||||
}
|
||||
|
||||
if (ByteUtil.highBitsToInt(version) > CURRENT_VERSION) {
|
||||
throw new InvalidMessageException("Unknown version: " + ByteUtil.highBitsToInt(version));
|
||||
}
|
||||
|
||||
SignalProtos.SenderKeyMessage senderKeyMessage = SignalProtos.SenderKeyMessage.parseFrom(message);
|
||||
|
||||
if (!senderKeyMessage.hasId() ||
|
||||
!senderKeyMessage.hasIteration() ||
|
||||
!senderKeyMessage.hasCiphertext())
|
||||
{
|
||||
throw new InvalidMessageException("Incomplete message.");
|
||||
}
|
||||
|
||||
this.serialized = serialized;
|
||||
this.messageVersion = ByteUtil.highBitsToInt(version);
|
||||
this.keyId = senderKeyMessage.getId();
|
||||
this.iteration = senderKeyMessage.getIteration();
|
||||
this.ciphertext = senderKeyMessage.getCiphertext().toByteArray();
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
} catch (ParseException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public int getKeyId() {
|
||||
return keyId;
|
||||
}
|
||||
|
||||
public int getIteration() {
|
||||
return iteration;
|
||||
}
|
||||
|
||||
public byte[] getCipherText() {
|
||||
return ciphertext;
|
||||
}
|
||||
|
||||
public void verifySignature(ECPublicKey signatureKey)
|
||||
throws InvalidMessageException
|
||||
{
|
||||
try {
|
||||
byte[][] parts = ByteUtil.split(serialized, serialized.length - SIGNATURE_LENGTH, SIGNATURE_LENGTH);
|
||||
|
||||
if (!Curve.verifySignature(signatureKey, parts[0], parts[1])) {
|
||||
throw new InvalidMessageException("Invalid signature!");
|
||||
}
|
||||
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] getSignature(ECPrivateKey signatureKey, byte[] serialized) {
|
||||
try {
|
||||
return Curve.calculateSignature(signatureKey, serialized);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] serialize() {
|
||||
return serialized;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getType() {
|
||||
return CiphertextMessage.SENDERKEY_TYPE;
|
||||
}
|
||||
}
|
@ -0,0 +1,162 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.protocol;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
|
||||
import org.whispersystems.libsignal.IdentityKey;
|
||||
import org.whispersystems.libsignal.InvalidKeyException;
|
||||
import org.whispersystems.libsignal.InvalidMessageException;
|
||||
import org.whispersystems.libsignal.LegacyMessageException;
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.text.ParseException;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public class SignalMessage implements CiphertextMessage {
|
||||
|
||||
private static final int MAC_LENGTH = 8;
|
||||
|
||||
private final int messageVersion;
|
||||
private final ECPublicKey senderRatchetKey;
|
||||
private final int counter;
|
||||
private final int previousCounter;
|
||||
private final byte[] ciphertext;
|
||||
private final byte[] serialized;
|
||||
|
||||
public SignalMessage(byte[] serialized) throws InvalidMessageException, LegacyMessageException {
|
||||
try {
|
||||
byte[][] messageParts = ByteUtil.split(serialized, 1, serialized.length - 1 - MAC_LENGTH, MAC_LENGTH);
|
||||
byte version = messageParts[0][0];
|
||||
byte[] message = messageParts[1];
|
||||
byte[] mac = messageParts[2];
|
||||
|
||||
if (ByteUtil.highBitsToInt(version) < CURRENT_VERSION) {
|
||||
throw new LegacyMessageException("Legacy message: " + ByteUtil.highBitsToInt(version));
|
||||
}
|
||||
|
||||
if (ByteUtil.highBitsToInt(version) > CURRENT_VERSION) {
|
||||
throw new InvalidMessageException("Unknown version: " + ByteUtil.highBitsToInt(version));
|
||||
}
|
||||
|
||||
SignalProtos.SignalMessage whisperMessage = SignalProtos.SignalMessage.parseFrom(message);
|
||||
|
||||
if (!whisperMessage.hasCiphertext() ||
|
||||
!whisperMessage.hasCounter() ||
|
||||
!whisperMessage.hasRatchetKey())
|
||||
{
|
||||
throw new InvalidMessageException("Incomplete message.");
|
||||
}
|
||||
|
||||
this.serialized = serialized;
|
||||
this.senderRatchetKey = Curve.decodePoint(whisperMessage.getRatchetKey().toByteArray(), 0);
|
||||
this.messageVersion = ByteUtil.highBitsToInt(version);
|
||||
this.counter = whisperMessage.getCounter();
|
||||
this.previousCounter = whisperMessage.getPreviousCounter();
|
||||
this.ciphertext = whisperMessage.getCiphertext().toByteArray();
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
} catch (ParseException e) {
|
||||
throw new InvalidMessageException(e);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public ECPublicKey getSenderRatchetKey() {
|
||||
return senderRatchetKey;
|
||||
}
|
||||
|
||||
public int getMessageVersion() {
|
||||
return messageVersion;
|
||||
}
|
||||
|
||||
public int getCounter() {
|
||||
return counter;
|
||||
}
|
||||
|
||||
public byte[] getBody() {
|
||||
return ciphertext;
|
||||
}
|
||||
|
||||
public void verifyMac(IdentityKey senderIdentityKey, IdentityKey receiverIdentityKey, SecretKeySpec macKey)
|
||||
throws InvalidMessageException
|
||||
{
|
||||
byte[][] parts = ByteUtil.split(serialized, serialized.length - MAC_LENGTH, MAC_LENGTH);
|
||||
byte[] ourMac = getMac(senderIdentityKey, receiverIdentityKey, macKey, parts[0]);
|
||||
byte[] theirMac = parts[1];
|
||||
|
||||
if (!MessageDigest.isEqual(ourMac, theirMac)) {
|
||||
throw new InvalidMessageException("Bad Mac!");
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] getMac(IdentityKey senderIdentityKey,
|
||||
IdentityKey receiverIdentityKey,
|
||||
SecretKeySpec macKey, byte[] serialized)
|
||||
{
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(macKey);
|
||||
|
||||
mac.update(senderIdentityKey.getPublicKey().serialize());
|
||||
mac.update(receiverIdentityKey.getPublicKey().serialize());
|
||||
|
||||
byte[] fullMac = mac.doFinal(serialized);
|
||||
return ByteUtil.trim(fullMac, MAC_LENGTH);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (java.security.InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] serialize() {
|
||||
return serialized;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getType() {
|
||||
return CiphertextMessage.WHISPER_TYPE;
|
||||
}
|
||||
|
||||
public static boolean isLegacy(byte[] message) {
|
||||
return message != null && message.length >= 1 &&
|
||||
ByteUtil.highBitsToInt(message[0]) != CiphertextMessage.CURRENT_VERSION;
|
||||
}
|
||||
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,114 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.ratchet;
|
||||
|
||||
import org.whispersystems.libsignal.IdentityKey;
|
||||
import org.whispersystems.libsignal.IdentityKeyPair;
|
||||
import org.whispersystems.libsignal.ecc.ECKeyPair;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.util.guava.Optional;
|
||||
|
||||
public class AliceSignalProtocolParameters {
|
||||
|
||||
private final IdentityKeyPair ourIdentityKey;
|
||||
private final ECKeyPair ourBaseKey;
|
||||
|
||||
private final IdentityKey theirIdentityKey;
|
||||
private final ECPublicKey theirSignedPreKey;
|
||||
private final Optional<ECPublicKey> theirOneTimePreKey;
|
||||
private final ECPublicKey theirRatchetKey;
|
||||
|
||||
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!");
|
||||
}
|
||||
}
|
||||
|
||||
public IdentityKeyPair getOurIdentityKey() {
|
||||
return ourIdentityKey;
|
||||
}
|
||||
|
||||
public ECKeyPair getOurBaseKey() {
|
||||
return ourBaseKey;
|
||||
}
|
||||
|
||||
public IdentityKey getTheirIdentityKey() {
|
||||
return theirIdentityKey;
|
||||
}
|
||||
|
||||
public ECPublicKey getTheirSignedPreKey() {
|
||||
return theirSignedPreKey;
|
||||
}
|
||||
|
||||
public Optional<ECPublicKey> getTheirOneTimePreKey() {
|
||||
return theirOneTimePreKey;
|
||||
}
|
||||
|
||||
public static Builder newBuilder() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
public ECPublicKey getTheirRatchetKey() {
|
||||
return theirRatchetKey;
|
||||
}
|
||||
|
||||
public static class Builder {
|
||||
private IdentityKeyPair ourIdentityKey;
|
||||
private ECKeyPair ourBaseKey;
|
||||
|
||||
private IdentityKey theirIdentityKey;
|
||||
private ECPublicKey theirSignedPreKey;
|
||||
private ECPublicKey theirRatchetKey;
|
||||
private Optional<ECPublicKey> theirOneTimePreKey;
|
||||
|
||||
public Builder setOurIdentityKey(IdentityKeyPair ourIdentityKey) {
|
||||
this.ourIdentityKey = ourIdentityKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setOurBaseKey(ECKeyPair ourBaseKey) {
|
||||
this.ourBaseKey = ourBaseKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setTheirRatchetKey(ECPublicKey theirRatchetKey) {
|
||||
this.theirRatchetKey = theirRatchetKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setTheirIdentityKey(IdentityKey theirIdentityKey) {
|
||||
this.theirIdentityKey = theirIdentityKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setTheirSignedPreKey(ECPublicKey theirSignedPreKey) {
|
||||
this.theirSignedPreKey = theirSignedPreKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setTheirOneTimePreKey(Optional<ECPublicKey> theirOneTimePreKey) {
|
||||
this.theirOneTimePreKey = theirOneTimePreKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AliceSignalProtocolParameters create() {
|
||||
return new AliceSignalProtocolParameters(ourIdentityKey, ourBaseKey, theirIdentityKey,
|
||||
theirSignedPreKey, theirRatchetKey, theirOneTimePreKey);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,114 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.ratchet;
|
||||
|
||||
import org.whispersystems.libsignal.IdentityKey;
|
||||
import org.whispersystems.libsignal.IdentityKeyPair;
|
||||
import org.whispersystems.libsignal.ecc.ECKeyPair;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.util.guava.Optional;
|
||||
|
||||
public class BobSignalProtocolParameters {
|
||||
|
||||
private final IdentityKeyPair ourIdentityKey;
|
||||
private final ECKeyPair ourSignedPreKey;
|
||||
private final Optional<ECKeyPair> ourOneTimePreKey;
|
||||
private final ECKeyPair ourRatchetKey;
|
||||
|
||||
private final IdentityKey theirIdentityKey;
|
||||
private final ECPublicKey theirBaseKey;
|
||||
|
||||
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!");
|
||||
}
|
||||
}
|
||||
|
||||
public IdentityKeyPair getOurIdentityKey() {
|
||||
return ourIdentityKey;
|
||||
}
|
||||
|
||||
public ECKeyPair getOurSignedPreKey() {
|
||||
return ourSignedPreKey;
|
||||
}
|
||||
|
||||
public Optional<ECKeyPair> getOurOneTimePreKey() {
|
||||
return ourOneTimePreKey;
|
||||
}
|
||||
|
||||
public IdentityKey getTheirIdentityKey() {
|
||||
return theirIdentityKey;
|
||||
}
|
||||
|
||||
public ECPublicKey getTheirBaseKey() {
|
||||
return theirBaseKey;
|
||||
}
|
||||
|
||||
public static Builder newBuilder() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
public ECKeyPair getOurRatchetKey() {
|
||||
return ourRatchetKey;
|
||||
}
|
||||
|
||||
public static class Builder {
|
||||
private IdentityKeyPair ourIdentityKey;
|
||||
private ECKeyPair ourSignedPreKey;
|
||||
private Optional<ECKeyPair> ourOneTimePreKey;
|
||||
private ECKeyPair ourRatchetKey;
|
||||
|
||||
private IdentityKey theirIdentityKey;
|
||||
private ECPublicKey theirBaseKey;
|
||||
|
||||
public Builder setOurIdentityKey(IdentityKeyPair ourIdentityKey) {
|
||||
this.ourIdentityKey = ourIdentityKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setOurSignedPreKey(ECKeyPair ourSignedPreKey) {
|
||||
this.ourSignedPreKey = ourSignedPreKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setOurOneTimePreKey(Optional<ECKeyPair> ourOneTimePreKey) {
|
||||
this.ourOneTimePreKey = ourOneTimePreKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setTheirIdentityKey(IdentityKey theirIdentityKey) {
|
||||
this.theirIdentityKey = theirIdentityKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setTheirBaseKey(ECPublicKey theirBaseKey) {
|
||||
this.theirBaseKey = theirBaseKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setOurRatchetKey(ECKeyPair ourRatchetKey) {
|
||||
this.ourRatchetKey = ourRatchetKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BobSignalProtocolParameters create() {
|
||||
return new BobSignalProtocolParameters(ourIdentityKey, ourSignedPreKey, ourRatchetKey,
|
||||
ourOneTimePreKey, theirIdentityKey, theirBaseKey);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.ratchet;
|
||||
|
||||
|
||||
import org.whispersystems.libsignal.kdf.DerivedMessageSecrets;
|
||||
import org.whispersystems.libsignal.kdf.HKDF;
|
||||
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public class ChainKey {
|
||||
|
||||
private static final byte[] MESSAGE_KEY_SEED = {0x01};
|
||||
private static final byte[] CHAIN_KEY_SEED = {0x02};
|
||||
|
||||
private final HKDF kdf;
|
||||
private final byte[] key;
|
||||
private final int index;
|
||||
|
||||
public ChainKey(HKDF kdf, byte[] key, int index) {
|
||||
this.kdf = kdf;
|
||||
this.key = key;
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
public byte[] getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public int getIndex() {
|
||||
return index;
|
||||
}
|
||||
|
||||
public ChainKey getNextChainKey() {
|
||||
byte[] nextKey = getBaseMaterial(CHAIN_KEY_SEED);
|
||||
return new ChainKey(kdf, nextKey, index + 1);
|
||||
}
|
||||
|
||||
public MessageKeys getMessageKeys() {
|
||||
byte[] inputKeyMaterial = getBaseMaterial(MESSAGE_KEY_SEED);
|
||||
byte[] keyMaterialBytes = kdf.deriveSecrets(inputKeyMaterial, "WhisperMessageKeys".getBytes(), DerivedMessageSecrets.SIZE);
|
||||
DerivedMessageSecrets keyMaterial = new DerivedMessageSecrets(keyMaterialBytes);
|
||||
|
||||
return new MessageKeys(keyMaterial.getCipherKey(), keyMaterial.getMacKey(), keyMaterial.getIv(), index);
|
||||
}
|
||||
|
||||
private byte[] getBaseMaterial(byte[] seed) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(key, "HmacSHA256"));
|
||||
|
||||
return mac.doFinal(seed);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.ratchet;
|
||||
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public class MessageKeys {
|
||||
|
||||
private final SecretKeySpec cipherKey;
|
||||
private final SecretKeySpec macKey;
|
||||
private final IvParameterSpec iv;
|
||||
private final int counter;
|
||||
|
||||
public MessageKeys(SecretKeySpec cipherKey, SecretKeySpec macKey, IvParameterSpec iv, int counter) {
|
||||
this.cipherKey = cipherKey;
|
||||
this.macKey = macKey;
|
||||
this.iv = iv;
|
||||
this.counter = counter;
|
||||
}
|
||||
|
||||
public SecretKeySpec getCipherKey() {
|
||||
return cipherKey;
|
||||
}
|
||||
|
||||
public SecretKeySpec getMacKey() {
|
||||
return macKey;
|
||||
}
|
||||
|
||||
public IvParameterSpec getIv() {
|
||||
return iv;
|
||||
}
|
||||
|
||||
public int getCounter() {
|
||||
return counter;
|
||||
}
|
||||
}
|
@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.ratchet;
|
||||
|
||||
import org.whispersystems.libsignal.InvalidKeyException;
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
import org.whispersystems.libsignal.ecc.ECKeyPair;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.kdf.HKDF;
|
||||
import org.whispersystems.libsignal.kdf.HKDFv3;
|
||||
import org.whispersystems.libsignal.protocol.CiphertextMessage;
|
||||
import org.whispersystems.libsignal.state.SessionState;
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
import org.whispersystems.libsignal.util.Pair;
|
||||
import org.whispersystems.libsignal.util.guava.Optional;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class RatchetingSession {
|
||||
|
||||
public static void initializeSession(SessionState sessionState, SymmetricSignalProtocolParameters parameters)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
if (isAlice(parameters.getOurBaseKey().getPublicKey(), parameters.getTheirBaseKey())) {
|
||||
AliceSignalProtocolParameters.Builder aliceParameters = AliceSignalProtocolParameters.newBuilder();
|
||||
|
||||
aliceParameters.setOurBaseKey(parameters.getOurBaseKey())
|
||||
.setOurIdentityKey(parameters.getOurIdentityKey())
|
||||
.setTheirRatchetKey(parameters.getTheirRatchetKey())
|
||||
.setTheirIdentityKey(parameters.getTheirIdentityKey())
|
||||
.setTheirSignedPreKey(parameters.getTheirBaseKey())
|
||||
.setTheirOneTimePreKey(Optional.<ECPublicKey>absent());
|
||||
|
||||
RatchetingSession.initializeSession(sessionState, aliceParameters.create());
|
||||
} else {
|
||||
BobSignalProtocolParameters.Builder bobParameters = BobSignalProtocolParameters.newBuilder();
|
||||
|
||||
bobParameters.setOurIdentityKey(parameters.getOurIdentityKey())
|
||||
.setOurRatchetKey(parameters.getOurRatchetKey())
|
||||
.setOurSignedPreKey(parameters.getOurBaseKey())
|
||||
.setOurOneTimePreKey(Optional.<ECKeyPair>absent())
|
||||
.setTheirBaseKey(parameters.getTheirBaseKey())
|
||||
.setTheirIdentityKey(parameters.getTheirIdentityKey());
|
||||
|
||||
RatchetingSession.initializeSession(sessionState, bobParameters.create());
|
||||
}
|
||||
}
|
||||
|
||||
public static void initializeSession(SessionState sessionState, AliceSignalProtocolParameters parameters)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
try {
|
||||
sessionState.setSessionVersion(CiphertextMessage.CURRENT_VERSION);
|
||||
sessionState.setRemoteIdentityKey(parameters.getTheirIdentityKey());
|
||||
sessionState.setLocalIdentityKey(parameters.getOurIdentityKey().getPublicKey());
|
||||
|
||||
ECKeyPair sendingRatchetKey = Curve.generateKeyPair();
|
||||
ByteArrayOutputStream secrets = new ByteArrayOutputStream();
|
||||
|
||||
secrets.write(getDiscontinuityBytes());
|
||||
|
||||
secrets.write(Curve.calculateAgreement(parameters.getTheirSignedPreKey(),
|
||||
parameters.getOurIdentityKey().getPrivateKey()));
|
||||
secrets.write(Curve.calculateAgreement(parameters.getTheirIdentityKey().getPublicKey(),
|
||||
parameters.getOurBaseKey().getPrivateKey()));
|
||||
secrets.write(Curve.calculateAgreement(parameters.getTheirSignedPreKey(),
|
||||
parameters.getOurBaseKey().getPrivateKey()));
|
||||
|
||||
if (parameters.getTheirOneTimePreKey().isPresent()) {
|
||||
secrets.write(Curve.calculateAgreement(parameters.getTheirOneTimePreKey().get(),
|
||||
parameters.getOurBaseKey().getPrivateKey()));
|
||||
}
|
||||
|
||||
DerivedKeys derivedKeys = calculateDerivedKeys(secrets.toByteArray());
|
||||
Pair<RootKey, ChainKey> sendingChain = derivedKeys.getRootKey().createChain(parameters.getTheirRatchetKey(), sendingRatchetKey);
|
||||
|
||||
sessionState.addReceiverChain(parameters.getTheirRatchetKey(), derivedKeys.getChainKey());
|
||||
sessionState.setSenderChain(sendingRatchetKey, sendingChain.second());
|
||||
sessionState.setRootKey(sendingChain.first());
|
||||
} catch (IOException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void initializeSession(SessionState sessionState, BobSignalProtocolParameters parameters)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
|
||||
try {
|
||||
sessionState.setSessionVersion(CiphertextMessage.CURRENT_VERSION);
|
||||
sessionState.setRemoteIdentityKey(parameters.getTheirIdentityKey());
|
||||
sessionState.setLocalIdentityKey(parameters.getOurIdentityKey().getPublicKey());
|
||||
|
||||
ByteArrayOutputStream secrets = new ByteArrayOutputStream();
|
||||
|
||||
secrets.write(getDiscontinuityBytes());
|
||||
|
||||
secrets.write(Curve.calculateAgreement(parameters.getTheirIdentityKey().getPublicKey(),
|
||||
parameters.getOurSignedPreKey().getPrivateKey()));
|
||||
secrets.write(Curve.calculateAgreement(parameters.getTheirBaseKey(),
|
||||
parameters.getOurIdentityKey().getPrivateKey()));
|
||||
secrets.write(Curve.calculateAgreement(parameters.getTheirBaseKey(),
|
||||
parameters.getOurSignedPreKey().getPrivateKey()));
|
||||
|
||||
if (parameters.getOurOneTimePreKey().isPresent()) {
|
||||
secrets.write(Curve.calculateAgreement(parameters.getTheirBaseKey(),
|
||||
parameters.getOurOneTimePreKey().get().getPrivateKey()));
|
||||
}
|
||||
|
||||
DerivedKeys derivedKeys = calculateDerivedKeys(secrets.toByteArray());
|
||||
|
||||
sessionState.setSenderChain(parameters.getOurRatchetKey(), derivedKeys.getChainKey());
|
||||
sessionState.setRootKey(derivedKeys.getRootKey());
|
||||
} catch (IOException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] getDiscontinuityBytes() {
|
||||
byte[] discontinuity = new byte[32];
|
||||
Arrays.fill(discontinuity, (byte) 0xFF);
|
||||
return discontinuity;
|
||||
}
|
||||
|
||||
private static DerivedKeys calculateDerivedKeys(byte[] masterSecret) {
|
||||
HKDF kdf = new HKDFv3();
|
||||
byte[] derivedSecretBytes = kdf.deriveSecrets(masterSecret, "WhisperText".getBytes(), 64);
|
||||
byte[][] derivedSecrets = ByteUtil.split(derivedSecretBytes, 32, 32);
|
||||
|
||||
return new DerivedKeys(new RootKey(kdf, derivedSecrets[0]),
|
||||
new ChainKey(kdf, derivedSecrets[1], 0));
|
||||
}
|
||||
|
||||
private static boolean isAlice(ECPublicKey ourKey, ECPublicKey theirKey) {
|
||||
return ourKey.compareTo(theirKey) < 0;
|
||||
}
|
||||
|
||||
private static class DerivedKeys {
|
||||
private final RootKey rootKey;
|
||||
private final ChainKey chainKey;
|
||||
|
||||
private DerivedKeys(RootKey rootKey, ChainKey chainKey) {
|
||||
this.rootKey = rootKey;
|
||||
this.chainKey = chainKey;
|
||||
}
|
||||
|
||||
public RootKey getRootKey() {
|
||||
return rootKey;
|
||||
}
|
||||
|
||||
public ChainKey getChainKey() {
|
||||
return chainKey;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
package org.whispersystems.libsignal.ratchet;
|
||||
|
||||
import org.whispersystems.libsignal.InvalidKeyException;
|
||||
import org.whispersystems.libsignal.ecc.Curve;
|
||||
import org.whispersystems.libsignal.ecc.ECKeyPair;
|
||||
import org.whispersystems.libsignal.ecc.ECPublicKey;
|
||||
import org.whispersystems.libsignal.kdf.DerivedRootSecrets;
|
||||
import org.whispersystems.libsignal.kdf.HKDF;
|
||||
import org.whispersystems.libsignal.util.ByteUtil;
|
||||
import org.whispersystems.libsignal.util.Pair;
|
||||
|
||||
public class RootKey {
|
||||
|
||||
private final HKDF kdf;
|
||||
private final byte[] key;
|
||||
|
||||
public RootKey(HKDF kdf, byte[] key) {
|
||||
this.kdf = kdf;
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
public byte[] getKeyBytes() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public Pair<RootKey, ChainKey> createChain(ECPublicKey theirRatchetKey, ECKeyPair ourRatchetKey)
|
||||
throws InvalidKeyException
|
||||
{
|
||||
byte[] sharedSecret = Curve.calculateAgreement(theirRatchetKey, ourRatchetKey.getPrivateKey());
|
||||
byte[] derivedSecretBytes = kdf.deriveSecrets(sharedSecret, key, "WhisperRatchet".getBytes(), DerivedRootSecrets.SIZE);
|
||||
DerivedRootSecrets derivedSecrets = new DerivedRootSecrets(derivedSecretBytes);
|
||||
|
||||
RootKey newRootKey = new RootKey(kdf, derivedSecrets.getRootKey());
|
||||
ChainKey newChainKey = new ChainKey(kdf, derivedSecrets.getChainKey(), 0);
|
||||
|
||||
return new Pair<RootKey, ChainKey>(newRootKey, newChainKey);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user