Code Monkey home page Code Monkey logo

spongycastle's Introduction

The Bouncy Castle Crypto Package For Java

The Bouncy Castle Crypto package is a Java implementation of cryptographic algorithms, it was developed by the Legion of the Bouncy Castle, a registered Australian Charity, with a little help! The Legion, and the latest goings on with this package, can be found at http://www.bouncycastle.org.

The Legion also gratefully acknowledges the contributions made to this package by others (see here for the current list). If you would like to contribute to our efforts please feel free to get in touch with us or visit our donations page, sponsor some specific work, or purchase a support contract through Crypto Workshop.

The package is organised so that it contains a light-weight API suitable for use in any environment (including the newly released J2ME) with the additional infrastructure to conform the algorithms to the JCE framework.

Except where otherwise stated, this software is distributed under a license based on the MIT X Consortium license. To view the license, see here. The OpenPGP library also includes a modified BZIP2 library which is licensed under the Apache Software License, Version 2.0.

Note: this source tree is not the FIPS version of the APIs - if you are interested in our FIPS version please contact us directly at [email protected].

Code Organisation

The clean room JCE, for use with JDK 1.1 to JDK 1.3 is in the jce/src/main/java directory.

The core module provides all the functionality in the ligthweight APIs.

The prov module provides all the JCA/JCE provider functionality.

The pkix module is the home for code for X.509 certificate generation and the APIs for standards that rely on ASN.1 such as CMS, TSP, PKCS#12, OCSP, CRMF, and CMP.

The mail module provides an S/MIME API built on top of CMS.

The pg module is the home for code used to support OpenPGP.

The tls module is the home for code used to a general TLS API and JSSE Provider (as at 1.56 this should be considered a beta).

The build scripts that come with the full distribution allow creation of the different releases by using the different source trees while excluding classes that are not appropriate and copying in the required compatibility classes from the directories containing compatibility classes appropriate for the distribution.

If you want to try create a build for yourself, using your own environment, the best way to do it is to start with the build for the distribution you are interested in, make sure that builds, and then modify your build scripts to do the required exclusions and file copies for your setup, otherwise you are likely to get class not found exceptions. The final caveat to this is that as the j2me distribution includes some compatibility classes starting in the java package, you need to use an obfuscator to change the package names before attempting to import a midlet using the BC API.

Examples and Tests

To view some examples, look at the test programs in the packages:

  • org.bouncycastle.crypto.test

  • org.bouncycastle.jce.provider.test

  • org.bouncycastle.cms.test

  • org.bouncycastle.mail.smime.test

  • org.bouncycastle.openpgp.test

  • org.bouncycastle.tsp.test

There are also some specific example programs for dealing with SMIME and OpenPGP. They can be found in:

  • org.bouncycastle.mail.smime.examples

  • org.bouncycastle.openpgp.examples

Mailing Lists

For those who are interested, there are 2 mailing lists for participation in this project. To subscribe use the links below and include the word subscribe in the message body. (To unsubscribe, replace subscribe with unsubscribe in the message body)

  • [email protected]
    This mailing list is for new release announcements only, general subscribers cannot post to it.
  • [email protected]
    This mailing list is for discussion of development of the package. This includes bugs, comments, requests for enhancements, questions about use or operation.

**NOTE:**You need to be subscribed to send mail to the above mailing list.

Feedback

If you want to provide feedback directly to the members of The Legion then please use [email protected], if you want to help this project survive please consider donating.

For bug reporting/requests you can report issues here on github, via feedback-crypto if required, and we also have a Jira issue tracker. We will accept pull requests based on this repository as well.

Finally

Enjoy!

spongycastle's People

Contributors

akwizgran avatar andrey-vasilyev avatar bdhess avatar dghbk avatar dghgit avatar dstutz avatar eriktews avatar flix- avatar franziskuskiefer avatar gnu-user avatar hauke avatar hbs avatar jon-eaves avatar justinludwig avatar martinschaef avatar mauriceaarts avatar meganwoods avatar mikesafonov avatar mtausig avatar oh2mqk avatar peterdettman avatar peterhalicky avatar pewsey avatar pierrelartigue avatar ppelleti avatar rtyley avatar sake avatar scop avatar timw avatar vivlesoren avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

spongycastle's Issues

Bouncy Castle 1.57 was released

Hello,

The version 1.57 of Bouncy Castlke has been release on May, 11th 2017. It could be nice to backport fixed issues and new features into this project.

Extract from release notes:

2.1.2 Defects Fixed

  • A class cast exception for master certification removal in PGPPublicKey.removeCertification() by certification has been fixed.
  • GOST GOFB 28147-89 mode had an edge condition concerning the incorrect calculation of N4 (see section 6.1 of RFC 5830) affecting about 1% of IVs. This has been fixed.
  • The X.509 PolicyConstraints class was using implicit rather than explicit tagging for the SkipCerts field. This has been fixed.
  • Key expiration in the OpenPGP is now calculated for ambiguous self signatures using the most recently created self-signature, in line with GPG and the recommendation in RFC 4880.
  • Multiple validity periods in PGP keys were resolved in an adhoc fashion, in line with GPG's approach the PGP has been changed to return the most recent validity period signed.
  • An occasional class cast exception that could occur with nested multi-parts in the S/MIME API has been fixed.
  • A couple of bogus aliases associated AlgorithmParameters that did not resolve in the provider have been removed.
  • The CMS API will now correctly verify PSS signatures with odd length salts.
    Choosing an invalid mode on a stream cipher in the JCE could result in an IllegalArgumentException. This has now been corrected to throw a NoSuchAlgorithmException.
  • Optional parameters for ECDSA public keys in CVCertificates were hard coded to non-optional. This has been fixed.
  • Passing a PKCS12 key to a Mac in the BC JCE always resulted in SHA-1 being used to process the password regardless of the underlying MAC algorithm. This has been fixed. An unrecognised HMAC will also now result in an exception.
  • The Base64 encoder now explicitly validates 2 character padding as being "==".
  • EC FixedPointCombMultiplier avoids 'infinity' point in lookup tables, reducing timing side-channels.
  • Reuse of a Blake2b digest with a call to reset() rather than doFinal() could result in incorrect padding being introduced and the wrong digest result produced. This has been fixed.

2.1.3 Additional Features and Functionality

  • ARIA (RFC 5794) is now supported by the provider and the lightweight API.
  • ARIA Key Wrapping (RFC 5649 style) is now supported by the provider and the lightweight API.
  • SM2 signatures, key exchange, and public key encryption has been added to the lightweight API.
  • XMSS has been added to the lightweight PQ API. Note: this should be treated as beta code.
  • API support for client side EST (RFC 7030), as well as some CMC (RFC 5273) has been added to the PKIX API. A full set of ASN.1 classes for both protocols has been added as well.
  • A test client for EST which will interop with the 7030 test server at http://testrfc7030.com/ has been added to the general test module in the current source tree.
  • The BCJSSE provider now supports SSLContext.getDefault(), with very similar behaviour to the SunJSSE provider, including checks of the relevant javax.net.ssl.* system properties and auto-loading of jssecacerts or cacerts as the default trust store.

2.1.4 Security Related Changes

  • The default parameter sizes for DH and DSA are now 2048. If you have been relying on key pair generation without passing in parameters generated keys will now be larger.
  • Further work has been done on preventing accidental re-use of a GCM cipher without first changing its key or iv.

