apksigner 1.0.0

APK signer and verifier CLI — a faithful Rust port of AOSP apksigner
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! Mirrors `com.android.apksigner.PasswordRetriever`.
//!
//! Retriever of passwords based on the password specs supported by the `apksigner` tool.
//!
//! apksigner supports retrieving multiple passwords from the same source (e.g., file, standard
//! input), which adds the need to keep some sources open across password retrievals. This type
//! addresses that need: construct one, call [`PasswordRetriever::get_passwords`] as needed, and
//! then [`PasswordRetriever::close`] (or drop it) to release held resources.
//!
//! ## Mapping notes
//!
//! Java passwords are `char[]` — arrays of UTF-16 code units — and the KeyStore/PBE APIs consume
//! exactly that. The nearest Rust equivalent for the character sequence is `Vec<char>`; the
//! consumer converts to bytes in whatever encoding the KeyStore or PKCS #8 blob expects. This is
//! why the password variants produced here are "character sequences obtained by encoding then
//! upcasting", matching the Java logic literally.
//!
//! ## Deviation: supported charsets
//!
//! The Java implementation accepts any charset the JVM knows (via `Charset.forName`) and can
//! detect the console encoding on Java 8 and older. This port has no charset registry: it
//! supports UTF-8, US-ASCII, ISO-8859-1 and the UTF-16 byte orders, and maps the common aliases
//! for those. Any other name — including the ones the help text mentions, such as `ibm437` — is
//! reported as unsupported, which is the same outcome as Java's
//! `IllegalArgumentException` path but is reached for a wider set of names.

use std::collections::HashMap;
use std::fs::File;
use std::io::{self, Read, Write};
use std::path::PathBuf;

/// Mirrors Java's `Charset` for the encodings this port can perform.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Charset {
    Utf8,
    Ascii,
    Latin1,
    Utf16Le,
    Utf16Be,
}

impl Charset {
    /// Encodes characters, replacing anything unmappable, mirroring
    /// `CharsetEncoder.onMalformedInput(REPLACE).onUnmappableCharacter(REPLACE)`.
    pub fn encode(self, chars: &[char]) -> Vec<u8> {
        match self {
            Charset::Utf8 => {
                let mut out = Vec::with_capacity(chars.len());
                for &c in chars {
                    let mut buf = [0u8; 4];
                    out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
                }
                out
            }
            Charset::Ascii => chars
                .iter()
                .map(|&c| if (c as u32) <= 0x7f { c as u8 } else { b'?' })
                .collect(),
            Charset::Latin1 => chars
                .iter()
                .map(|&c| if (c as u32) <= 0xff { c as u8 } else { b'?' })
                .collect(),
            Charset::Utf16Le => {
                let mut out = Vec::with_capacity(chars.len() * 2);
                for &c in chars {
                    let mut buf = [0u16; 2];
                    for unit in c.encode_utf16(&mut buf) {
                        out.extend_from_slice(&unit.to_le_bytes());
                    }
                }
                out
            }
            Charset::Utf16Be => {
                let mut out = Vec::with_capacity(chars.len() * 2);
                for &c in chars {
                    let mut buf = [0u16; 2];
                    for unit in c.encode_utf16(&mut buf) {
                        out.extend_from_slice(&unit.to_be_bytes());
                    }
                }
                out
            }
        }
    }

    /// Decodes bytes, replacing anything malformed or unmappable, mirroring
    /// `CharsetDecoder.onMalformedInput(REPLACE).onUnmappableCharacter(REPLACE)`.
    pub fn decode(self, bytes: &[u8]) -> Vec<char> {
        match self {
            Charset::Utf8 => String::from_utf8_lossy(bytes).chars().collect(),
            Charset::Ascii => bytes
                .iter()
                .map(|&b| if b <= 0x7f { b as char } else { '\u{FFFD}' })
                .collect(),
            Charset::Latin1 => bytes.iter().map(|&b| b as char).collect(),
            Charset::Utf16Le => decode_utf16(bytes, true),
            Charset::Utf16Be => decode_utf16(bytes, false),
        }
    }
}

