Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: encrypt partial updates (v2) #511

Merged
merged 10 commits into from
Jan 7, 2025
205 changes: 9 additions & 196 deletions android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,7 @@ private void download(
version,
sessionKey,
checksum,
this.publicKey,
manifest != null
);

Expand All @@ -373,26 +374,6 @@ private void download(
}
}

private String decryptChecksum(String checksum, String version)
throws IOException {
if (this.publicKey.isEmpty()) {
Log.e(CapacitorUpdater.TAG, "The public key is empty");
return checksum;
}
try {
byte[] checksumBytes = Base64.decode(checksum, Base64.DEFAULT);
PublicKey pKey = CryptoCipherV2.stringToPublicKey(this.publicKey);
byte[] decryptedChecksum = CryptoCipherV2.decryptRSA(checksumBytes, pKey);
// return Base64.encodeToString(decryptedChecksum, Base64.DEFAULT);
String result = Base64.encodeToString(decryptedChecksum, Base64.DEFAULT);
return result.replaceAll("\\s", ""); // Remove all whitespace, including newlines
} catch (GeneralSecurityException e) {
Log.e(TAG, "decryptChecksum fail: " + e.getMessage());
this.sendStats("decrypt_fail", version);
throw new IOException("Decryption failed: " + e.getMessage());
}
}

public Boolean finishDownload(
String id,
String dest,
Expand All @@ -412,12 +393,15 @@ public Boolean finishDownload(
if (!isManifest) {
String checksumDecrypted = Objects.requireNonNullElse(checksumRes, "");
if (!this.hasOldPrivateKeyPropertyInConfig && !sessionKey.isEmpty()) {
this.decryptFileV2(downloaded, sessionKey, version);
checksumDecrypted = this.decryptChecksum(checksumRes, version);
checksum = this.calcChecksumV2(downloaded);
CryptoCipherV2.decryptFile(downloaded, publicKey, sessionKey);
checksumDecrypted = CryptoCipherV2.decryptChecksum(
checksumRes,
publicKey
);
checksum = CryptoCipherV2.calcChecksum(downloaded);
} else {
this.decryptFile(downloaded, sessionKey, version);
checksum = this.calcChecksum(downloaded);
CryptoCipher.decryptFile(downloaded, privateKey, sessionKey, version);
checksum = CryptoCipher.calcChecksum(downloaded);
}
if (
(!checksumDecrypted.isEmpty() || !this.publicKey.isEmpty()) &&
Expand Down Expand Up @@ -517,177 +501,6 @@ private void setCurrentBundle(final File bundle) {
this.editor.commit();
}

private String calcChecksum(File file) {
final int BUFFER_SIZE = 1024 * 1024 * 5; // 5 MB buffer size
CRC32 crc = new CRC32();

try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = fis.read(buffer)) != -1) {
crc.update(buffer, 0, length);
}
return String.format("%08x", crc.getValue());
} catch (IOException e) {
System.err.println(
TAG + " Cannot calc checksum: " + file.getPath() + " " + e.getMessage()
);
return "";
}
}

private String calcChecksumV2(File file) {
final int BUFFER_SIZE = 1024 * 1024 * 5; // 5 MB buffer size
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (java.security.NoSuchAlgorithmException e) {
System.err.println(TAG + " SHA-256 algorithm not available");
return "";
}

try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = fis.read(buffer)) != -1) {
digest.update(buffer, 0, length);
}
byte[] hash = digest.digest();
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (IOException e) {
System.err.println(
TAG +
" Cannot calc checksum v2: " +
file.getPath() +
" " +
e.getMessage()
);
return "";
}
}

private void decryptFileV2(
final File file,
final String ivSessionKey,
final String version
) throws IOException {
// (str != null && !str.isEmpty())
if (
this.publicKey.isEmpty() ||
ivSessionKey == null ||
ivSessionKey.isEmpty() ||
ivSessionKey.split(":").length != 2
) {
Log.i(TAG, "Cannot found public key or sessionKey");
return;
}
if (!this.publicKey.startsWith("-----BEGIN RSA PUBLIC KEY-----")) {
Log.e(
CapacitorUpdater.TAG,
"The public key is not a valid RSA Public key"
);
return;
}
try {
String ivB64 = ivSessionKey.split(":")[0];
String sessionKeyB64 = ivSessionKey.split(":")[1];
byte[] iv = Base64.decode(ivB64.getBytes(), Base64.DEFAULT);
byte[] sessionKey = Base64.decode(
sessionKeyB64.getBytes(),
Base64.DEFAULT
);
PublicKey pKey = CryptoCipherV2.stringToPublicKey(this.publicKey);
byte[] decryptedSessionKey = CryptoCipherV2.decryptRSA(sessionKey, pKey);

SecretKey sKey = CryptoCipherV2.byteToSessionKey(decryptedSessionKey);
byte[] content = new byte[(int) file.length()];

try (
final FileInputStream fis = new FileInputStream(file);
final BufferedInputStream bis = new BufferedInputStream(fis);
final DataInputStream dis = new DataInputStream(bis)
) {
dis.readFully(content);
dis.close();
byte[] decrypted = CryptoCipherV2.decryptAES(content, sKey, iv);
// write the decrypted string to the file
try (
final FileOutputStream fos = new FileOutputStream(
file.getAbsolutePath()
)
) {
fos.write(decrypted);
}
}
} catch (GeneralSecurityException e) {
Log.i(TAG, "decryptFile fail");
this.sendStats("decrypt_fail", version);
e.printStackTrace();
throw new IOException("GeneralSecurityException");
}
}