Andorid proguard-rules error(Android 混淆时报错)

我使用的是;com.madgag.spongycastle:core:$1.58.0.0
混淆时的配置为:
-keep class org.spongycastle.crypto.* {;}
-keep class org.spongycastle.crypto.agreement.** {
;}
-keep class org.spongycastle.crypto.digests.* {;}
-keep class org.spongycastle.crypto.ec.
{;}
-keep class org.spongycastle.crypto.encodings.
{;}
-keep class org.spongycastle.crypto.engines.
{;}
-keep class org.spongycastle.crypto.macs.
{;}
-keep class org.spongycastle.crypto.modes.
{;}
-keep class org.spongycastle.crypto.paddings.
{;}
-keep class org.spongycastle.crypto.params.
{;}
-keep class org.spongycastle.crypto.prng.
{;}
-keep class org.spongycastle.crypto.signers.
{;}
-keep class org.spongycastle.pqc.crypto.mceliece.McElieceCCA2PrivateKeyParameters.
{;}
-keep class org.spongycastle.jcajce.provider.symmetric.** {
;}
-keep class org.spongycastle.jcajce.**{*;}

-keep class org.spongycastle.jcajce.provider.asymmetric.* {;}
-keep class org.spongycastle.jcajce.provider.asymmetric.util.
{;}
-keep class org.spongycastle.jcajce.provider.asymmetric.dh.
{;}
-keep class org.spongycastle.jcajce.provider.asymmetric.ec.
{*;}

-keep class org.spongycastle.jcajce.provider.digest.** {;}
-keep class org.spongycastle.jcajce.provider.keystore.** {
;}
-keep class org.spongycastle.jcajce.provider.symmetric.** {;}
-keep class org.spongycastle.pqc.jcajce.provider.mceliece.BCMcElieceCCA2PrivateKey.**{
;}

出错信息如下,请问该怎样解决,谢谢。
image

ASN.1 data in PKCS7 signature

Hi,

In a standard PKCS7 signature, generated with SpongyCastle, in the ASN.1 signature data,
the Sequence objects length seems always set with a 0x80 (undefined) value.

Everything else is correct, though. The length is well set for every other data type.
The structure is identical between Spongy and Bouncy signatures,
but the length isn't undefined with Bouncy (same data to sign and same signature certificate) :
http://img11.hostingpics.net/pics/479305bouncy.png (Boucy)
http://img11.hostingpics.net/pics/696082spongy.png (Spongy)

OpenSSL seems to have hard time to read p7s generated without these length attributes.
The verification is successful using the spongy library, but cannot be validated using some other OpenSSL...

Do you have the same results ? Or any clues ?
Thanks.

JUnit bundled into libary

When we were inspecting our runtime dependencies we realized that spongycastle bundles JUnit. Is this really necessary?

debugCompileClasspath - Resolved configuration for compilation for variant: debug
.
.
.
+--- com.madgag.spongycastle:prov:1.58.0.0
|    +--- com.madgag.spongycastle:core:1.58.0.0
|    \--- junit:junit:4.12
|         \--- org.hamcrest:hamcrest-core:1.3

java.security.NoSuchAlgorithmException: AES/CBC/PKCS5PADDING

Hi,
we are using spongycastle as provider in out Android app (we switched from bouncycastle). On some devices we encounter a NoSuchAlgorithmException when calling Cipher.getInstance() with "AES/CBC/PKCS5PADDING" as algorithm and "SC" as provider. The call fails on following devices:

  • ME302C
  • GT-I8200N
  • GT-I9305
  • YD206
  • GT-N7100
  • ...

As far as we now, the call never succeeds on those devices. We are using 1.54.0.0.

Thanks for your work!

Spongy Castle KeyPairGenerator extremely slow on Android M

Hi,

When using Spongy Castle KeyPairGenerator , the statement "keyGen.generateKeyPair();" takes extremely long time to execute on Android M.

It takes around 12-13 seconds for this line to execute on Android 6 devices . in comparison - It takes 2-3 seconds on previous Android versions using the exact same libraries.

A sample Android Studio project is attached.

any help in getting better performance

would be greatly appreciated.

sample code :

    KeyPair keyPair = null;
    KeyPairGenerator keyGen = null;
    keyGen = KeyPairGenerator.getInstance("RSA", "BC");
    keyGen.initialize(2048);

    keyPair = keyGen.generateKeyPair(); <-This is the problematic statement

    byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
    String privateKey = new String(Base64.encode(privateKeyBytes, Base64.NO_WRAP));
    PublicKey signaturePublicKey = keyPair.getPublic();

JAR vs. JAR sources

Hi,

I am wondering why the prov-1.54.0.0.jar contains the bouncycastle and spongycastle packages and the sources only spongycastle?

I am getting duplicate issues when importing into my Android project. Could me doing something very wrong of course, as Java / Android is not my daily platform.

1.58 released

1.58 is out and once again my project needs it since as it turned out 1.56 has introduced some breaking changes which were properly fixed in 1.58. Are there plans to release spongycastle 1.58 any time soon?

Once again I'm willing to make a 0.1 BTC donation so feel free to provide an address.

Version of bc 1.51?

Hiya,

BC 1.51 is now in final beta and we really need the performance improvements in bitcoinj. I was wondering if you'll have time to upgrade to the newest version any time soon? If not, how hard is it for us to do that?

SpongyCastle abandoned

Is this project abandoned? There are few new releases for BouncyCastle whereas SpongyCastle has not ben updated to reflect this. Kindly provide an update on this project.

Different behaviour for signature on Desktop / Android

I use the following code in order to sign data:

static public byte[] sign(byte[] data, PrivateKey privateKey, int saltLength) throws Exception {
        Signature instance = Signature.getInstance("SHA256withRSA/PSS", provider);
        MGF1ParameterSpec mgf1ParameterSpec = new MGF1ParameterSpec("SHA-256");
        PSSParameterSpec pssParameterSpec = new PSSParameterSpec("SHA-256", "MGF1",mgf1ParameterSpec , saltLength, 1);
        instance.setParameter(pssParameterSpec);
        instance.initSign(privateKey);
        instance.update(data);
        return instance.sign();
}

(The code is very similar for checking sign)

On desktop (with BC or SC), the code is working fine, and signature can be checked with other platform (tested with python, node, ...).

On Android, the "saltLength" is not read, and is forced to 32bits, so I can't sign / verify signature from device on other platform if another "saltLength" is used. (I verified it by brute-forcing saltLength value on desktop).

I really don't know how to debug it, the very same Java code has different behavior between launched on desktop or Android. Any idea how to force "saltLength" on Android ?

Thanks in advance !

Serpent GCM is very slow on Android

Hello all,

I implemented Serpent GCM encryption using spongycastle.

public byte[] encrypt(byte[] key, byte[] iv, byte[] pt, byte[] aad,
int tagLength) throws InvalidCipherTextException {
GCMBlockCipher c = new GCMBlockCipher(new SerpentEngine());
c.init(true,
new AEADParameters(new KeyParameter(key), tagLength, iv, aad));
int outsize = c.getOutputSize(pt.length);
byte[] out = new byte[outsize];
int len = c.processBytes(pt, 0, pt.length, out, 0);
c.doFinal(out, len);
return out;
}
It works perfectly on my desktop machine (Windows Core i7). It takes about 200 milliseconds to encrypt 5Mb file. But all of a sudden the same code deployed on Samsung galaxy 4 tablet (Android 5.0.1) takes 40 seconds to do the same encryption of the same file. We tried Huawei Acend G300 (Android 2.3.6) and it takes only 17 seconds.