/// Decodes UTF-16 bytes with replacement for malformed input.
fn decode_utf16(bytes: &[u8], little_endian: bool) -> Vec<char> {
    let mut units = Vec::with_capacity(bytes.len() / 2);
    let mut i = 0;
    while i + 1 < bytes.len() {
        let pair = [bytes[i], bytes[i + 1]];
        units.push(if little_endian {
            u16::from_le_bytes(pair)
        } else {
            u16::from_be_bytes(pair)
        });
        i += 2;
    }
    if i < bytes.len() {
        // Trailing odd byte: malformed, replaced.
        units.push(0xFFFD);
    }
    char::decode_utf16(units)
        .map(|r| r.unwrap_or('\u{FFFD}'))
        .collect()
}

/// The character encoding used when a password is read from standard input or a file and no
/// additional encoding is supplied.
///
/// Java uses `Charset.defaultCharset()`, which is UTF-8 on every modern platform this tool
/// targets; Rust has no runtime default-charset setting, so UTF-8 is used.
pub fn default_charset() -> Charset {
    Charset::Utf8
}

/// Mirrors `PasswordRetriever.getCharsetByName`.
///
/// Returns `Err` where the Java method throws `IllegalArgumentException`.
pub fn get_charset_by_name(charset_name: &str) -> Result<Charset, String> {
    // On Windows 10, cp65001 is the UTF-8 code page; the Java version special-cases it because
    // some JVMs have no mapping for it.
    if charset_name.eq_ignore_ascii_case("cp65001") {
        return Ok(Charset::Utf8);
    }

    let normalized = charset_name.to_ascii_lowercase().replace('_', "-");
    match normalized.as_str() {
        "utf-8" | "utf8" => Ok(Charset::Utf8),
        "us-ascii" | "ascii" | "ansi-x3.4-1968" | "iso646-us" => Ok(Charset::Ascii),
        "iso-8859-1" | "iso8859-1" | "latin1" | "l1" | "cp819" | "ibm819" => Ok(Charset::Latin1),
        "utf-16le" | "utf16le" | "unicode" | "unicode-little" => Ok(Charset::Utf16Le),
        "utf-16be" | "utf16be" | "unicode-big" | "unicodebigunmarked" => Ok(Charset::Utf16Be),
        _ => Err(format!("Unsupported charset: {}", charset_name)),
    }
}

/// A password as a sequence of characters, mirroring Java's `char[]`.
pub type Password = Vec<char>;

/// Mirrors `PasswordRetriever.SPEC_STDIN`.
pub const SPEC_STDIN: &str = "stdin";

/// A byte stream that supports Java-style single-byte pushback.
struct PasswordSource {
    reader: Box<dyn Read>,
    pushback: Option<u8>,
}

impl PasswordSource {
    fn new(reader: Box<dyn Read>) -> Self {
        PasswordSource {
            reader,
            pushback: None,
        }
    }

    /// Reads the next byte, taking pushback into account.
    fn next_byte(&mut self) -> io::Result<Option<u8>> {
        if let Some(byte) = self.pushback.take() {
            return Ok(Some(byte));
        }
        let mut buf = [0u8; 1];
        loop {
            match self.reader.read(&mut buf) {
                Ok(0) => return Ok(None),
                Ok(_) => return Ok(Some(buf[0])),
                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(e) => return Err(e),
            }
        }
    }

    /// Mirrors `PasswordRetriever.readEncodedPassword`.
    ///
    /// Reads bytes up to the next line terminator. A `\r` not followed by `\n` is *kept* in the
    /// password and the following byte is pushed back, exactly as the Java does.
    fn read_encoded_password(&mut self) -> io::Result<Vec<u8>> {
        let mut result = Vec::new();
        while let Some(b) = self.next_byte()? {
            if b == b'\n' {
                break;
            } else if b == b'\r' {
                match self.next_byte()? {
                    None => break,
                    Some(b'\n') => break,
                    Some(next) => self.pushback = Some(next),
                }
            }
            result.push(b);
        }
        Ok(result)
    }
}

/// Mirrors `com.android.apksigner.PasswordRetriever`.
pub struct PasswordRetriever {
    /// Character encoding used by the console, or `None` when unknown.
    ///
    /// Java detects this only on Java 8 and older; on Java 9+ it is always unknown. This port
    /// has no console-encoding API at all, so it is always unknown.
    console_encoding: Option<Charset>,

    file_input_streams: HashMap<PathBuf, PasswordSource>,
    /// Standard input is kept as a single persistent source so that consecutive `stdin` specs
    /// read successive lines, matching the Java behavior of reading from a single `System.in`.
    stdin_source: Option<PasswordSource>,

