Skip to content

Commit 90d1f8a

Browse files
committed
Add org.bouncycastle.pkcs12.store_it_count so the PBE iteration count the PKCS12 keystore writes with is settable, the write-side counterpart of the existing max_it_count that only bounds what is accepted on load, and bring the jdk1.3 and jdk1.4 keystore overlays into step with it so all three distributions share the 600,000 default rather than the 1,024 and 51,200 they had kept, take their MAC count from a file they loaded, and honour the property, with the Gradle and Ant test harnesses setting it low so the suites do not spend their time on the KDF.
1 parent f0d5c85 commit 90d1f8a

12 files changed

Lines changed: 271 additions & 43 deletions

File tree

‎ant/bc+-build.xml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1072,6 +1072,9 @@
10721072
</fileset>
10731073
</classpath>
10741074
<sysproperty key="test.java.version.prefix" value="${env.JAVA_VERSION_PREFIX}" />
1075+
<!-- the PKCS#12 keystore writes with a 600,000 iteration PBE by default, several
1076+
seconds per store; the tests are not measuring the KDF, so write cheap files -->
1077+
<sysproperty key="org.bouncycastle.pkcs12.store_it_count" value="4096" />
10751078

10761079
<formatter type="xml" />
10771080
<batchtest todir="${artifacts.reports.xml.dir}" unless="testcase">
@@ -1101,6 +1104,10 @@
11011104
</fileset>
11021105
</classpath>
11031106

1107+
<!-- the PKCS#12 keystore writes with a 600,000 iteration PBE by default, several
1108+
seconds per store; the tests are not measuring the KDF, so write cheap files -->
1109+
<sysproperty key="org.bouncycastle.pkcs12.store_it_count" value="4096" />
1110+
11041111
<formatter type="xml" />
11051112
<test name="${testcase}" todir="${artifacts.reports.xml.dir}" if="testcase" />
11061113
<batchtest todir="${artifacts.reports.xml.dir}" unless="testcase">

‎build.gradle‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,12 @@ configure(subprojects.findAll {it.name != 'bom'}) {
311311
reports {
312312
junitXml.outputLocation = layout.buildDirectory.dir("test-results")
313313
}
314+
315+
// The PKCS#12 keystore writes with a 600,000 iteration PBE by default, which is
316+
// several seconds per store and dominates the wall time of any suite that touches
317+
// a keystore. The tests are not measuring the KDF, so write cheap files here. Runs
318+
// after testFull's systemProperties assignment above, so it survives it.
319+
systemProperty 'org.bouncycastle.pkcs12.store_it_count', '4096'
314320
}
315321

316322
// Bundle the project LICENSE into META-INF/ of every jar produced.

‎core/src/main/java/org/bouncycastle/util/Properties.java‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,25 @@ public class Properties
3636
*/
3737
public static final String PKCS12_MAX_IT_COUNT = "org.bouncycastle.pkcs12.max_it_count";
3838