Could you please give me an idea why it's so dramatically different from Desktop and why the encryption time is faster on much less powerfull device Huawei than on Samsung galaxy s4 tablet?

If there is any way to improve the performance of the code on Android?

Thank you very much in advance for your time!

Vitaly

Auto SC commit deletes and recreates files instead of moving them

Heyo. Cool project!

I have some thoughts on commit 9a2b105 -- you delete org/bouncycastle files and then create them fresh in org/spongycastle. The result is a huge diff and the loss of verification that none of the sources were changed.

Of course I'm not saying you can't be trusted, but given the nature of this library, it's worth considering this.

Am I correct in assuming that you keep rebasing your changes on top of any changes coming from bcgit/bc-java? Because then you could change your auto SC commit to use "git mv", which will do the right thing and track changes across the files and show in the diff that they remain unchanged.

An example, since I recently had to move some files as well:
thialfihar/apg@0bf3d1b
(note the moved files after the handful of changes in the beginning).

Security alert from play store

Your app contains unsafe cryptographic encryption patterns. Please see this Google Help Center article ( https://support.google.com/faqs/answer/9450925 ) for details.Vulnerable classes:Org.spongycastle.openpgp.operator.jcajce.JcePBEKeyEncryptionMethodGenerator.encryptSessionInfo

I am getting this warning for below method implementation.

protected byte[] encryptSessionInfo(int encAlgorithm, byte[] key, byte[] sessionInfo) throws PGPException {
try {
String cName = PGPUtil.getSymmetricCipherName(encAlgorithm);
Cipher c = this.helper.createCipher(cName + "/CFB/NoPadding");
SecretKey sKey = new SecretKeySpec(key, PGPUtil.getSymmetricCipherName(encAlgorithm));
c.init(1, sKey, new IvParameterSpec(new byte[c.getBlockSize()]));
return c.doFinal(sessionInfo, 0, sessionInfo.length);
} catch (IllegalBlockSizeException var7) {
throw new PGPException("illegal block size: " + var7.getMessage(), var7);
} catch (BadPaddingException var8) {
throw new PGPException("bad padding: " + var8.getMessage(), var8);
} catch (InvalidAlgorithmParameterException var9) {
throw new PGPException("IV invalid: " + var9.getMessage(), var9);
} catch (InvalidKeyException var10) {
throw new PGPException("key invalid: " + var10.getMessage(), var10);
}
}

BouncyCastle 1.53 is out

Is there gonna be an update to new BouncyCastle 1.53? This version contains changes in SHA3, which break compatibility with older versions. Its impossible to use BC 1.53 against SC 1.52 without altering the app code.

Reintroducing the mail module?

Hey folks,

the mail module was deprecated a while ago due to the use java.awt.* classes. I managed based on some stackoverflow posts and external dependencies (android-mail) to make the mail module working on android. I know there is already a PR open (#20), but it seems it's out of date and it's diff is way too huge.
Is anyone interested in a working implementation of mail on the android platform?

Spongycastle having openssl issue. App rejected by google play

Hi
I have uploaded an updated apk to play store which has spongycastle added in gradle script.

But the apk got rejected by google play who sent me a message

OpenSSL
The vulnerabilities were addressed in OpenSSL 1.02f/1.01r. To confirm your OpenSSL version, you can do a grep search for:

$ unzip -p YourApp.apk | strings | grep "OpenSSL"

You can find more information and next steps in this Google Help Center article.

I followed the steps and found these

OpenSSLPBKDF
!$PBEWithMD5And128BitAESCBCOpenSSL
!$PBEWithMD5And192BitAESCBCOpenSSL
!$PBEWithMD5And256BitAESCBCOpenSSL
BLorg/spongycastle/crypto/generators/OpenSSLPBEParametersGenerator;
QLorg/spongycastle/jcajce/provider/symmetric/AES$PBEWithMD5And128BitAESCBCOpenSSL;
QLorg/spongycastle/jcajce/provider/symmetric/AES$PBEWithMD5And192BitAESCBCOpenSSL;
QLorg/spongycastle/jcajce/provider/symmetric/AES$PBEWithMD5And256BitAESCBCOpenSSL;
BLorg/spongycastle/jcajce/provider/symmetric/OpenSSLPBKDF$Mappings;
?Lorg/spongycastle/jcajce/provider/symmetric/OpenSSLPBKDF$PBKDF;
9Lorg/spongycastle/jcajce/provider/symmetric/OpenSSLPBKDF;
MLorg/spongycastle/openssl/jcajce/JceOpenSSLPKCS8DecryptorProviderBuilder$1$1;
MLorg/spongycastle/openssl/jcajce/JceOpenSSLPKCS8DecryptorProviderBuilder$1$2;
KLorg/spongycastle/openssl/jcajce/JceOpenSSLPKCS8DecryptorProviderBuilder$1;
ILorg/spongycastle/openssl/jcajce/JceOpenSSLPKCS8DecryptorProviderBuilder;
CLorg/spongycastle/openssl/jcajce/JceOpenSSLPKCS8EncryptorBuilder$1;
ALorg/spongycastle/openssl/jcajce/JceOpenSSLPKCS8EncryptorBuilder;

OpenSSLPBKDF
"PBEWithMD5And128BitAES-CBC-OpenSSL
"PBEWithMD5And192BitAES-CBC-OpenSSL
"PBEWithMD5And256BitAES-CBC-OpenSSL
PBKDF-OpenSSL
Unable to create OpenSSL PBDKF:
+com.android.org.conscrypt.OpenSSLSocketImpl
7org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl
OpenSSLDie
DH_OpenSSL
DSA_OpenSSL
ECDH_OpenSSL
ECDSA_OpenSSL
%s(%d): OpenSSL internal error, assertion failed: %s
You need to read the OpenSSL FAQ, http://www.openssl.org/support/faq.html
OpenSSL CMAC method
OpenSSL PKCS#3 DH method
OpenSSL DH Method
OpenSSL DSA method
OpenSSL EC algorithm
OpenSSL ECDH method
OpenSSL ECDSA method
OpenSSL HMAC method
OpenSSL RSA method
OpenSSL 'dlfcn' shared library method
OpenSSL default
EVP part of OpenSSL 1.0.1c 10 May 2012
cU!
}AES part of OpenSSL 1.0.1c 10 May 2012
ASN.1 part of OpenSSL 1.0.1c 10 May 2012
Big Number part of OpenSSL 1.0.1c 10 May 2012
lhash part of OpenSSL 1.0.1c 10 May 2012
RAND part of OpenSSL 1.0.1c 10 May 2012
SHA1 part of OpenSSL 1.0.1c 10 May 2012
SHA-256 part of OpenSSL 1.0.1c 10 May 2012
DlSHA-512 part of OpenSSL 1.0.1c 10 May 2012
Stack part of OpenSSL 1.0.1c 10 May 2012
Diffie-Hellman part of OpenSSL 1.0.1c 10 May 2012
DSA part of OpenSSL 1.0.1c 10 May 2012
(1ECDH part of OpenSSL 1.0.1c 10 May 2012
ECDSA part of OpenSSL 1.0.1c 10 May 2012
RSA part of OpenSSL 1.0.1c 10 May 2012
X.509 part of OpenSSL 1.0.1c 10 May 2012
ECONF part of OpenSSL 1.0.1c 10 May 2012
MD5 part of OpenSSL 1.0.1c 10 May 2012
CONF_def part of OpenSSL 1.0.1c 10 May 2012
OpenSSLDie
DH_OpenSSL
DSA_OpenSSL
ECDH_OpenSSL
ECDSA_OpenSSL
OpenSSL_add_all_ciphers
OpenSSL_add_all_digests
UI_OpenSSL
%s(%d): OpenSSL internal error, assertion failed: %s
OpenSSL 1.0.0p 8 Jan 2015
OpenSSL default
OpenSSL PKCS#3 DH method
OpenSSL DH Method
OpenSSL DSA method
OpenSSL 'dlfcn' shared library method
OpenSSL EC algorithm
OpenSSL ECDH method
OpenSSL ECDSA method
OpenSSL HMAC method
You need to read the OpenSSL FAQ, http://www.openssl.org/support/faq.html
OpenSSL RSA method
OpenSSL default user interface
AES part of OpenSSL 1.0.0p 8 Jan 2015
ASN.1 part of OpenSSL 1.0.0p 8 Jan 2015
Blowfish part of OpenSSL 1.0.0p 8 Jan 2015
Big Number part of OpenSSL 1.0.0p 8 Jan 2015
CONF_def part of OpenSSL 1.0.0p 8 Jan 2015
CONF part of OpenSSL 1.0.0p 8 Jan 2015
DES part of OpenSSL 1.0.0p 8 Jan 2015
libdes part of OpenSSL 1.0.0p 8 Jan 2015
Diffie-Hellman part of OpenSSL 1.0.0p 8 Jan 2015
DSA part of OpenSSL 1.0.0p 8 Jan 2015
^ECDH part of OpenSSL 1.0.0p 8 Jan 2015
ECDSA part of OpenSSL 1.0.0p 8 Jan 2015
EVP part of OpenSSL 1.0.0p 8 Jan 2015
lhash part of OpenSSL 1.0.0p 8 Jan 2015
MD4 part of OpenSSL 1.0.0p 8 Jan 2015
MD5 part of OpenSSL 1.0.0p 8 Jan 2015
PEM part of OpenSSL 1.0.0p 8 Jan 2015
RAND part of OpenSSL 1.0.0p 8 Jan 2015
RC2 part of OpenSSL 1.0.0p 8 Jan 2015
RC4 part of OpenSSL 1.0.0p 8 Jan 2015
RIPE-MD160 part of OpenSSL 1.0.0p 8 Jan 2015
RSA part of OpenSSL 1.0.0p 8 Jan 2015
SHA1 part of OpenSSL 1.0.0p 8 Jan 2015
SHA-256 part of OpenSSL 1.0.0p 8 Jan 2015
DlSHA-512 part of OpenSSL 1.0.0p 8 Jan 2015
Stack part of OpenSSL 1.0.0p 8 Jan 2015
TXT_DB part of OpenSSL 1.0.0p 8 Jan 2015
X.509 part of OpenSSL 1.0.0p 8 Jan 2015
OpenSSLDie
OpenSSL 1.0.0p 8 Jan 2015
SSLv2 part of OpenSSL 1.0.0p 8 Jan 2015
SSLv3 part of OpenSSL 1.0.0p 8 Jan 2015
TLSv1 part of OpenSSL 1.0.0p 8 Jan 2015

I'm wondering if you can help to give me some advice on this?

Thanks

Spongy Castle: is it obsolete?

Spongy Castle was created back in 2011 because the Android platform bundled an old, restricted subset of Bouncy Castle. Simply adding an updated version of Bouncy Castle to your app resulted in class-clashes and exceptions - so you needed a repackaged & renamed version, like Spongy Castle.

Why might Spongy Castle be obsolete?

As mentioned in the book Android Security Internals by @nelenkov, the org.bouncycastle packages in Android were renamed to com.android.org.bouncycastle starting with Android 3.0 (see also open-keychain/open-keychain#1676 and Android Platform commit 0ac85ead96f - note that the version of BC bundled with Android 4.0 was still a restricted subset). So using Spongy Castle may no longer be necessary, if you can just include an up-to-date version of Bouncy Castle directly.

There are also alternative crypto libraries to consider, like Facebook's Conceal, Google's Conscrypt, libsodium-jni, etc.

Why might Spongy Castle not be obsolete?

  • pre-Android 3.0 devices are still in active use. There are higher areas of use in poorer countries, and those people still need secure cryptography. Signal (not a SC user, so far as I'm aware) currently still supports Android 2.3 and up.
  • even on post-Android 3.0 devices, device manufacturers are not above carelessly bundling libraries, it's possible that Bouncy Castle may still be bundled on some obscure devices.
  • Although the version of Bouncy Castle bundled with Android has a changed package name, it still has "BC" as the provider name, leaving some ambiguity as to the choice of implementation when adding your own copy of Bouncy Castle to the app and choosing "BC" as your provider (thx to David Hook for passing on this point)

So Spongy Castle may still be necessary, if you really do need the functionality of Bouncy Castle on older devices. However it takes non-negligible effort to maintain Spongy Castle, so I'm using this issue to solicit feedback from people on whether they do, or do not, need further releases of Spongy Castle, and also to answer the users who ask "Why hasn't the latest release of Spongy Castle come out yet?"

Why do releases of Spongy Castle lag so far behind Bouncy Castle?

Version Bouncy release Spongy release Lag in days
1.50 3 Dec 2013 26 Jan 2014 54
1.51 25 Jul 2014 26 Jul 2014 1
1.52 2 Mar 2015 15 Jun 2015 105
1.53 12 Oct 2015 18 Oct 2015 6
1.54 29 Dec 2015 29 Dec 2015 0 (thanks to advance warning from @cwgit)
1.55 18 Aug 2016 - ...
1.56 23 Dec 2016 - ...

The Bouncy Castle project has a suite of nearly a thousand tests, and with every new release of Spongy Castle I want to make sure that those tests all pass - I have to make sure I haven't broken anything. In particular, I want to make sure that those tests pass in public CI (eg Travis CI) so that people can reproduce my work.

Unfortunately, this is surprisingly difficult:

  • The Bouncy Castle project itself has no public CI setup, and they've not been able to share their private CI infrastructure with me.
  • Many tests in the suite trigger javax.crypto.JceSecurity.verifyProviderJar() checks that will only pass with one of these two problematic options:
    • Obtain a JCE Code Signing Certificate from Oracle, to sign the Spongy Castle provider for the purpose of the tests - note that the signature is not required for Spongy Castle to operate on Android, just for the tests to pass. I've not yet attempted to go down this path.
    • Avoid the signing requirements during tests by using OpenJDK, specifically OpenJDK 7 or earlier - which is no longer available on the current version of Ubuntu.
  • Generally, with every new release, a new set of tests fail for other reasons too, and investigating those takes time. Some of the fixes I've found I've been able to contribute back to the upstream Bouncy Castle project.

Sunset on a Spongy Castle?

Given the inevitable obsolescence of Spongy Castle, at some point there will be literally no reason to keep on devoting the significant chunk of time it takes to cut a release! That time may not have arrived yet - but for my own sanity, I'd like to know when it does, so I can use my time to do other stuff.

So, please vote on this issue:

  • 👍 to say Spongy Castle is obsolete
  • 👎 to say you still need it

...and if you could add a comment, explaining why you need it, and linking to your project, that would be great and hold much more weight with me.

Is spongycast still updated

I see that the bc-java repository has been updated all the time. Is there no need to adapt to the spongycast?

Javadoc upload

It'd be nice if you could generate the javadocs and upload them e.g. to github sites. Then I can tell my own javadoc run to use your site as a link so where my API exposes Spongy/BouncyCastle stuff, it can auto link to the right javadocs.

Can't use sponcycastle as jce provider in jre

Hi
I'm trying to use spongycastle as a jce prover for a jre in a desktop machine. I can't use bouncycastle for it because it creates a classloader conflict in another place of the machine. I added the core and prov jar's in $JRE/lib/ext and the line:
security.provider.9=org.spongycastle.jce.provider.BouncyCastleProvider

In $JRE/lib/security/java.security
Using this code:
http://www.java2s.com/Code/Java/Security/ListAllProviderAndItsAlgorithms.htm

I can check that spongycastle is correctly loaded but something must be wrong because, later I try to load some https url which must be served by spongycastle and it doesn't work. With an equivalent bouncycastle version it works.
The issue can be tested installing java 1.6, and using this code:
https://github.com/UniconLabs/java-keystore-ssl-test

In this way:
/usr/java/jdk1.6.0_45/bin/java -jar java-keystore-test-0.0.1.jar https://webpre.sedeb2b.com/EdiwinWS/services/geFactGva?wsdl

Before testing add to cacerts the root certificates in https://acedicom.edicomgroup.com/eu/caedicom_en.xml, please

This works when using bouncycastle as additional jce provider but not with spongycastle ¿any idea of what can be happening?

2.x version (IllegalArgumentException not an OID)

I have an issue reported by a user where they are getting an IllegalArgumentException for an OID. I see a number of fixes in the 2.x versions of Bouncy Castle for OID parsing.

Are there plans to release a 2.x version of SpongyCastle?

P.S. User stack trace attached. Apologies that it's a screen shot that's all I have at this time.
spongycastle oid exception

P192 performance

Hi all,
I did some performance tests and comparisons of an app that uses NIST P-192 in spongycastle and was baffled by its bad performance. A simple multiplication takes about 600ms on a Nexus 5. On my (dated) laptop with Core2Duo P8600, BouncyCastle needs ~90ms for the same operation. JavaScript in Firefox (using JSBN) can do the same in about 40ms.

I'm not sure if spongycastle can do anything about this, I just wanted to raise this here in case anyone wonders or fancies to improve performance of the implementation.

spongycastle fails in android API < 21

i am trying to run some spongycastle code in android:

        try {
            Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());
            ECGenParameterSpec spec = new ECGenParameterSpec("P-256");
            KeyPairGenerator generator = KeyPairGenerator.getInstance("ECDSA", "SC");
            generator.initialize(spec, new SecureRandom());
            KeyPair keyPair = generator.generateKeyPair();
            ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
            ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
            String publicKeyStr = publicKey.getW().getAffineX().toString() + ":" + publicKey.getW().getAffineY().toString();
            Log.d(TAG, publicKeyStr);
            Calendar c = Calendar.getInstance();
            Date d0 = c.getTime();
            c.add(Calendar.DATE, 1);
            Date expiry = c.getTime();
            String token = Jwts.builder()
                    .setIssuedAt(d0)
                    .setSubject("00000000-0000-0000-0000-000000000001")
                    .setExpiration(expiry)
                    .signWith(privateKey, SignatureAlgorithm.ES256).compact();
            Log.d(TAG, token);
        } catch (Exception e) {
            Log.d(TAG, e.toString());
        }

in API version 21+, it works as expected.

in API version 18, it works in debug. in release, it fails in function generator.generateKeyPair() with java.lang.IllegalArgumentException: Invalid point.

in API version 16, it fails in function Jwts.builder().signWith() with io.jsonwebtoken.security.SignatureException: Invalid Elliptic Curve PrivateKey. can't recognise key type in ECDSA based signer.

any idea what i am doing wrong?

org.spongycastle.jce.provider.X509LDAPCertStoreSpi imports javax.naming name space

First and foremost: thanks a lot for your effort on making the complete bouncycastle functionality available on android.

Using lint on my own code, I noticed that org.spongycastle.jce.provider.X509LDAPCertStoreSpi in imports several classes from the javax.naming name space, which is not included in Android. Accordingly, the lint check fails. As your fork is aimed at Android in particular, one possible way to deal with this could be to leave out that file and adjust BouncyCastleProvider.java accordingly. If it's ok for you, I can prepare a pull request for you.

The specific lint error message was:

Correctness
InvalidPackage: Package not included in Android
../../../../../../../.gradle/caches/modules-2/files-2.1/com.madgag.spongycastle/prov/1.51.0.0/6755081df770180856ca48694b40cd34c2208128/prov-1.51.0.0.jar: Invalid package reference in library; not included in Android: javax.naming.directory. Referenced from org.spongycastle.jce.provider.X509LDAPCertStoreSpi.
../../../../../../../.gradle/caches/modules-2/files-2.1/com.madgag.spongycastle/prov/1.51.0.0/6755081df770180856ca48694b40cd34c2208128/prov-1.51.0.0.jar: Invalid package reference in library; not included in Android: javax.naming. Referenced from org.spongycastle.jce.provider.X509LDAPCertStoreSpi.
Priority: 6 / 10
Category: Correctness
Severity: Error
Explanation: Package not included in Android.
This check scans through libraries looking for calls to APIs that are not included in Android.

When you create Android projects, the classpath is set up such that you can only access classes in the API packages that are included in Android. However, if you add other projects to your libs/ folder, there is no guarantee that those .jar files were built with an Android specific classpath, and in particular, they could be accessing unsupported APIs such as java.applet.

This check scans through library jars and looks for references to API packages that are not included in Android and flags these. This is only an error if your code calls one of the library classes which wind up referencing the unsupported package.

X509v3Certificate causes handshake failure

Hi, I am using the below code to generate a certificate, store it in the keystore and then initialize an SSLServerSocketFactory. However the client always give a handshake failure.

The exceptions and error handling code it omitted to keep it short.

static {
    Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
}
private static X509Certificate generateCertificate(KeyPair keyPair) {

    long current = System.currentTimeMillis();
    long endOffset = 365 * 24 * 60 * 60 * 1000L;
    long endTimeStamp = current + endOffset;

    Date startDate = new Date(current - 365 * 24 * 60 * 60 * 1000L);
    Date endDate = new Date(endTimeStamp);

    X500NameBuilder issuerNameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    issuerNameBuilder.addRDN(BCStyle.C, "us");
    issuerNameBuilder.addRDN(BCStyle.ST, "az");
    issuerNameBuilder.addRDN(BCStyle.L, "gi");
    issuerNameBuilder.addRDN(BCStyle.O, "sm");
    issuerNameBuilder.addRDN(BCStyle.OU, "sm");
    issuerNameBuilder.addRDN(BCStyle.CN, "zz");
    X500Name issuerX500Name = issuerNameBuilder.build();

    X500Name subjectX500Name = issuerX500Name;

    SecureRandom random = new SecureRandom();

    SubjectPublicKeyInfo subjectPublicKeyInfo =
        SubjectPublicKeyInfo.getInstance(keyPair.getPublic.getEncoded());
    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(
        issuerX500Name,
        new BigInteger(32, random),
        startDate,
        endDate,
        subjectX500Name,
        subjectPublicKeyInfo);

    ContentSigner signer = new JcaContentSignerBuilder(signAlgo).setProvider("SC").build(keyPair.getPrivate())
    return new JcaX509CertificateConverter().setProvider("SC").
        getCertificate(v3CertGen.build(signer));
}

static KeyStore initializeKeyStore() {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);
    KeyPair keyPair = kpg.genKeyPair();

    X509Certificate cert = generateCertificate(keyPair);
    KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
    keyStore.load(null, KEY_STORE_PASSWORD.toCharArray());
    keyStore.setKeyEntry(
                MY_CERT_ALIAS,
                keyPair.getPrivate(),
                MY_CERT_PASSWORD.toCharArray(),
                new Certificate[]{cert});
    return keyStore;
}

// Create SSLServerSocketFactory
static SSLServerSocketFactory createServerSSLSocketFactory(Context context) {
    KeyStore keyStore = initializeKeyStore();

    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    TrustManager[] trustManagers = tmf.getTrustManagers();
    if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
        throw new IllegalStateException("Unexpected default trust managers:" +
            Arrays.toString(trustManagers));
    }

    // Server certificate setup
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, KEY_STORE_PASSWORD.toCharArray());

    SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    SSLServerSocketFactory factory = sslContext.getServerSocketFactory();

    return factory;
}