private void decryptFile(
final File file,
final String ivSessionKey,
final String version
) throws IOException {
// (str != null && !str.isEmpty())
if (this.privateKey == null || this.privateKey.isEmpty()) {
Log.i(TAG, "Cannot found privateKey");
return;
} else if (
ivSessionKey == null ||
ivSessionKey.isEmpty() ||
ivSessionKey.split(":").length != 2
) {
Log.i(TAG, "Cannot found sessionKey");
return;
}
try {
String ivB64 = ivSessionKey.split(":")[0];
String sessionKeyB64 = ivSessionKey.split(":")[1];
byte[] iv = Base64.decode(ivB64.getBytes(), Base64.DEFAULT);
byte[] sessionKey = Base64.decode(
sessionKeyB64.getBytes(),
Base64.DEFAULT
);
PrivateKey pKey = CryptoCipher.stringToPrivateKey(this.privateKey);
byte[] decryptedSessionKey = CryptoCipher.decryptRSA(sessionKey, pKey);
SecretKey sKey = CryptoCipher.byteToSessionKey(decryptedSessionKey);
byte[] content = new byte[(int) file.length()];

try (
final FileInputStream fis = new FileInputStream(file);
final BufferedInputStream bis = new BufferedInputStream(fis);
final DataInputStream dis = new DataInputStream(bis)
) {
dis.readFully(content);
dis.close();
byte[] decrypted = CryptoCipher.decryptAES(content, sKey, iv);
// write the decrypted string to the file
try (
final FileOutputStream fos = new FileOutputStream(
file.getAbsolutePath()
)
) {
fos.write(decrypted);
}
}
} catch (GeneralSecurityException e) {
Log.i(TAG, "decryptFile fail");
this.sendStats("decrypt_fail", version);
e.printStackTrace();
throw new IOException("GeneralSecurityException");
}
}

public void downloadBackground(
final String url,
final String version,
Expand Down
85 changes: 85 additions & 0 deletions android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@
*/
import android.util.Base64;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
Expand All @@ -24,6 +30,7 @@
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.zip.CRC32;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
Expand Down Expand Up @@ -146,6 +153,84 @@ public static PrivateKey stringToPrivateKey(String private_key)
return readPkcs1PrivateKey(pkcs1EncodedBytes);
}

public static void decryptFile(
final File file,
final String privateKey,
final String ivSessionKey,
final String version
) throws IOException {
// (str != null && !str.isEmpty())
if (privateKey == null || privateKey.isEmpty()) {
Log.i(CapacitorUpdater.TAG, "Cannot found privateKey");
return;
} else if (
ivSessionKey == null ||
ivSessionKey.isEmpty() ||
ivSessionKey.split(":").length != 2
) {
Log.i(CapacitorUpdater.TAG, "Cannot found sessionKey");
return;
}
try {
String ivB64 = ivSessionKey.split(":")[0];
String sessionKeyB64 = ivSessionKey.split(":")[1];
byte[] iv = Base64.decode(ivB64.getBytes(), Base64.DEFAULT);
byte[] sessionKey = Base64.decode(
sessionKeyB64.getBytes(),
Base64.DEFAULT
);
PrivateKey pKey = CryptoCipher.stringToPrivateKey(privateKey);
byte[] decryptedSessionKey = CryptoCipher.decryptRSA(sessionKey, pKey);
SecretKey sKey = CryptoCipher.byteToSessionKey(decryptedSessionKey);
byte[] content = new byte[(int) file.length()];

try (
final FileInputStream fis = new FileInputStream(file);
final BufferedInputStream bis = new BufferedInputStream(fis);
final DataInputStream dis = new DataInputStream(bis)
) {
dis.readFully(content);
dis.close();
byte[] decrypted = CryptoCipher.decryptAES(content, sKey, iv);
// write the decrypted string to the file
try (
final FileOutputStream fos = new FileOutputStream(
file.getAbsolutePath()
)
) {
fos.write(decrypted);
}
}
} catch (GeneralSecurityException e) {
Log.i(CapacitorUpdater.TAG, "decryptFile fail");
e.printStackTrace();
throw new IOException("GeneralSecurityException");
}
}

public static String calcChecksum(File file) {
final int BUFFER_SIZE = 1024 * 1024 * 5; // 5 MB buffer size
CRC32 crc = new CRC32();

try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = fis.read(buffer)) != -1) {
crc.update(buffer, 0, length);
}
return String.format("%08x", crc.getValue());
} catch (IOException e) {
System.err.println(
CapacitorUpdater.TAG +
" Cannot calc checksum: " +
file.getPath() +
" " +
e.getMessage()
);
return "";
}
}

public static PublicKey stringToPublicKey(String publicKey) {
byte[] encoded = Base64.decode(publicKey, Base64.DEFAULT);

Expand Down
Loading
Loading