    closed: bool,
}

impl Default for PasswordRetriever {
    fn default() -> Self {
        Self::new()
    }
}

impl PasswordRetriever {
    pub fn new() -> Self {
        PasswordRetriever {
            console_encoding: get_console_encoding(),
            file_input_streams: HashMap::new(),
            stdin_source: None,
            closed: false,
        }
    }

    /// Returns the passwords described by the provided spec.
    ///
    /// More than one password may be returned for compatibility with `keytool` and `jarsigner`,
    /// which in certain cases use the form of passwords encoded using the console's character
    /// encoding or the JVM default encoding.
    ///
    /// Supported specs:
    /// * `stdin` — read the password as a line from the console, if available, or standard input
    /// * `pass:password` — password specified inside the spec, after `pass:`
    /// * `file:path` — read the password as a line from the specified file
    /// * `env:name` — password is in the specified environment variable
    ///
    /// When the same file (including standard input) is used for providing multiple passwords,
    /// the passwords are read from the file one line at a time.
    pub fn get_passwords(
        &mut self,
        spec: &str,
        description: &str,
        additional_pwd_encodings: &[Charset],
    ) -> io::Result<Vec<Password>> {
        self.assert_not_closed()?;

        if let Some(inline) = spec.strip_prefix("pass:") {
            let pwd: Vec<char> = inline.chars().collect();
            return Ok(self.passwords_from_chars(&pwd, additional_pwd_encodings));
        }

        if spec == SPEC_STDIN {
            // Java uses the console when one is attached, which suppresses echo. Rust's standard
            // library exposes no console handle, so the description is always printed and the
            // password is read from standard input with echo left to the terminal.
            print!("{}: ", description);
            io::stdout().flush()?;
            let source = match self.stdin_source.as_mut() {
                Some(source) => source,
                None => {
                    self.stdin_source = Some(PasswordSource::new(Box::new(io::stdin())));
                    self.stdin_source.as_mut().unwrap()
                }
            };
            let encoded_pwd = source.read_encoded_password()?;
            if encoded_pwd.is_empty() {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    format!("Failed to read {}: standard input closed", description),
                ));
            }
            return Ok(self.passwords_from_bytes(
                &encoded_pwd,
                default_charset(),
                additional_pwd_encodings,
            ));
        }

        if let Some(name) = spec.strip_prefix("file:") {
            let file = canonicalize(name)?;
            if !self.file_input_streams.contains_key(&file) {
                let stream = File::open(&file)?;
                self.file_input_streams
                    .insert(file.clone(), PasswordSource::new(Box::new(stream)));
            }
            let encoded_pwd = self
                .file_input_streams
                .get_mut(&file)
                .expect("just inserted")
                .read_encoded_password()?;
            if encoded_pwd.is_empty() {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    format!(
                        "Failed to read {} : end of file reached in {}",
                        description,
                        file.display()
                    ),
                ));
            }
            return Ok(self.passwords_from_bytes(
                &encoded_pwd,
                default_charset(),
                additional_pwd_encodings,
            ));
        }

        if let Some(name) = spec.strip_prefix("env:") {
            let value = std::env::var(name).ok();
            let Some(value) = value else {
                // The Java implementation interpolates the (null) value rather than the name, so
                // the message reads "environment variable null not specified".
                return Err(io::Error::new(
                    io::ErrorKind::NotFound,
                    format!(
                        "Failed to read {}: environment variable {} not specified",
                        description, "null"
                    ),
                ));
            };
            let chars: Vec<char> = value.chars().collect();
            return Ok(self.passwords_from_chars(&chars, additional_pwd_encodings));
        }

        Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("Unsupported password spec for {}: {}", description, spec),
        ))
    }

    /// Returns the provided password and all password variants derived from it.
    /// The resulting list is guaranteed to contain at least one element.
    fn passwords_from_chars(
        &self,
        pwd: &[char],
        additional_encodings: &[Charset],
    ) -> Vec<Password> {
        let mut passwords = Vec::with_capacity(3);
        self.add_passwords(&mut passwords, pwd, additional_encodings);
        passwords
    }

    /// Returns the provided password and all password variants derived from it, where the
    /// password was supplied as bytes encoded using `encoding_for_decoding`.
    fn passwords_from_bytes(
        &self,
        encoded_pwd: &[u8],
        encoding_for_decoding: Charset,
        additional_encodings: &[Charset],
    ) -> Vec<Password> {
        let mut passwords = Vec::with_capacity(4);

        // Decode the password and add it and its variants to the list.
        let pwd = encoding_for_decoding.decode(encoded_pwd);
        self.add_passwords(&mut passwords, &pwd, additional_encodings);

        // Add the original encoded form.
        add_password(&mut passwords, cast_bytes_to_chars(encoded_pwd));
        passwords
    }

    /// Adds the provided password and its variants to the list.
    ///
    /// Only passwords/variants which are not yet in the list are added.
    fn add_passwords(
        &self,
        passwords: &mut Vec<Password>,
        pwd: &[char],
        additional_encodings: &[Charset],
    ) {
        for &encoding in additional_encodings {
            // Password encoded using the provided encoding (usually the console's character
            // encoding) and upcast into a character sequence.
            add_password(passwords, cast_bytes_to_chars(&encoding.encode(pwd)));
        }

        // Verbatim password.
        add_password(passwords, pwd.to_vec());

        // Password encoded using the console encoding and upcast into a character sequence.
        if let Some(console_encoding) = self.console_encoding {
            add_password(
                passwords,
                cast_bytes_to_chars(&console_encoding.encode(pwd)),
            );
        }

        // Password encoded using the default character encoding and upcast.
        add_password(
            passwords,
            cast_bytes_to_chars(&default_charset().encode(pwd)),
        );
    }

    fn assert_not_closed(&self) -> io::Result<()> {
        if self.closed {
            return Err(io::Error::new(io::ErrorKind::BrokenPipe, "Closed"));
        }
        Ok(())
    }

    /// Releases the resources held by this retriever. Mirrors `AutoCloseable.close()`.
    pub fn close(&mut self) {
        self.file_input_streams.clear();
        self.stdin_source = None;
        self.closed = true;
    }
}