Then use the below command, I get a handshake failure. I have tried on Google Nexus 5 devices with Android 5.1.1 and 6.0.1. The errors are the same. From the network trace, the client sends a client hello and later the server returns Handshake Failure (40) and shuts down the connection.

openssl s_client -connect 192.168.0.8:10099

Output:

CONNECTED(00000003)
140091672004248:error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure:s23_clnt.c:769:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 7 bytes and written 305 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID: 
    Session-ID-ctx: 
    Master-Key: 
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1527744291
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---

If I use the following code to generate a keystore and push to the Android device, it works with no problem.

keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.bks -storepass password -validity 360 -keysize 2048 -validity 9999 -storetype BKS -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath bcprov-jdk15on-159.jar

Did anyone run into the same issue on Android, or have any idea? Thank you!

JCE Provider Addition

This is not really a bug, but is a problem in the way that the website for SpongyCastle advises users to add the JCE provider.

Currently, the website advertises:

Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);

As the method to use SpongyCastle.

Please change it to:

Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());

The advertised method creates issues by using the Android Key Store on API 18 and up, and sometimes creates issues with the Fingerprint APIs on some devices on API 23 and up.

Also, please inform the user on explicitly using the "SC" provider for all SpongyCastle cryptographic operations, instead of relying on the provider ordering and resolution.