39+
/**
40+
* The PBE iteration count the PKCS12 keystore uses when <b>writing</b> a file - the write-side
41+
* counterpart of {@link #PKCS12_MAX_IT_COUNT}, which only bounds what is accepted on load.
42+
* Default 600,000 for the key and certificate encryption, twice that for the integrity MAC.
43+
* <p>
44+
* Lowering this trades password-cracking resistance for store/load time, and is only worth
45+
* doing where something other than the passphrase carries the confidentiality of the file -
46+
* a machine-generated high-entropy password, or a keystore held somewhere already protected.
47+
* It is deliberately an operator decision rather than a per-call one: a deployment that wants
48+
* cheaper files sets it once at startup for the whole JVM.
49+
* <p>
50+
* A value outside 1 .. 2,500,000 is ignored and the default used, so a mistyped property fails
51+
* towards the default rather than towards a file with no PBE work in it; the upper bound keeps
52+
* the doubled MAC count inside the 5,000,000 that {@link #PKCS12_MAX_IT_COUNT} defaults to, so
53+
* a file written under this property can always be read back. Read via
54+
* {@link #asInteger(String, int)}.
55+
*/
56+
public static final String PKCS12_STORE_IT_COUNT = "org.bouncycastle.pkcs12.store_it_count";
57+
3958
/**
4059
* Maximum time, in seconds, that a downloaded CRL is cached by the internal CrlCache used
4160
* by the CertPath validator and X509RevocationChecker. When set to a positive value, cached

‎core/src/main/jdk1.4/org/bouncycastle/util/Properties.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ public class Properties
2626
// classes that reference them compile in the jdk1.4 build. Keep in step with base.
2727
public static final String PKCS12_IGNORE_USELESS_PASSWD = "org.bouncycastle.pkcs12.ignore_useless_passwd";
2828
public static final String PKCS12_MAX_IT_COUNT = "org.bouncycastle.pkcs12.max_it_count";
29+
public static final String PKCS12_STORE_IT_COUNT = "org.bouncycastle.pkcs12.store_it_count";
2930
public static final String BKS_MAX_IT_COUNT = "org.bouncycastle.bks.max_it_count";
3031
public static final String OPENSSH_MAX_ROUNDS = "org.bouncycastle.openssh.max_rounds";
3132
public static final String X509_CRL_CACHE_TTL = "org.bouncycastle.x509.crl_cache_ttl";

‎docs/releasenotes.html‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,9 +143,10 @@ <h3>2.1.2 Defects Fixed</h3>
143143

144144
<h3>2.1.3 Additional Features and Functionality</h3>
145145
<ul>
146+
<li>The new org.bouncycastle.pkcs12.store_it_count property sets the PBE iteration count the PKCS12 keystore uses when writing a file, the write-side counterpart of the existing org.bouncycastle.pkcs12.max_it_count, which only bounds what is accepted on load. The default is unchanged - 600,000 for the key and certificate encryption, twice that for the integrity MAC - but until now there was no way to ask for anything else, and the count was raised from 51,200 in 1.85, which multiplies the cost of writing or reading a keystore by about twelve. Lowering it trades password-cracking resistance for store and load time, and is only worth doing where something other than the passphrase carries the confidentiality of the file: a machine-generated high-entropy password, or a keystore held somewhere already protected. It is deliberately an operator setting rather than a per-call one, so a deployment that wants cheaper files sets it once at startup. A value outside 1 .. 2,500,000 is ignored and the default used, the upper bound keeping the doubled MAC count inside the 5,000,000 that org.bouncycastle.pkcs12.max_it_count defaults to, so a file written under this property can always be read back. A keystore loaded from an existing file still keeps and rewrites the MAC iteration count it arrived with. The same change corrects a long standing divergence in the legacy Ant distributions, whose hand maintained copies of the keystore SPIs had never been brought forward: the jdk13 and jdk14 jars were writing PKCS12 files at 1,024 iterations - the figure PKCS#12 shipped with in the 1990s - and their PBMAC1 keystore at 51,200, rather than the count the modern jars use, and neither took its MAC count from a file it had loaded. All three now share the default and honour the new property.</li>
146147
<li>OpenPGP secret keys whose private key material is held outside the key - on a hardware token - are now supported, following <a href="https://datatracker.ietf.org/doc/draft-dkg-openpgp-external-secrets/">draft-dkg-openpgp-external-secrets</a>. org.bouncycastle.bcpg.SecretKeyPacket recognises the External S2K usage octet (SecretKeyPacket.USAGE_EXTERNAL) and its locator hint, PGPSecretKey exposes isExternalKey() / getExternalKeyLocatorHint(), and a decryption backend is plugged into the high level API by registering an org.bouncycastle.openpgp.api.PublicKeyDataDecryptorFactoryProvider with OpenPGPMessageProcessor. On the lightweight side BcPublicKeyDataDecryptorFactory now isolates the raw private-key operation behind BcPublicKeyCryptoCallback, so a subclass of the new org.bouncycastle.openpgp.api.operator.bc.BcExternalPublicKeyDataDecryptorFactory routes only the RSA decryption or the ECDH/X25519 agreement to a device while inheriting all packet parsing, KDF and key-unwrap logic. org.bouncycastle.openpgp.api.operator.jcajce.JceExternalPublicKeyDataDecryptorFactoryBuilder is the JCA/JCE analogue: its factories inherit the session-key recovery flow from the new stack-neutral org.bouncycastle.openpgp.api.operator.AbstractExternalPublicKeyDataDecryptorFactory (which carries the parsing, length checks and KDF/key-unwrap sequencing over byte-level primitive hooks), bind the HKDF, key unwrap and ephemeral-key handling to the configured JCA provider, and present the sender's ephemeral key to the device callback as a java.security.PublicKey. Note the External S2K usage octet is provisional: the draft records it as "TBD (252?)" and IANA has not assigned it.</li>
147-
<li>A new module, bcpgsc (org.bouncycastle.openpgp.smartcard), provides an OpenPGP smart-card API on top of the external-secret-key support: listing cards across pluggable backends, uploading key material, and decrypting messages with a card-held key. Two backends ship - a YubiKey backend built on the YubiKit libraries, and an in-memory simulator for testing without hardware. The YubiKit libraries are a compile-only dependency, so the published bcpgsc jar carries no third-party runtime dependency; an application using org.bouncycastle.openpgp.smartcard.yubikey must add them to its own classpath. The YubiKey backend can route decryption through either the lightweight or the JCA/JCE operator binding, selected with YubikeySmartCardBackend.bcImpl() / jceImpl(). Contributed by Paul Schaub.</li>
148-
<li>org.bouncycastle.openpgp.operator.PGPKeyPairGenerator gained named convenience methods for the three brainpool curves RFC 9580 sec. 9.2 permits for OpenPGP - generateBrainpoolP256r1ECDHKeyPair / generateBrainpoolP384r1ECDHKeyPair / generateBrainpoolP512r1ECDHKeyPair and the matching ECDSA variants - alongside the existing NIST P-256/P-384/P-521 methods. The generated ECDH keys carry the per-curve KDF hash and KEK symmetric algorithm required by sec. 11.5.1, which the key-pair generator tests now assert for the brainpool and the NIST curves alike. Contributed by Paul Schaub.</li>
148+
<li>A new module, bcpgsc (org.bouncycastle.openpgp.smartcard), provides an OpenPGP smart-card API on top of the external-secret-key support: listing cards across pluggable backends, uploading key material, and decrypting messages with a card-held key. Two backends ship - a YubiKey backend built on the YubiKit libraries, and an in-memory simulator for testing without hardware. The YubiKit libraries are a compile-only dependency, so the published bcpgsc jar carries no third-party runtime dependency; an application using org.bouncycastle.openpgp.smartcard.yubikey must add them to its own classpath. The YubiKey backend can route decryption through either the lightweight or the JCA/JCE operator binding, selected with YubikeySmartCardBackend.bcImpl() / jceImpl().</li>
149+
<li>org.bouncycastle.openpgp.operator.PGPKeyPairGenerator gained named convenience methods for the three brainpool curves RFC 9580 sec. 9.2 permits for OpenPGP - generateBrainpoolP256r1ECDHKeyPair / generateBrainpoolP384r1ECDHKeyPair / generateBrainpoolP512r1ECDHKeyPair and the matching ECDSA variants - alongside the existing NIST P-256/P-384/P-521 methods. The generated ECDH keys carry the per-curve KDF hash and KEK symmetric algorithm required by sec. 11.5.1, which the key-pair generator tests now assert for the brainpool and the NIST curves alike.</li>
149150
<li>Further extended key usages are now available as KeyPurposeId constants: id-kp-secureShellClient and id-kp-secureShellServer (RFC 6187 sec. 2.2.2, id-kp 21/22), id-kp-cmcArchive (RFC 6402 sec. 2.10, id-kp 29) and id-kp-bundleSecurity (RFC 9174, id-kp 35).</li>
150151
<li>The two RFC 4556 (PKINIT) extended key usages are now available as KeyPurposeId constants: id-pkinit-KPClientAuth (1.3.6.1.5.2.3.4, sec. 3.2.2) as KeyPurposeId.id_kp_pkinitClientAuth and id-pkinit-KPKdc (1.3.6.1.5.2.3.5, sec. 3.2.4) as KeyPurposeId.id_kp_pkinitKdc. Note these sit under the Kerberos id-pkinit arc rather than the PKIX id-kp arc, and are distinct from the Microsoft smartcard logon usage already available as id_kp_smartcardlogon.</li>
151152
<li>org.bouncycastle.math.ec.ECConstantTimeMultiplier is a new constant-time variable-point scalar multiplier: a fixed window with signed-odd-digit recoding, so the iteration and doubling counts are independent of the scalar, with table entries fetched through ECCurve.createCacheSafeLookupTable's masked scan. It works over both prime and binary curves (the point must lie in the subgroup of the given, odd, group order) and returns exactly the point the existing multipliers do - only the timing profile differs. Use it via the new ECAlgorithms.multiplySecret(p, k) / multiplySecret(p, k, order), or install it on a curve with ECCurve.Config.setMultiplier.</li>

‎prov/src/main/java/org/bouncycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,8 @@
174174
* <ul>
175175
* <li>{@link Properties#PKCS12_MAX_IT_COUNT} — caps the PBE iteration count
176176
* accepted on load.</li>
177+
* <li>{@link Properties#PKCS12_STORE_IT_COUNT} — the PBE iteration count used
178+
* when writing (default 600,000, twice that for the MAC).</li>
177179
* <li>{@link Properties#PKCS12_IGNORE_USELESS_PASSWD} — accepts a password
178180
* supplied where none is needed.</li>
179181
* <li>{@link Properties#PKCS12_ALLOW_SUN_SECRET_KEYS} — opt-in SunJCE
@@ -191,7 +193,6 @@ public class PKCS12KeyStoreSpi
191193
private final JcaJceHelper helper = new BCJcaJceHelper();
192194

193195
private static final int SALT_SIZE = 20;
194-
private static final int MIN_ITERATIONS = 600000;
195196

196197
private IgnoresCaseHashtable keys = new IgnoresCaseHashtable();
197198
private IgnoresCaseHashtable localIds = new IgnoresCaseHashtable();
@@ -225,7 +226,9 @@ public class PKCS12KeyStoreSpi
225226
private ASN1ObjectIdentifier certAlgorithm;
226227

227228
private AlgorithmIdentifier macAlgorithm = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE);
228-
private int itCount = 2 * MIN_ITERATIONS;
229+
// The MAC iteration count: taken from a loaded file so that storing it again preserves it,
230+
// and -1 until then, meaning doStore should use the store-time default.
231+
private int itCount = -1;
229232
private int saltLength = 20;
230233

231234
private class CertId
@@ -1663,6 +1666,10 @@ private void syncFriendlyName()
16631666
private void doStore(OutputStream stream, char[] password, boolean useDEREncoding, boolean overwriteFriendlyName)
16641667
throws IOException
16651668
{
1669+
int storeItCount = PKCS12Util.getStoreIterationCount();
1670+
// a file loaded from disk keeps its own MAC count, otherwise twice the PBE count
1671+
int macItCount = (itCount > 0) ? itCount : 2 * storeItCount;
1672+
16661673
if (!overwriteFriendlyName)
16671674
{
16681675
syncFriendlyName();
@@ -1750,15 +1757,15 @@ private void doStore(OutputStream stream, char[] password, boolean useDEREncodin
17501757
if (isPBKDF2(keyAlgorithm))
17511758
{
17521759
// TODO: keySize hard coded to 256 bits
1753-
PBKDF2Params kParams = new PBKDF2Params(kSalt, MIN_ITERATIONS, getKeyLength(keyAlgorithm), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_hmacWithSHA256, DERNull.INSTANCE));
1760+
PBKDF2Params kParams = new PBKDF2Params(kSalt, storeItCount, getKeyLength(keyAlgorithm), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_hmacWithSHA256, DERNull.INSTANCE));
17541761
EncryptionScheme encScheme = new EncryptionScheme(keyAlgorithm, getAlgParams(keyAlgorithm));
17551762
kAlgId = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, new PBES2Parameters(
17561763
new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, kParams), encScheme));
17571764
kBytes = wrapKey(encScheme, privKey, kParams, password);
17581765
}
17591766
else
17601767
{
1761-
PKCS12PBEParams kParams = new PKCS12PBEParams(kSalt, MIN_ITERATIONS);
1768+
PKCS12PBEParams kParams = new PKCS12PBEParams(kSalt, storeItCount);
17621769
kBytes = wrapKey(keyAlgorithm.getId(), privKey, kParams, password);
17631770
kAlgId = new AlgorithmIdentifier(keyAlgorithm, kParams.toASN1Primitive());
17641771
}
@@ -1846,13 +1853,13 @@ private void doStore(OutputStream stream, char[] password, boolean useDEREncodin
18461853
AlgorithmIdentifier cAlgId;
18471854
if (isPBKDF2(certAlgorithm))
18481855
{
1849-
PBKDF2Params cParams = new PBKDF2Params(cSalt, MIN_ITERATIONS, getKeyLength(certAlgorithm), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_hmacWithSHA256, DERNull.INSTANCE));
1856+
PBKDF2Params cParams = new PBKDF2Params(cSalt, storeItCount, getKeyLength(certAlgorithm), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_hmacWithSHA256, DERNull.INSTANCE));
18501857
cAlgId = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, new PBES2Parameters(
18511858
new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, cParams), new EncryptionScheme(certAlgorithm, getAlgParams(certAlgorithm))));
18521859
}
18531860
else
18541861
{
1855-
PKCS12PBEParams cParams = new PKCS12PBEParams(cSalt, MIN_ITERATIONS);
1862+
PKCS12PBEParams cParams = new PKCS12PBEParams(cSalt, storeItCount);
18561863
cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.toASN1Primitive());
18571864
}
18581865
Hashtable doneCerts = new Hashtable();
@@ -2100,11 +2107,11 @@ private void doStore(OutputStream stream, char[] password, boolean useDEREncodin
21002107
{
21012108
try
21022109
{
2103-
byte[] res = calculatePbeMac(helper, macAlgorithm, mSalt, itCount, password, false, data);
2110+
byte[] res = calculatePbeMac(helper, macAlgorithm, mSalt, macItCount, password, false, data);
21042111

21052112
DigestInfo dInfo = new DigestInfo(macAlgorithm, res);
21062113

2107-
mData = new MacData(dInfo, mSalt, itCount);
2114+
mData = new MacData(dInfo, mSalt, macItCount);
21082115
}
21092116
catch (Exception e)
21102117
{

0 commit comments

Comments
 (0)