impl Drop for PasswordRetriever {
    fn drop(&mut self) {
        self.close();
    }
}

/// Adds the provided password to the list. Does nothing if the password is already in the list.
fn add_password(passwords: &mut Vec<Password>, password: Password) {
    if passwords.contains(&password) {
        return;
    }
    passwords.push(password);
}

/// Upcasts each byte to a character and returns the resulting sequence.
///
/// Mirrors `PasswordRetriever.castBytesToChars`, which is what makes the "encoded form used as
/// the password" variants possible.
fn cast_bytes_to_chars(bytes: &[u8]) -> Vec<char> {
    bytes.iter().map(|&b| b as char).collect()
}

/// Canonicalizes a path the way `new File(name).getCanonicalFile()` does, falling back to the
/// provided path when the filesystem cannot resolve it.
fn canonicalize(name: &str) -> io::Result<PathBuf> {
    let path = PathBuf::from(name);
    std::fs::canonicalize(&path)
}

/// Returns the character encoding used by the console, or `None` if it is not known.
///
/// Mirrors `PasswordRetriever.getConsoleEncoding`, which returns `null` on Java 9 and newer
/// because access to the console's encoding is restricted.
fn get_console_encoding() -> Option<Charset> {
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn pass_spec_yields_the_password_verbatim() {
        let mut r = PasswordRetriever::new();
        let passwords = r
            .get_passwords("pass:hunter2", "KeyStore password for signer #1", &[])
            .unwrap();
        assert!(passwords.contains(&"hunter2".chars().collect::<Vec<char>>()));
        // The default-encoding variant is identical for pure ASCII, so it is deduplicated.
        assert_eq!(passwords.len(), 1);
    }

    #[test]
    fn env_spec_reads_the_named_variable() {
        let name = "APKSIGNER_TEST_PASSWORD_ENV";
        // SAFETY: since edition 2024 the environment is process-global mutable state, so
        // mutating it is `unsafe`. The name is unique to this test and no other test reads it.
        unsafe { std::env::set_var(name, "s3cret") };
        let mut r = PasswordRetriever::new();
        let passwords = r
            .get_passwords(&format!("env:{}", name), "KeyStore password", &[])
            .unwrap();
        assert!(passwords.contains(&"s3cret".chars().collect::<Vec<char>>()));
        // SAFETY: as above -- this test owns the variable.
        unsafe { std::env::remove_var(name) };
    }

    #[test]
    fn env_spec_reports_a_missing_variable_with_the_java_wording() {
        let mut r = PasswordRetriever::new();
        let err = r
            .get_passwords(
                "env:APKSIGNER_DEFINITELY_NOT_SET_12345",
                "KeyStore password",
                &[],
            )
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Failed to read KeyStore password: environment variable null not specified"
        );
    }

    #[test]
    fn unsupported_spec_is_rejected() {
        let mut r = PasswordRetriever::new();
        let err = r
            .get_passwords("magic:thing", "KeyStore password", &[])
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Unsupported password spec for KeyStore password: magic:thing"
        );
    }

    #[test]
    fn file_spec_reads_successive_lines() {
        let dir = std::env::temp_dir();
        let path = dir.join("apksigner_password_retriever_test.txt");
        std::fs::write(&path, "first\nsecond\n").unwrap();

        let mut r = PasswordRetriever::new();
        let spec = format!("file:{}", path.display());
        let first = r.get_passwords(&spec, "KeyStore password", &[]).unwrap();
        let second = r.get_passwords(&spec, "Key password", &[]).unwrap();

        assert!(first.contains(&"first".chars().collect::<Vec<char>>()));
        assert!(second.contains(&"second".chars().collect::<Vec<char>>()));

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn additional_encodings_add_variants_for_non_ascii_passwords() {
        let mut r = PasswordRetriever::new();
        // A character outside US-ASCII: the UTF-8 encoded form, upcast to chars, is a distinct
        // variant from the verbatim password.
        let passwords = r
            .get_passwords("pass:\u{00e4}", "KeyStore password", &[Charset::Utf8])
            .unwrap();
        assert!(
            passwords.len() >= 2,
            "expected variants, got {:?}",
            passwords
        );
        assert!(passwords.contains(&vec!['\u{00e4}']));
        assert!(passwords.contains(&vec!['\u{00c3}', '\u{00a4}']));
    }

    #[test]
    fn console_encoding_is_unknown_so_it_adds_no_variant() {
        let r = PasswordRetriever::new();
        assert!(r.console_encoding.is_none());
    }

    #[test]
    fn closed_retriever_rejects_further_reads() {
        let mut r = PasswordRetriever::new();
        r.close();
        let err = r.get_passwords("pass:x", "desc", &[]).unwrap_err();
        assert_eq!(err.to_string(), "Closed");
    }

    #[test]
    fn read_encoded_password_handles_crlf_lf_and_cr() {
        fn read_all(input: &[u8]) -> Vec<Vec<u8>> {
            let mut source = PasswordSource::new(Box::new(Cursor::new(input.to_vec())));
            let mut lines = Vec::new();
            loop {
                let line = source.read_encoded_password().unwrap();
                if line.is_empty() {
                    break;
                }
                lines.push(line);
            }
            lines
        }

        assert_eq!(
            read_all(b"a\r\nb\nc\r"),
            vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec()]
        );
    }

    #[test]
    fn read_encoded_password_keeps_a_lone_carriage_return() {
        // Java unreads the byte after a `\r` that is not part of a CRLF and then writes the `\r`
        // itself, so the result contains the carriage return.
        let mut source = PasswordSource::new(Box::new(Cursor::new(b"a\rb\n".to_vec())));
        assert_eq!(source.read_encoded_password().unwrap(), b"a\rb".to_vec());
    }

    #[test]
    fn known_charset_names_resolve() {
        assert_eq!(get_charset_by_name("utf-8").unwrap(), Charset::Utf8);
        assert_eq!(get_charset_by_name("UTF-8").unwrap(), Charset::Utf8);
        assert_eq!(get_charset_by_name("cp65001").unwrap(), Charset::Utf8);
        assert_eq!(get_charset_by_name("US-ASCII").unwrap(), Charset::Ascii);
        assert_eq!(get_charset_by_name("ISO-8859-1").unwrap(), Charset::Latin1);
        assert!(get_charset_by_name("ibm437").is_err());
    }

    #[test]
    fn charset_round_trips_ascii() {
        let chars: Vec<char> = "hunter2".chars().collect();
        let encoded = Charset::Utf8.encode(&chars);
        assert_eq!(encoded, b"hunter2".to_vec());
        assert_eq!(Charset::Utf8.decode(&encoded), chars);
    }
}