algorithm identifier 1.2.840.10045.2.1 in key not recognised

Hi,
need to convert pkcs8 to pkcs12 so I used this code to load privatekey from pkcs8 file :

public static PrivateKey loadPrivateKey(String keyFile) { try { File f = new File(keyFile); FileInputStream fis = null; fis = new FileInputStream(f); DataInputStream dis = new DataInputStream(fis); byte[] keyBytes = new byte[(int) f.length()]; dis.readFully(keyBytes); dis.close(); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey pk = kf.generatePrivate(spec); return pk; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return null; }

but I have an exception org.spongycastle.jcajce.provider.asymmetric.util.ExtendedInvalidKeySpecException

org.spongycastle.jcajce.provider.asymmetric.util.ExtendedInvalidKeySpecException: unable to process key spec: java.io.IOException: algorithm identifier 1.2.840.10045.2.1 in key not recognised at org.spongycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi.engineGeneratePrivate(KeyFactorySpi.java:105) at java.security.KeyFactory.generatePrivate(KeyFactory.java:186) at org.XXXXXX.loadPrivateKey(CertProvider.java:45) at android.app.Activity.performCreate(Activity.java:5104) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) at android.app.ActivityThread.access$600(ActivityThread.java:141) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5041) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) at dalvik.system.NativeStart.main(Native Method) Caused by: java.io.IOException: algorithm identifier 1.2.840.10045.2.1 in key not recognised at org.spongycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi.generatePrivate(KeyFactorySpi.java:153) at org.spongycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi.engineGeneratePrivate(KeyFactorySpi.java:91) ... 17 more

any indication to solve this? or may SC on android can handle *.pkcs8, so I don't need to convert to pkcs12 (at least for this momment I just need *.pkcs8 files).

THX.

java.lang.IllegalArgumentException: Invalid point

Exception in thread "Thread-1" java.lang.IllegalArgumentException: Invalid point
at org.spongycastle.math.ec.ECAlgorithms.validatePoint(ECAlgorithms.java:193)
at org.spongycastle.math.ec.AbstractECMultiplier.multiply(AbstractECMultiplier.java:22)
at org.spongycastle.crypto.generators.ECKeyPairGenerator.generateKeyPair(ECKeyPairGenerator.java:73)
at org.bitcoinj.core.ECKey.(ECKey.java:179)
at org.bitcoinj.core.ECKey.(ECKey.java:168)

Parsing Master List with Spongy castle return Null Public Key

I am trying to parse the master list using the code below in this link:

Github MasterList Parser

Using this code (Bouncy Castle) I am getting the error below:


        try {
            Enumeration<?> derObjects = ASN1Sequence.getInstance(octets).getObjects();
            CertificateFactory cf = CertificateFactory.getInstance("X.509","BC");

            while (derObjects.hasMoreElements()) {
                ASN1Integer version = (ASN1Integer)derObjects.nextElement(); //Should be 0
//              if (version!=0) throw Exception; //TODO Exception model
                ASN1Set certSet = ASN1Set.getInstance(derObjects.nextElement());

                Enumeration<Certificate> certs = certSet.getObjects();
                while (certs.hasMoreElements()) {
                    org.bouncycastle.asn1.x509.Certificate certAsASN1Object = org.bouncycastle.asn1.x509.Certificate.getInstance(certs.nextElement());
                    cscaCerts.add(cf.generateCertificate(new ByteArrayInputStream(certAsASN1Object.getEncoded())));
                }

            }
java.security.NoSuchAlgorithmException: The BC provider no longer provides an implementation for CertificateFactory.X.509. Please see https://android-developers.googleblog.com/2018/03/cryptography-changes-in-android-p.html for more details.

Using Spongy Castle I am getting null in public key (in object java.security.cert within the list cscaCerts) NO error but after parsing null public key presented.

  try {
            Enumeration<?> derObjects = ASN1Sequence.getInstance(octets).getObjects();

            while (derObjects.hasMoreElements()) {
                ASN1Integer version = (ASN1Integer) derObjects.nextElement(); //Should be 0
//              if (version!=0) throw Exception; //TODO Exception model
                ASN1Set certSet = ASN1Set.getInstance(derObjects.nextElement());

                Enumeration<Certificate> certs = certSet.getObjects();
                while (certs.hasMoreElements()) {
                    org.spongycastle.asn1.x509.Certificate certAsASN1Object = org.spongycastle.asn1.x509.Certificate.getInstance(certs.nextElement());
                    cscaCerts.add(new X509CertificateObject(certAsASN1Object));
                }

            }

Public Key: null

implementation 'com.madgag.spongycastle:prov:1.58.0.0'
implementation 'com.madgag.spongycastle:bcpkix-jdk15on:1.58.0.0'
targetSdk 32 Gradle jdk: 17

NoClassDefFoundError Exception

My application uses Spongy Castle 1.54.0.0 loaded through Maven in Android Studio (I include core, prov, pkix, and pg).

It works fine on my main development devices. I recently tried testing on an older device (Galaxy S3 4.4.2 [API 19]) and I get a this fatal exception whenever the application is loaded.

The exception occurs when loading the library using this in the main application file:

static
{
    Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
}

Here's the full stack trace starting after that call:

java.lang.NoClassDefFoundError: org.spongycastle.util.Arrays
            at org.spongycastle.asn1.ASN1ObjectIdentifier$OidHandle.<init>(ASN1ObjectIdentifier.java:449)
            at org.spongycastle.asn1.ASN1ObjectIdentifier.intern(ASN1ObjectIdentifier.java:425)
            at org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers.<clinit>(PKCSObjectIdentifiers.java:117)
            at org.spongycastle.jcajce.provider.digest.MD2$Mappings.configure(MD2.java:70)
            at org.spongycastle.jce.provider.BouncyCastleProvider.loadAlgorithms(BouncyCastleProvider.java:220)
            at org.spongycastle.jce.provider.BouncyCastleProvider.setup(BouncyCastleProvider.java:135)
            at org.spongycastle.jce.provider.BouncyCastleProvider.access$000(BouncyCastleProvider.java:44)
            at org.spongycastle.jce.provider.BouncyCastleProvider$1.run(BouncyCastleProvider.java:127)
            at java.security.AccessController.doPrivileged(AccessController.java:45)
            at org.spongycastle.jce.provider.BouncyCastleProvider.<init>(BouncyCastleProvider.java:123)

Any idea what's going on? It looks like some dependency might be missing, but those should be taken care of through Maven.

OutOfMemoryError BouncyCastleProvider.addAlgorithm

I have an OOM problem. This is the stacktrace on Firebase Crashlytics.

Fatal Exception: java.lang.OutOfMemoryError: Failed to allocate a 16396 byte allocation with 2088 free bytes and 2088B until OOM
       at java.util.Hashtable.makeTable(Hashtable.java:487)
       at java.util.Hashtable.doubleCapacity(Hashtable.java:507)
       at java.util.Hashtable.put(Hashtable.java:380)
       at java.security.Provider.put(Provider.java:264)
       at org.spongycastle.jce.provider.BouncyCastleProvider.addAlgorithm(BouncyCastleProvider.java)
       at org.spongycastle.jce.provider.BouncyCastleProvider.addAlgorithm(BouncyCastleProvider.java)
       at org.spongycastle.jcajce.provider.symmetric.DSTU7624$Mappings.configure(DSTU7624.java)
       at org.spongycastle.jce.provider.BouncyCastleProvider.loadAlgorithms(BouncyCastleProvider.java)
       at org.spongycastle.jce.provider.BouncyCastleProvider.setup(BouncyCastleProvider.java)
       at org.spongycastle.jce.provider.BouncyCastleProvider.access$000(BouncyCastleProvider.java)
       at org.spongycastle.jce.provider.BouncyCastleProvider$1.run(BouncyCastleProvider.java)
       at java.security.AccessController.doPrivileged(AccessController.java:45)
       at org.spongycastle.jce.provider.BouncyCastleProvider.<init>(BouncyCastleProvider.java)
       at br.com.***.library.securemobiletoken.TokenUtils.<init>(TokenUtils.java)
       at br.com.***.library.securemobiletoken.SecureMobileToken.<init>(SecureMobileToken.java)
       at br.com.***.***.MainActivity.configureSMT(MainActivity.java)
       at br.com.***.***.MainActivity.onCreate(MainActivity.java)
       at android.app.Activity.performCreate(Activity.java:6609)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3113)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3275)
       at android.app.ActivityThread.access$1000(ActivityThread.java:218)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:145)
       at android.app.ActivityThread.main(ActivityThread.java:7007)
       at java.lang.reflect.Method.invoke(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

Probably in our library this line causes the error, but I guess nothing wrong with this that could cause OOM exception.

public TokenUtils() {
        Security.addProvider(new BouncyCastleProvider());
    }

The issue is captured on a device that has android 5.1.1, samsung, Galaxy J3(2016)
Orientation: Portrait
Free space in RAM: 322.4 MB
Free disk space: 1.63 GB

Thanks in advance.

Public Domain - spongycastle-spongy-master.zip

Dear Creator

Would it be okay to use your work [spongycastle-spongy-master.zip] under Creative Commons CC0 v1.0 Universal License (CC0 v1.0)?

The Swiss law do not recognize a permanent relinquishment of Copyrights as the Public Domain provides for.

Thank you very much and kind regards
Philipp

Android Q spongy castle issue

From API level 28, Google has restricted Security provider feature(bouncy castle issue). So alternatively we have added Security provider using spongy castle Now we can able to generate a keypair. But the key pair is not matching with the previous one. We can't get Private keyThis is we used previously,Old code api 27:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC", "BC");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
keyGen.initialize(256, random);
KeyFactory kaif = KeyFactory.getInstance("EC", "BC");
KeyPair pair = keyGen.generateKeyPair();
PrivateKey privateKey = pair.getPrivate();
PublicKey publicKey = pair.getPublic();

After the API level issue, we have removed "BC" and added Bouncy Castle manually by adding the below lineSecurity.insertProviderAt(BouncyCastleProvider(), 1); by implementing Bouncy castle in dependencies, implementation "com.madgag.spongycastle:core:1.58.0.0" implementation "com.madgag.spongycastle:prov:1.58.0.0" But the key pair is not matching with the previous one. New Code:api 28
Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
keyGen.initialize(256, random);
KeyFactory kaif = KeyFactory.getInstance("EC");
KeyPair pair = keyGen.generateKeyPair();
PrivateKey privateKey = pair.getPrivate();
PublicKey publicKey = pair.getPublic();

**Issue:
EC Private Key [f5:ac:ed:47:79:86:8b:7f:ee:54:ed:a3:37:1c:19:e7:8e:43:71:65]
X: 644540eb3c2dba45cb1085c4c063cd5f89d4514585f2108102a94faae8357a11
Y: 11087095e61da377e4a9fb9369a6074c3ba7cf472e0ed9bc57326d60d42de39

EC Public Key [f5:ac:ed:47:79:86:8b:7f:ee:54:ed:a3:37:1c:19:e7:8e:43:71:65]
X: 644540eb3c2dba45cb1085c4c063cd5f89d4514585f2108102a94faae8357a11
Y: 11087095e61da377e4a9fb9369a6074c3ba7cf472e0ed9bc57326d60d42de39

Expectation:
EC Private Key
S: c831bb8b5682e1960b14902b9f4d80b36eb481dabb9ce5b43fa4f8413e3a7198
EC Public Key
X: 1b6015f63670cee9058950e9ad553dbe4bc8f0f0d7b3b366ef7a284b916f3a71
Y: e562f35d5fe84e867525c5b26fd125e56582a1491adb2a21602a27f106b1d5ae**
Private key values differs
MyApplication.zip

Incorrect Secret generation in Tripartite Diffie-Hellman Key Exchange

Secret computation for three parties Diffie-Hellman are inconsistent among each party.
The proof of concept code snippet is listed as follow:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
// I construct DH parameters using IKE 2048 configuration
DHParameterSpec dhparams = TripartiesDH.ike2048();
keyGen.initialize(dhparams);
// Three parties, including A, B, C
KeyPair keyPairA = keyGen.generateKeyPair();
KeyPair keyPairB = keyGen.generateKeyPair();
KeyPair keyPairC = keyGen.generateKeyPair();

KeyAgreement kaA = KeyAgreement.getInstance("DH");
KeyAgreement kaB = KeyAgreement.getInstance("DH");
KeyAgreement kaC = KeyAgreement.getInstance("DH");

kaA.init(keyPairA.getPrivate());
kaB.init(keyPairB.getPrivate());
kaC.init(keyPairC.getPrivate());

// ((g^a)^b)^c
kaA.doPhase(keyPairB.getPublic(), false);
kaA.doPhase(keyPairC.getPublic(), true);
// ((g^b)^a)^c
kaB.doPhase(keyPairA.getPublic(), false);
kaB.doPhase(keyPairC.getPublic(), true);
// ((g^c)^a)^b
kaC.doPhase(keyPairA.getPublic(), false);
kaC.doPhase(keyPairB.getPublic(), true);

byte[] kABC = kaA.generateSecret();
byte[] kBAC = kaB.generateSecret();
byte[] kCAB = kaC.generateSecret();

// Generated secrets are inconsistency
System.out.println("g^a^b^c = "+TripartiesDH.bytesToHex(kABC));
System.out.println("g^a^b^c = "+TripartiesDH.bytesToHex(kBAC));
System.out.println("g^a^b^c = "+TripartiesDH.bytesToHex(kCAB));

My first guess would be doPhase() function was never tested against false flag. But I am not so sure it's a really issue or I have to keep intermediate result for KeyAgreement object while performing the next DH computation.

There are some problems in using Oracle JDK1.8 encryption and decryption, so it does not support it?

hi,
when I useing oracle JDK1.8,get error:

java.lang.SecurityException: JCE cannot authenticate the provider SC
at javax.crypto.Cipher.getInstance(Cipher.java:656)
at com.test.ecc.EckeySCTest.publicEncrypt(EckeySCTest.java:56)
at com.test.ecc.EckeySCTest.test(EckeySCTest.java:71)
at com.test.ecc.EckeySCTest.main(EckeySCTest.java:48)
Caused by: java.util.jar.JarException: file:/D:/blockchain/repository/com/madgag/spongycastle/prov/1.58.0.0/prov-1.58.0.0.jar has unsigned entries - org/spongycastle/jce/MultiCertStoreParameters.class

Nexus scan: CVE-2019-17359

Need to implement the newer BC code...
The ASN.1 parser in Bouncy Castle Crypto (aka BC Java) 1. 63 can trigger a large attempted memory allocation and resultant OutOfMemoryError, via crafted ASN.1 data. This is fixed in 1.64

BouncyCastle 1.55 is out

Just for the record, BouncyCastle 1.55 has been released :)
Can we expect SpongyCastle 1.55 to be rolled out anytime soon?

Many thanks!

Retrieve ECC Public Key from Base64 encoded string

I've been trying to create an instance of java.security.PublicKey using a Base64 encoded ECC public key.

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        byte[] data = decodePublicKey("AsIAEFjzIcX+Kvhe8AmLoGUc8aYAEAwf5ecREGZ2u4RLxQuav/A=");
        PublicKey publicKey = loadPublicKey("secp128r1", data);

        Log.d(TAG, publicKey.toString());
    } catch (SQLException | IOException | GeneralSecurityException e) {
        Log.e(TAG, e.getMessage(), e);
    }
}

private byte[] decodePublicKey(String s) throws UnsupportedEncodingException {
    return Base64.decode(s, Base64.DEFAULT);
}

public PublicKey loadPublicKey(String curve, byte[] data)
        throws SQLException, IOException, GeneralSecurityException {
    Log.d(TAG, Arrays.toString(data));
    // [2, -62, 0, 16, 88, -13, 33, -59, -2, 42, -8, 94, -16, 9, -117, -96, 101, 28, -15, -90, 0, 16, 12, 31, -27, -25, 17, 16, 102, 118, -69, -124, 75, -59, 11, -102, -65, -16]
    Log.d(TAG, "Length :" + String.valueOf(data.length));

    KeyFactory factory = KeyFactory.getInstance("ECDSA", "SC");
    ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curve);
    ECCurve eccCurve = spec.getCurve();
    Log.d(TAG, "Curve: " + eccCurve);

    EllipticCurve ellipticCurve = EC5Util.convertCurve(eccCurve, spec.getSeed());

    // decoding point fails, 
    // line no 66.
    ECPoint point = ECPointUtil.decodePoint(ellipticCurve, data);
    ECParameterSpec params = EC5Util.convertSpec(ellipticCurve, spec);

    ECPublicKeySpec keySpec = new ECPublicKeySpec(point, params);
    return factory.generatePublic(keySpec);
}

Logcat:

Process: com.example.eccdemo, PID: 21151
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.eccdemo/com.example.eccdemo.MainActivity}: java.lang.IllegalArgumentException: Incorrect length for compressed encoding
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2329)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
        at android.app.ActivityThread.access$900(ActivityThread.java:147)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
 Caused by: java.lang.IllegalArgumentException: Incorrect length for compressed encoding
        at org.spongycastle.math.ec.ECCurve.decodePoint(ECCurve.java:349)
        at org.spongycastle.jce.ECPointUtil.decodePoint(ECPointUtil.java:52)
        at com.example.eccdemo.MainActivity.loadPublicKey(MainActivity.java:66)
        at com.example.eccdemo.MainActivity.onCreate(MainActivity.java:45)
        at android.app.Activity.performCreate(Activity.java:5933)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
        at android.app.ActivityThread.access$900(ActivityThread.java:147)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

Further Inspection:

In Logcat, upon printing the decoded bytes, they actually differ from the one on the server:

    Log.d(TAG, Arrays.toString(data));
    [2, -62, 0, 16, 88, -13, 33, -59, -2, 42, -8, 94, -16, 9, -117, -96, 101, 28, -15, -90, 0, 16, 12, 31, -27, -25, 17, 16, 102, 118, -69, -124, 75, -59, 11, -102, -65, -16]

In python console:

In [131]: [_ for _ in ap.public_key.tobytes()]
Out[131]: [2, 194, 0, 16, 88, 243, 33, 197, 254, 42, 248, 94, 240, 9, 139, 160, 101, 28, 241, 166, 0, 16, 12, 31, 229, 231, 17, 16, 102, 118, 187, 132, 75, 197, 11, 154, 191, 240]

It would be great if someone can explain the reason to this anomaly, and also help me out on the small snippets to get PublicKey and PrivateKey instances from the respective encoded Strings.

Failing to load ECDSA public key with SC

Just ignore this. I was doing it wrong.
Since I saw people with the same problem, I thought it was a SC problem, but it wasn't.

Thank you for your work with SC.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.