question
stringlengths 11
28.2k
| answer
stringlengths 26
27.7k
| tag
stringclasses 130
values | question_id
int64 935
78.4M
| score
int64 10
5.49k
|
---|---|---|---|---|
I am looking for a cross platform way to share public keys for ECDSA signing. I had a great thing going from a performance perspective with CngKey and the standard .NET crypto libraries, but then I couldn't figure out how a 33 (or 65) byte public key (using secp256r1/P256) was getting turned into 104 bytes by MS.. Ergo, I couldn't support cross platform signing and verifying..
I'm using BouncyCastle now, but holy handgranade is it SLOW!
So, looking for suggestions for the following requirements:
Cross platform/Languages (server is .NET, but this is served up via a JSON/Web.API interface)
JavaScript, Ruby, Python, C++ etc..
Not crazy as slow on the server
Not so painfully slow people can't use it on the client.
The client has to be able to sign the message, the server has to be able to validate the signature with a public key that was exchanged at registration to the service.
Anyways, Ideas would be awesome... Thanks
| So I have figured out the format of a CngKey exported in ECCPublicKeyBlob and ECCPrivateKeyBlob. This should allow others to interop between other key formats and CngKey for Elliptcal Curve signing and such.
ECCPrivateKeyBlob is formatted (for P256) as follows
[KEY TYPE (4 bytes)][KEY LENGTH (4 bytes)][PUBLIC KEY (64 bytes)][PRIVATE KEY (32 Bytes)]
KEY TYPE in HEX is 45-43-53-32
KEY LENGTH in HEX is 20-00-00-00
PUBLIC KEY is the uncompressed format minus the leading byte (which is always 04 to signify an uncompressed key in other libraries)
ECCPublicKeyBlob is formatted (for P256) as follows
[KEY TYPE (4 bytes)][KEY LENGTH (4 bytes)][PUBLIC KEY (64 bytes)]
KEY TYPE in HEX is 45-43-53-31
KEY LENGTH in HEX is 20-00-00-00
PUBLIC KEY is the uncompressed format minus the leading byte (which is always 04 to signify an uncompressed key in other libraries)
So given a uncompressed Public key in Hex from another language, you can trim the first byte, add those 8 bytes to the front and import it using
CngKey.Import(key,CngKeyBlobFormat.EccPrivateBlob);
Note: The key blob format is documented by Microsoft.
The KEY TYPE and KEY LENGTH are defined in BCRYPT_ECCKEY_BLOB struct as:
{ ulong Magic; ulong cbKey; }
ECC public key memory format:
BCRYPT_ECCKEY_BLOB
BYTE X[cbKey] // Big-endian.
BYTE Y[cbKey] // Big-endian.
ECC private key memory format:
BCRYPT_ECCKEY_BLOB
BYTE X[cbKey] // Big-endian.
BYTE Y[cbKey] // Big-endian.
BYTE d[cbKey] // Big-endian.
The MAGIC values available in .NET are in Microsoft's official GitHub dotnet/corefx BCrypt/Interop.Blobs.
internal enum KeyBlobMagicNumber : int
{
BCRYPT_ECDH_PUBLIC_P256_MAGIC = 0x314B4345,
BCRYPT_ECDH_PRIVATE_P256_MAGIC = 0x324B4345,
BCRYPT_ECDH_PUBLIC_P384_MAGIC = 0x334B4345,
BCRYPT_ECDH_PRIVATE_P384_MAGIC = 0x344B4345,
BCRYPT_ECDH_PUBLIC_P521_MAGIC = 0x354B4345,
BCRYPT_ECDH_PRIVATE_P521_MAGIC = 0x364B4345,
BCRYPT_ECDSA_PUBLIC_P256_MAGIC = 0x31534345,
BCRYPT_ECDSA_PRIVATE_P256_MAGIC = 0x32534345,
BCRYPT_ECDSA_PUBLIC_P384_MAGIC = 0x33534345,
BCRYPT_ECDSA_PRIVATE_P384_MAGIC = 0x34534345
BCRYPT_ECDSA_PUBLIC_P521_MAGIC = 0x35534345,
BCRYPT_ECDSA_PRIVATE_P521_MAGIC = 0x36534345,
...
...
}
| Bouncy Castle | 24,251,336 | 20 |
Does anyone know of a simple tutorial or sample code of how to sign data in c# using bouncy castle. In Java there are tons of tutorials and samples. I can't find a single example in c#. Does anyone know how to do this?
| Okay I could not find any documentation on how to do this. But I ended up figuring it out.
I am pasting the full code here so hopefully it can help someone in the future.
This class will calculate a RSA signature with a sha1 hash for the provided string and verify it as well.
using System;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
namespace API.Crypto
{
public class RsaSha1Signing
{
private RsaKeyParameters MakeKey(String modulusHexString, String exponentHexString, bool isPrivateKey)
{
var modulus = new Org.BouncyCastle.Math.BigInteger(modulusHexString, 16);
var exponent = new Org.BouncyCastle.Math.BigInteger(exponentHexString, 16);
return new RsaKeyParameters(isPrivateKey, modulus, exponent);
}
public String Sign(String data, String privateModulusHexString, String privateExponentHexString)
{
/* Make the key */
RsaKeyParameters key = MakeKey(privateModulusHexString, privateExponentHexString, true);
/* Init alg */
ISigner sig = SignerUtilities.GetSigner("SHA1withRSA");
/* Populate key */
sig.Init(true, key);
/* Get the bytes to be signed from the string */
var bytes = Encoding.UTF8.GetBytes(data);
/* Calc the signature */
sig.BlockUpdate(bytes, 0, bytes.Length);
byte[] signature = sig.GenerateSignature();
/* Base 64 encode the sig so its 8-bit clean */
var signedString = Convert.ToBase64String(signature);
return signedString;
}
public bool Verify(String data, String expectedSignature, String publicModulusHexString, String publicExponentHexString)
{
/* Make the key */
RsaKeyParameters key = MakeKey(publicModulusHexString, publicExponentHexString, false);
/* Init alg */
ISigner signer = SignerUtilities.GetSigner("SHA1withRSA");
/* Populate key */
signer.Init(false, key);
/* Get the signature into bytes */
var expectedSig = Convert.FromBase64String(expectedSignature);
/* Get the bytes to be signed from the string */
var msgBytes = Encoding.UTF8.GetBytes(data);
/* Calculate the signature and see if it matches */
signer.BlockUpdate(msgBytes, 0, msgBytes.Length);
return signer.VerifySignature(expectedSig);
}
}
}
| Bouncy Castle | 8,830,510 | 19 |
I am trying to use C# to read in a .pem file that contains only a RSA public key. I do not have access to the private key information, nor does my application require it. The file myprivatekey.pem file begins with
-----BEGIN PUBLIC KEY-----
and ends with
-----END PUBLIC KEY-----.
My current code is as follows:
Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair;
using (var reader = File.OpenText(@"c:\keys\myprivatekey.pem"))
keyPair = (Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair)new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
However the code throws an InvalidCastException with the message
Unable to cast object of type
'Org.BouncyCastle.Crypto.Parameters.DsaPublicKeyParameters' to type
'Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair'.
How can I use Bouncy Castle's PemReader to read only a public key, when no private key information is available?
| The following code will read a public key from a given filename. The exception handling should be changed for any production code. This method returns an AsymetricKeyParameter:
public Org.BouncyCastle.Crypto.AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename)
{
var fileStream = System.IO.File.OpenText(pemFilename);
var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(fileStream);
var KeyParameter = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)pemReader.ReadObject();
return KeyParameter;
}
| Bouncy Castle | 11,346,200 | 19 |
let me start by saying I'm extremely new to all of this. What I am trying to do is to use gpg from within Java in order to decrypt an encrypted file.
What I've done successfully:
Had a colleague encrypt a file using my public key and his private key and successfully decrypted it.
Went the other way
Had another colleague try to decrypt a file that wasn't for him: fail (as expected)
My key was generated like this...
(gpg --version tells me I'm using 1.4.5 and I'm using Bouncy Castle 1.47)
gpg --gen-ley
Select option "DSA and Elgamal (default)"
Fill in the other fields and generate a key.
The file was encrypted using my public key and another's secret key. I want to decrypt it. I've written the following Java code to accomplish this. I'm using several deprecated methods, but I can't figure out how to properly implement the factory methods required to use the non-deprecated versions, so if anyone has an idea on implementations of those that I should be using that would be a nice bonus.
Security.addProvider(new BouncyCastleProvider());
PGPSecretKeyRingCollection secretKeyRing = new PGPSecretKeyRingCollection(new FileInputStream(new File("test-files/secring.gpg")));
PGPSecretKeyRing pgpSecretKeyRing = (PGPSecretKeyRing) secretKeyRing.getKeyRings().next();
PGPSecretKey secretKey = pgpSecretKeyRing.getSecretKey();
PGPPrivateKey privateKey = secretKey.extractPrivateKey("mypassword".toCharArray(), "BC");
System.out.println(privateKey.getKey().getAlgorithm());
System.out.println(privateKey.getKey().getFormat());
PGPObjectFactory pgpF = new PGPObjectFactory(
new FileInputStream(new File("test-files/test-file.txt.gpg")));
Object pgpObj = pgpF.nextObject();
PGPEncryptedDataList encryptedDataList = (PGPEncryptedDataList) pgpObj;
Iterator objectsIterator = encryptedDataList.getEncryptedDataObjects();
PGPPublicKeyEncryptedData publicKeyEncryptedData = (PGPPublicKeyEncryptedData) objectsIterator.next();
InputStream inputStream = publicKeyEncryptedData.getDataStream(privateKey, "BC");
So when I run this code I learn that my algorithm and format are as follows for my secret key:
Algorithm: DSA
Format: PKCS#8
And then it breaks on the last line:
Exception in thread "main" org.bouncycastle.openpgp.PGPException: error setting asymmetric cipher
at org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder.decryptSessionData(Unknown Source)
at org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder.access$000(Unknown Source)
at org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder$2.recoverSessionData(Unknown Source)
at org.bouncycastle.openpgp.PGPPublicKeyEncryptedData.getDataStream(Unknown Source)
at org.bouncycastle.openpgp.PGPPublicKeyEncryptedData.getDataStream(Unknown Source)
at org.bouncycastle.openpgp.PGPPublicKeyEncryptedData.getDataStream(Unknown Source)
at org.bouncycastle.openpgp.PGPPublicKeyEncryptedData.getDataStream(Unknown Source)
at TestBouncyCastle.main(TestBouncyCastle.java:74)
Caused by: java.security.InvalidKeyException: unknown key type passed to ElGamal
at org.bouncycastle.jcajce.provider.asymmetric.elgamal.CipherSpi.engineInit(Unknown Source)
at org.bouncycastle.jcajce.provider.asymmetric.elgamal.CipherSpi.engineInit(Unknown Source)
at javax.crypto.Cipher.init(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
... 8 more
I'm open to a lot of suggestions here, from "don't use gpg, use x instead" to "don't use bouncy castle, use x instead" to anything in between. Thanks!
| If anyone is interested to know how to encrypt and decrypt gpg files using bouncy castle openPGP library, check the below java code:
The below are the 4 methods you going to need:
The below method will read and import your secret key from .asc file:
public static PGPSecretKey readSecretKeyFromCol(InputStream in, long keyId) throws IOException, PGPException {
in = PGPUtil.getDecoderStream(in);
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(in, new BcKeyFingerprintCalculator());
PGPSecretKey key = pgpSec.getSecretKey(keyId);
if (key == null) {
throw new IllegalArgumentException("Can't find encryption key in key ring.");
}
return key;
}
The below method will read and import your public key from .asc file:
@SuppressWarnings("rawtypes")
public static PGPPublicKey readPublicKeyFromCol(InputStream in) throws IOException, PGPException {
in = PGPUtil.getDecoderStream(in);
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in, new BcKeyFingerprintCalculator());
PGPPublicKey key = null;
Iterator rIt = pgpPub.getKeyRings();
while (key == null && rIt.hasNext()) {
PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next();
Iterator kIt = kRing.getPublicKeys();
while (key == null && kIt.hasNext()) {
PGPPublicKey k = (PGPPublicKey) kIt.next();
if (k.isEncryptionKey()) {
key = k;
}
}
}
if (key == null) {
throw new IllegalArgumentException("Can't find encryption key in key ring.");
}
return key;
}
The below 2 methods to decrypt and encrypt gpg files:
public void decryptFile(InputStream in, InputStream secKeyIn, InputStream pubKeyIn, char[] pass) throws IOException, PGPException, InvalidCipherTextException {
Security.addProvider(new BouncyCastleProvider());
PGPPublicKey pubKey = readPublicKeyFromCol(pubKeyIn);
PGPSecretKey secKey = readSecretKeyFromCol(secKeyIn, pubKey.getKeyID());
in = PGPUtil.getDecoderStream(in);
JcaPGPObjectFactory pgpFact;
PGPObjectFactory pgpF = new PGPObjectFactory(in, new BcKeyFingerprintCalculator());
Object o = pgpF.nextObject();
PGPEncryptedDataList encList;
if (o instanceof PGPEncryptedDataList) {
encList = (PGPEncryptedDataList) o;
} else {
encList = (PGPEncryptedDataList) pgpF.nextObject();
}
Iterator<PGPPublicKeyEncryptedData> itt = encList.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData encP = null;
while (sKey == null && itt.hasNext()) {
encP = itt.next();
secKey = readSecretKeyFromCol(new FileInputStream("PrivateKey.asc"), encP.getKeyID());
sKey = secKey.extractPrivateKey(new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass));
}
if (sKey == null) {
throw new IllegalArgumentException("Secret key for message not found.");
}
InputStream clear = encP.getDataStream(new BcPublicKeyDataDecryptorFactory(sKey));
pgpFact = new JcaPGPObjectFactory(clear);
PGPCompressedData c1 = (PGPCompressedData) pgpFact.nextObject();
pgpFact = new JcaPGPObjectFactory(c1.getDataStream());
PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject();
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
InputStream inLd = ld.getDataStream();
int ch;
while ((ch = inLd.read()) >= 0) {
bOut.write(ch);
}
//System.out.println(bOut.toString());
bOut.writeTo(new FileOutputStream(ld.getFileName()));
//return bOut;
}
public static void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey) throws IOException, NoSuchProviderException, PGPException {
Security.addProvider(new BouncyCastleProvider());
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
comData.close();
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(new BcPGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.TRIPLE_DES).setSecureRandom(new SecureRandom()));
cPk.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey));
byte[] bytes = bOut.toByteArray();
OutputStream cOut = cPk.open(out, bytes.length);
cOut.write(bytes);
cOut.close();
out.close();
}
Now here is how to invoke/run the above:
try {
decryptFile(new FileInputStream("encryptedFile.gpg"), new FileInputStream("PrivateKey.asc"), new FileInputStream("PublicKey.asc"), "yourKeyPassword".toCharArray());
PGPPublicKey pubKey = readPublicKeyFromCol(new FileInputStream("PublicKey.asc"));
encryptFile(new FileOutputStream("encryptedFileOutput.gpg"), "fileToEncrypt.txt", pubKey);
} catch (PGPException e) {
fail("exception: " + e.getMessage(), e.getUnderlyingException());
}
| Bouncy Castle | 14,993,223 | 19 |
I'm implementing a factory pattern for 3 different cryptography classes. The factory will determine which one to create and then get a serialized instance of the correct class from a database and return it to the requester.
Right now I'm working on serializing the classes to store them in the database. I'm writing one for a PGP cryptography class called BouncyCastle. I can create the class and the keys from files but when I try to serialize it, it says that the two member variables, which are objects of class PgpPublicKey, and PgpPrivateKey, cannot be serialized because they do not have parameterless constructors.
public void createdBouncyFromFiles()
{
var bc = new BouncyCastle("C:\\TestFiles\\BouncyPublicKey.txt", "C:\\TestFiles\\BouncyPrivateKey.txt", "Password1");
var xmlSerializer = new XmlSerializer(bc.GetType());
var textWriter = new StringWriter();
xmlSerializer.Serialize(textWriter, bc);
var theSerializedClass = textWriter.ToString();
}
The class has two member variables that are the problem.
public class BouncyCastle : ICryptographyProvider
{
public PgpPublicKey m_publicKey;
public PgpPrivateKey m_privateKey;
public string m_passPhrase;
// cut out the irelevant parts
This is the public key class. No parameterless constructor.
public class PgpPublicKey
{
public PgpPublicKey(PublicKeyAlgorithmTag algorithm, AsymmetricKeyParameter pubKey, DateTime time);
// cut other methods
}
| Any Serializer Class need a parameterless constructor because, while deserializing it create an empty new instance, then it copies every public property taken from seialized data.
You can easily make the constructor private, if you want to avoid to create it without parameters.
EX:
public class PgpPublicKey
{
public PgpPublicKey(PublicKeyAlgorithmTag algorithm, AsymmetricKeyParameter pubKey, DateTime time);
private PgpPublicKey();
// cut other methods
}
| Bouncy Castle | 15,212,051 | 19 |
I have a problem with reading certificate information. I want to read full information using java with bouncycastle library in Android programmatically. Now, i'm just using keytool command in console:
>keytool -list -keystore 1.p12 -storetype pkcs12 -v
Any suggestions?
| I've found solution, the main idea is to cast certificate to x509, then get the SubjectDN and parse values.
public class TestClass {
public static void main(String[] args) throws Exception {
KeyStore p12 = KeyStore.getInstance("pkcs12");
p12.load(new FileInputStream("pkcs.p12"), "password".toCharArray());
Enumeration<String> e = p12.aliases();
while (e.hasMoreElements()) {
String alias = e.nextElement();
X509Certificate c = (X509Certificate) p12.getCertificate(alias);
Principal subject = c.getSubjectDN();
String subjectArray[] = subject.toString().split(",");
for (String s : subjectArray) {
String[] str = s.trim().split("=");
String key = str[0];
String value = str[1];
System.out.println(key + " - " + value);
}
}
}
}
| Bouncy Castle | 16,970,302 | 19 |
The case: I am maintaining a Java applet which uses the BouncyCastle libraries bcpkix-jdk15on-149.jar, and bcprov-jdk15on-149.jar.
Problem is when the applet is run on a JRE version 7_u40 enabled browser.
The behavior has changed from version 7_u25 in a way that it always prompts a modal window like "Security prompt for an app using a self-signed certificate" (which cannot be permanently hidden anymore), just to trust bcprov.
https://www.java.com/en/download/help/appsecuritydialogs.xml
As far as I know, this is because BC libraries are signed with the BouncyCastle certificate, issued by the "JCE Code Signing CA".
Because of that, the lib can perform and act as a cryptography provider.
BUT: the JRE can not build the certificate chain to trust the signature. It shows "provider : UNKNOWN"
I know i can remove that signature and sign by myself (I own a Thawte code sign certificate):
it works with bcpkix lib
it does not work with bcprov because it won't be considered as a valid cryptography provider (it won't be trusted by the JRE).
Am I right?
What can I do?
PS: I googled a lot to find the JCA root cert (to put it into the JRE truststore), without success... Is there a way to grab that root CA?
| After a lot of search and some post in BC mailing list.... I found the solution, so I drop it here for others who may face that issue:
The solution is basically to sign the BC library a second time with my own certificate.
The JAR needs the JCA signature in order to be trusted as a cryptography provider, so do not remove it.
The JAR also needs (in addition) a code signature in order to be able to be run in the JVM (trusted by the JRE).
One last thing, some incompatibility happened on the signature technology:
BC lib is signed using SHA1 digest algorythm
jarsigner (on my computer) is doing the signature with SHA256 digest algorythm by default, which leads to a verification failure.
So I had to ask jarsigner to do it the SHA1 way. (for some reason both signatures have to be consistent from that point of view)
Here is the magic parameter of jarsigner command to add and make it happen:
-digestalg SHA1
Sample command:
jarsigner -keystore ./mykeystore.jks -storepass myPass -digestalg SHA1 bcprov-jdk15on-149.jar myAlias
... and you're done!
The following post gave me the tip: What prevents Java from verifying signed jars with multiple signature algorithms
| Bouncy Castle | 19,029,575 | 19 |
Is it possible to read the RSA private key of format PKCS1 in JAVA without converting to PKCS8? if yes, sample code is appreciated.
-----BEGIN RSA PRIVATE KEY-----
BASE64 ENCODED DATA
-----END RSA PRIVATE KEY-----
| Java does not come with out-of-the-box support for PKCS1 keys. You can however use Bouncycastle
PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
Object object = pemParser.readObject();
KeyPair kp = converter.getKeyPair((PEMKeyPair) object);
PrivateKey privateKey = kp.getPrivate();
| Bouncy Castle | 41,934,846 | 19 |
I'm trying to add BouncyCastle as a security provider on Windows XP Pro so I can use it to add some certs to an Android application per the instructions here. Unfortunately I can't get it to add the provider.
I've:
Downloaded the provider to C:\Program Files\Java\jre6\lib\ext\.
Added C:\Program Files\Java\jre6\lib\ext\bcprov-jdk16-146.jar to %CLASSPATH%.
Added security.provider.7=org.bouncycastle.jce.provider.BouncyCastleProvider to java.security (7 being the next int in the order).
When I run:
keytool -import -v -trustcacerts -alias 0 -file mycert.crt -keystore mystore.bks -storetype BKS -providerName org.bouncycastle.jce.provider.BouncyCastleProvider -storepass mypassword
I get the following error message:
keytool error: java.lang.ClassNotFoundException: org.bouncycastle.jce.provider.BouncyCastleProvider
I've also tried adding it dynamically:
import java.security.Provider;
import java.security.Security;
import java.util.Enumeration;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class BouncyCastleMain {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider()); // add it
try { // list them out
Provider p[] = Security.getProviders();
for (int i = 0; i < p.length; i++) {
System.out.println(p[i]);
for (Enumeration<?> e = p[i].keys(); e.hasMoreElements();)
System.out.println("\t" + e.nextElement());
}
} catch (Exception e) {
System.out.println(e);
}
}
}
At first I got an access error when compiling the java class, but changed it to a warning per the suggestion here. Now when I run the code it shows BouncyCastle in the list of providers but it doesn't stick around after the program is done.
I'm sure it must be doable, but I'm stymied over how to get this guy installed long enough to run keytool using it. Is it possible to run keytool via a java API, or could there be some step I've missed that will make the provider stick around?
Thanks!
| The -providerName option requires a provider name ("BC", in this case), not a class name. An alternative option, -providerClass, does require a class name, and it is useful when the provider isn't registered in the java.security file.
When you register a provider "programatically", it is only temporary. Your program must re-register its provider each time it runs. You won't be able to use this approach if your goal is to make BouncyCastle available to keytool.
Since you've already installed the provider (by putting the archive in lib/ext and listing it in java.security), using the -providerName BC option is probably the easiest solution. Alternatively, you can use the -providerClass org.bouncycastle.jce.provider.BouncyCastleProvider option.
By the way, you should not use the CLASSPATH environment variable. Libraries in lib/ext are on the class path already.
If, after correcting the options, you still get a NoSuchProviderException (using -providerName) or ClassNotFoundException (using -providerClass), verify that you are using the right copy of keytool. That is, when executing, specify the full path of keytool, rather than relying on your PATH variable. Make sure that the path refers to the JRE into which BouncyCastle was installed. It isn't uncommon for a system to have multiple JREs and JDKs.
| Bouncy Castle | 5,914,108 | 18 |
I'm having issues with Bouncycastle, which only arise when running the :lint task.
Generally it seems to be a Java 9 byte-code version 53.0 / ASM version conflict.
These are the dependencies:
// https://mvnrepository.com/artifact/org.bouncycastle
implementation "org.bouncycastle:bcprov-jdk15on:1.64"
implementation "org.bouncycastle:bcpkix-jdk15on:1.64"
Which cause the :lint task to throw processing errors:
> Task :mobile:lint
Error processing bcpkix-jdk15on-1.64.jar:META-INF/versions/9/module-info.class: broken class file? (This feature requires ASM6)
Error processing bcprov-jdk15on-1.64.jar:META-INF/versions/9/module-info.class: broken class file? (This feature requires ASM6)
META-INF/versions/9/module-info.class: broken class file? (This feature requires ASM6)
The same goes for:
// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation "com.google.code.gson:gson:2.8.6"
Since upgrading from 1.4.1 to 1.4.2-native-mt, it's the same again:
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2-native-mt"
kotlin-stdlib-1.4.0.jar:META-INF\versions\9\module-info.class: broken class file? (Module requires ASM6)
| As already mentioned this was introduced in Java 9, that Android does not support. You could just use packagingOptions to remove those classes.
android {
packagingOptions {
exclude "**/module-info.class"
}
}
This should not affect actual executed code and should also remove classes for lint checks as lint is working on bytecode.
| Bouncy Castle | 60,598,110 | 18 |
How do I implement AES encryption with the java bouncy castle library? Example code or a link to example code would be nice :)
| If you download the bcprov source, you'll see the class org.bouncycastle.jce.provider.test.AESTest. It shows you how to set up the bouncyCastle provider, create encryption and decryption Cipher objects, set up CipherOutputStreams and call the write methods on those streams.
Edit:
seems like link is broken. Look here for AESTest
| Bouncy Castle | 2,435,338 | 17 |
I'm developing some cryptography on BlackBerry, and we're working with certificates. We use BouncyCastle Lightweight API instead of RIM api to apply the cryptography, but in the lightweight API PEMWriter doesn't work (Well, it isn't included because it needs some JCE).
public RSAPrivateCrtKeyParameters _RSAPrivateKey;
public RSAKeyParameters _RSAPublicKey;
I get this keys from the object
AsymmetricCipherKeyPair theKeyPair
So, i need a method to BASE64Encode the two keys, or how to transform this keys to other objects that can be directly transformed to base64/PEM format. I can generate the certificate manually, but i need the encoding of the keys.
I know there are methods to do this, but all require PEMWriter or APIs that are not enabled with j2ME and the bouncycastle lightweight API.
| You could look into the PEMWriter/PEMReader code of bouncy castle and use their implementation as a reference:
PemWriter
PemReader
| Bouncy Castle | 14,750,082 | 17 |
We have an application that creates PDFs unsing jasperreports.
It also manipulates said PDFs using iText after they have been created.
We recently started using encryption on some PDF. That means before the app can handle the PDF after its creation, it has to be decrypted. While attempting to do so using iText's PdfReader(String path, byte[] password) I get the following exception:
java.lang.VerifyError: class org.bouncycastle.asn1.ASN1Primitive overrides final method equals.(Ljava/lang/Object;)Z
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at com.simontuffs.onejar.JarClassLoader.defineClass(JarClassLoader.java:561)
at com.simontuffs.onejar.JarClassLoader.findClass(JarClassLoader.java:475)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at com.itextpdf.text.pdf.PdfEncryption.<init>(PdfEncryption.java:148)
at com.itextpdf.text.pdf.PdfReader.readDecryptedDocObj(PdfReader.java:914)
at com.itextpdf.text.pdf.PdfReader.readDocObj(PdfReader.java:1294)
at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:643)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:187)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:212)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:202)
The project is built as a runnable .jar using Maven and uses the following dependencies:
iText 5.4.2
bouncycastle 1.48
I should mention that jasperreports has its own dependency of iText and bouncycastle:
iText 2.1.7
bouncycastle 1.38
I can't figure out what's going on on and need help.
| My best guess is that you have ended up with two different versions of Bouncy Castle on your classpath, and it happened so that the classloader has loaded the superclass from one version and is now trying to load the subclass from the other. The versions are different in that one of them defines a final equals method.
| Bouncy Castle | 17,212,410 | 17 |
Normally when I grab an X509Certificate2 out of my keystore I can call .PrivateKey to retrieve the cert's private key as an AsymmetricAlgorithm. However I have decided to use Bouncy Castle and its instance of X509Certificate only has a getPublicKey(); I cannot see a way to get the private key out of the cert. Any ideas?
I get the an X509Certificate2 from my Windows-MY keystore then use:
//mycert is an X509Certificate2 retrieved from Windows-MY Keystore
X509CertificateParser certParser = new X509CertificateParser();
X509Certificate privateCertBouncy = certParser.ReadCertificate(mycert.GetRawCertData());
AsymmetricKeyParameter pubKey = privateCertBouncy.GetPublicKey();
//how do i now get the private key to make a keypair?
Is there anyway to convert a AsymmetricAlgorithm(C# private key) to a AsymmetricKeyParameter(bouncycastle private key)?
| Akp = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(this.Certificate.PrivateKey).Private;
| Bouncy Castle | 3,240,222 | 16 |
I'm building a network application that uses BouncyCastle as a cryptography provider. Let's say you have this to generate a keypair:
ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("prime192v1");
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
g.initialize(ecSpec, new SecureRandom());
KeyPair pair = g.generateKeyPair();
I'm confused as to why you're getting an instance of an ECDSA KeyPairGenerator. Why doesn't it just say EC? I know that there's an ECDH Key type that is shipped with BouncyCastle, but I thought that the two represented the same stuff about the points on the curve -- or am I completely wrong with the theory behind it?
The reason that I ask is that right now my application uses ECDH fine to establish an AES secret key, but now I want to use the same EC key to sign each message using ECDSA.
| ECDSA and ECDH are from distinct standards (ANSI X9.62 and X9.63, respectively), and used in distinct contexts. X9.63 explicitly reuses elements from X9.62, including the standard representation of public keys (e.g. in X.509 certificates). Hence, ECDSA and ECDH key pairs are largely interchangeable. Whether a given implementation will permit such exchange, however, is an open question. Historically, (EC)DSA and (EC)DH come from distinct worlds.
Note, though, that usage contexts are quite distinct. There is a bit more to cryptography than computations on elliptic curves; the "key lifecycle" must be taken into account. In plain words, you do not want to manage key agreement keys and signature keys with the same procedures. For instance, if you lose your key agreement key (your dog eats your smartcard -- do not laugh, it really happens), then you can no longer decrypt data which was encrypted relatively to that key (e.g. encrypted emails sent to you, and stored in encrypted format). From a business point of view, the loss of a key can also be the loss of an employee (the employee was fired, and was struck by a bus, or retired, or whatever). Hence, encryption keys (including key agreement keys) must often be escrowed (for instance, a copy of the private key is printed and stored in a safe). On the other hand, loss of a signature key implies no data loss; previously issued signatures can still be verified; recovering from such a loss is as simple as creating a new key pair. However, the existence of an escrow system tends to automatically strip signatures of any legal value that could be attached to them.
Also, on a more general basis, I would strongly advise against using the same private key in two distinct algorithms: interactions between algorithms have not been fully explored (simply studying one algorithm is already hard work). For instance, what happens if someone begins to feed your ECDH-based protocol with curve points extracted from ECDSA signatures which you computed with the same private key ?
So you really should not reuse the same key for ECDH and ECDSA.
| Bouncy Castle | 4,969,570 | 16 |
What's the best way to integrate the Bouncy Castle provider in a Java program?
I know I can add it programmatically, by using:
import org.bouncycastle.jce.provider.BouncyCastleProvider;
...
Security.addProvider(new BouncyCastleProvider());
Or either I can add it to a path in the JRE on my machine.
What's the best choice?
| In my opinion the adding it as security provider with own code is the best option.
This is because it is only project dependent - not system dependent. Add the BouncyCastle jar file(s) to your project and add them to the class-path and that's it. It will work on all systems without need for further manual installation steps.
If you install BouncyCastle into the JRE you always have problems in case you have to update the JRE.
| Bouncy Castle | 6,442,012 | 16 |
I have a bunch of root and intermediate certificates given as byte arrays, and I also have end user certificate. I want to build a certificate chain for given end user certificate. In .NET framework I can do it like this:
using System.Security.Cryptography.X509Certificates;
static IEnumerable<X509ChainElement>
BuildCertificateChain(byte[] primaryCertificate, IEnumerable<byte[]> additionalCertificates)
{
X509Chain chain = new X509Chain();
foreach (var cert in additionalCertificates.Select(x => new X509Certificate2(x)))
{
chain.ChainPolicy.ExtraStore.Add(cert);
}
// You can alter how the chain is built/validated.
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreWrongUsage;
// Do the preliminary validation.
var primaryCert = new X509Certificate2(primaryCertificate);
if (!chain.Build(primaryCert))
throw new Exception("Unable to build certificate chain");
return chain.ChainElements.Cast<X509ChainElement>();
}
How to do it in BouncyCastle? I tried with code below but I get PkixCertPathBuilderException: No certificate found matching targetContraints:
using Org.BouncyCastle;
using Org.BouncyCastle.Pkix;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Store;
static IEnumerable<X509Certificate> BuildCertificateChainBC(byte[] primary, IEnumerable<byte[]> additional)
{
X509CertificateParser parser = new X509CertificateParser();
PkixCertPathBuilder builder = new PkixCertPathBuilder();
// Separate root from itermediate
List<X509Certificate> intermediateCerts = new List<X509Certificate>();
HashSet rootCerts = new HashSet();
foreach (byte[] cert in additional)
{
X509Certificate x509Cert = parser.ReadCertificate(cert);
// Separate root and subordinate certificates
if (x509Cert.IssuerDN.Equivalent(x509Cert.SubjectDN))
rootCerts.Add(new TrustAnchor(x509Cert, null));
else
intermediateCerts.Add(x509Cert);
}
// Create chain for this certificate
X509CertStoreSelector holder = new X509CertStoreSelector();
holder.Certificate = parser.ReadCertificate(primary);
// WITHOUT THIS LINE BUILDER CANNOT BEGIN BUILDING THE CHAIN
intermediateCerts.Add(holder.Certificate);
PkixBuilderParameters builderParams = new PkixBuilderParameters(rootCerts, holder);
builderParams.IsRevocationEnabled = false;
X509CollectionStoreParameters intermediateStoreParameters =
new X509CollectionStoreParameters(intermediateCerts);
builderParams.AddStore(X509StoreFactory.Create(
"Certificate/Collection", intermediateStoreParameters));
PkixCertPathBuilderResult result = builder.Build(builderParams);
return result.CertPath.Certificates.Cast<X509Certificate>();
}
Edit: I added the line that fixed my problem. It's commented with all caps. Case closed.
| I've done this in Java a number of times. Given that the API seems to be a straight port of the Java one I'll take a stab.
I'm pretty sure when you add the store to the builder, that collection is expected to contain all certs in the chain to be built, not just intermediate ones. So rootCerts and primary should be added.
If that doesn't solve the problem on its own I would try also specifying the desired cert a different way. You can do one of two things:
Implement your own Selector that always only matches your desired cert (primary in the example).
Instead of setting holder.Certificate, set one or more criteria on holder. For instance, setSubject, setSubjectPublicKey, setIssuer.
Those are the two most common problems I had with PkixCertPathBuilder.
| Bouncy Castle | 10,724,594 | 16 |
I am looking for an example or tutorial to generate X509 Certificates using BC in Java.
A lot of example are having/using deprecated API. I gave a look at BC, but it doesn't show which class does what or no proper documentation/example.
Please If any one you are having idea about it, please point me to a tutorial where I can use BC to generate X509 Certificates. [Generation and writing the public and private keys to files]
| Creation of KeyPairGenerator:
private KeyPairGenerator createKeyPairGenerator(String algorithmIdentifier,
int bitCount) throws NoSuchProviderException,
NoSuchAlgorithmException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(
algorithmIdentifier, BouncyCastleProvider.PROVIDER_NAME);
kpg.initialize(bitCount);
return kpg;
}
Creation of keyPair:
private KeyPair createKeyPair(String encryptionType, int byteCount)
throws NoSuchProviderException, NoSuchAlgorithmException
{
KeyPairGenerator keyPairGenerator = createKeyPairGenerator(encryptionType, byteCount);
KeyPair keyPair = keyPairGenerator.genKeyPair();
return keyPair;
}
KeyPair keyPair = createKeyPair("RSA", 4096);
Converting things to PEM (can be written to file):
private String convertCertificateToPEM(X509Certificate signedCertificate) throws IOException {
StringWriter signedCertificatePEMDataStringWriter = new StringWriter();
JcaPEMWriter pemWriter = new JcaPEMWriter(signedCertificatePEMDataStringWriter);
pemWriter.writeObject(signedCertificate);
pemWriter.close();
return signedCertificatePEMDataStringWriter.toString();
}
Creation of X509Certificate:
X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
serverCertificate, new BigInteger("1"),
new Date(System.currentTimeMillis()),
new Date(System.currentTimeMillis() + 30L * 365L * 24L * 60L * 60L * 1000L),
jcaPKCS10CertificationRequest.getSubject(),
jcaPKCS10CertificationRequest.getPublicKey()
/*).addExtension(
new ASN1ObjectIdentifier("2.5.29.35"),
false,
new AuthorityKeyIdentifier(keyPair.getPublic().getEncoded())*/
).addExtension(
new ASN1ObjectIdentifier("2.5.29.19"),
false,
new BasicConstraints(false) // true if it is allowed to sign other certs
).addExtension(
new ASN1ObjectIdentifier("2.5.29.15"),
true,
new X509KeyUsage(
X509KeyUsage.digitalSignature |
X509KeyUsage.nonRepudiation |
X509KeyUsage.keyEncipherment |
X509KeyUsage.dataEncipherment));
Signing:
ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").build(signingKeyPair.getPrivate());
X509CertificateHolder x509CertificateHolder = certificateBuilder.build(sigGen);
org.spongycastle.asn1.x509.Certificate eeX509CertificateStructure =
x509CertificateHolder.toASN1Structure();
return eeX509CertificateStructure;
}
private X509Certificate readCertificateFromASN1Certificate(
org.spongycastle.asn1.x509.Certificate eeX509CertificateStructure,
CertificateFactory certificateFactory)
throws IOException, CertificateException { //
// Read Certificate
InputStream is1 = new ByteArrayInputStream(eeX509CertificateStructure.getEncoded());
X509Certificate signedCertificate =
(X509Certificate) certificateFactory.generateCertificate(is1);
return signedCertificate;
}
CertificateFactory:
certificateFactory = CertificateFactory.getInstance("X.509",
BouncyCastleProvider.PROVIDER_NAME);
| Bouncy Castle | 14,930,381 | 16 |
I am developing an application that needs to validate SHA256withECDSAsignatures with the help of secp256r1 (NIST P-256, P-256, prime256v1) public keys.
The public keys are generated by a different application at some earlier point in time and stored in my database in hex encoding. The format of the hex string here is equivalent to the hex string OpenSSL would generate when calling openssl ec -in x.pem -noout -text on a file x.pem that has previously been generated by openssl ecparam -genkey -name secp256r1 -out x.pem.
The message and signature are received from a different application.
Consider the following test data:
// Stored in Database
byte[] pubKey = DatatypeConverter.parseHexBinary("049a55ad1e210cd113457ccd3465b930c9e7ade5e760ef64b63142dad43a308ed08e2d85632e8ff0322d3c7fda14409eafdc4c5b8ee0882fe885c92e3789c36a7a");
// Received from Other Application
byte[] message = DatatypeConverter.parseHexBinary("54686973206973206a75737420736f6d6520706f696e746c6573732064756d6d7920737472696e672e205468616e6b7320616e7977617920666f722074616b696e67207468652074696d6520746f206465636f6465206974203b2d29");
byte[] signature = DatatypeConverter.parseHexBinary("304402205fef461a4714a18a5ca6dce6d5ab8604f09f3899313a28ab430eb9860f8be9d602203c8d36446be85383af3f2e8630f40c4172543322b5e8973e03fff2309755e654");
Now this should be a valid signature.
My objective is to validate the signature over the message using the Java and/or Bouncycastle crypto API. I have created a method isValidSignaturefor that:
private static boolean isValidSignature(byte[] pubKey, byte[] message,
byte[] signature) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, InvalidKeySpecException {
Signature ecdsaVerify = Signature.getInstance("SHA256withECDSA", new BouncyCastleProvider());
ecdsaVerify.initVerify(getPublicKeyFromHex(pubKey));
ecdsaVerify.update(message);
return ecdsaVerify.verify(signature);
}
I have tried to extract the public key:
KeyFactory.generatePublic:
private static PublicKey getPublicKeyFromHex(byte[] pubKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
KeyFactory fact = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider());
return fact.generatePublic(new X509EncodedKeySpec(pubKey));
}
But this throws a java.security.spec.InvalidKeySpecException (DER length more than 4 bytes: 26).
What can I do to parse this?
| The Bouncy Castle example code on elliptic curve key pair Generation and key factories got me pretty close.
Once I managed to create a ECDSA key factory and a curve specification for the secp256r1/NIST P-256/P-256/prime256v1 curve I was able to use ECPointUtil.decodePoint to obtain a curve point. I could then generate a public key specification that enabled me to generate a public key like this:
private PublicKey getPublicKeyFromBytes(byte[] pubKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("prime256v1");
KeyFactory kf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider());
ECNamedCurveSpec params = new ECNamedCurveSpec("prime256v1", spec.getCurve(), spec.getG(), spec.getN());
ECPoint point = ECPointUtil.decodePoint(params.getCurve(), pubKey);
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params);
ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKeySpec);
return pk;
}
| Bouncy Castle | 26,159,149 | 16 |
Perhaps my expectations are wrong. I am not an cryptography expert, I'm just a simple user. I have exhaustively tried to make this work with no success so far.
Background information:
I'm trying to port a Legacy Encryption from Delphi Encryption Compendium which is using Blowfish Engine (TCipher_Blowfish_)with CTS operation mode (cmCTS). The private key is hashed by RipeMD256(THash_RipeMD256).
Problems:
The input plain text array of bytes needs to be the same size of CIPHER_BLOCK. As far as I can tell it shouldn't.
From Wikipedia:
In cryptography, ciphertext stealing (CTS) is a general method of using a block cipher mode of operation that allows for processing of messages that are not evenly divisible into blocks without resulting in any expansion of the ciphertext, at the cost of slightly increased complexity.
The output is not the same as the old routine:
I'm using:
Same IV
Same Password
Same input plain text
The legacy application is using ANSI String, the new one uses Unicode, so for every input string I've called Encoding.ASCII.GetBytes("plainText"), Encoding.ASCII.GetBytes("privatepassword").
The private password bytes is then hashed by RipeMD256, I've checked the output bytes and they are the same.
I can confirm the problem is specific in the Bouncy Clastle (operation mode or missing configuration/step) because I've downloaded a second library Blowfish.cs and using an input of 8 bytes (same size as the cipher block) and using the Encrypt_CBC(bytes[]) with the same IV results in the same output as the legacy format.
This is the sketch of the code i'm using for both Blowfish.cs and Bouncy Castle:
Delphi Encryption Compendium
var
IV: Array [0..7] of Byte (1,2,3,4,5,6,7,8);
Key: String = '12345678';
with TCipher_Blowfish.Create('', nil) do
begin
try
InitKey(Key, @IV); //Key is auto hashed using RIPE256 here;
Result:= CodeString('12345678', paEncode, -1); //Output bytes is later encoded as MIME64 here, the result is the hash.
finally
Free;
end;
end;
Blofish.cs
var hashOfPrivateKey = HashValue(Encoding.ASCII.GetBytes("12345678"));
Blowfish b = new BlowFish(hashOfPrivateKey);
b.IV = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8};
var input = Encoding.ASCII.GetBytes("12345678");
var output = b.Encrypt_CBC(input);
I assume that CTS and CBC will always have the same result if the input is 8 bits length. Is this just lucky/coincidence or is fundamentally truth?
Bouncy Castle
IBufferedCipher inCipher = CipherUtilities.GetCipher("BLOWFISH/CTS");
var hashOfPrivateKey = HashValue(Encoding.ASCII.GetBytes("12345678"));
var key = new KeyParameter(hashOfPrivateKey);
var IV = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8};
var cipherParams = new ParametersWithIV(key, IV);
inCipher.Init(true, cipherParams);
var input = Encoding.ASCII.GetBytes("12345678");
//try one: direct with DoFinal
var output = inCipher.DoFinal(input);
// output bytes different from expected
inCipher.Reset();
//try two: ProcessBytes then DoFinal
var outBytes = new byte[input.Length];
var res = inCipher.ProcessBytes(input, 0, input.Length, outBytes, 0);
var r = inCipher.DoFinal(outBytes, res);
// outBytes bytes different from expected
As I said, I'm comparing CBC with CTS based on the assumption that given a 8 bytes input, the output will be the same. I cannot forward the implementation with Bouncy Castle if even with the same input the output is not the same.
I Don't Know:
If the CTS Mode used in Delphi Encryption Compendium uses CBC along with CTS. I Couldn't find documented anywhere.
The difference between calling just DoFinal() and ProcessBytes() then DoFinal() in Bouncy Castle, I imagine that is required when the input block is larger than engine block size, in this case they are the same size.
If Delphi Encryption Compendium is correct/wrong or If Bouncy Castle is correct/wrong. I don't have enough knowledge in cryptography to understand the implementation, otherwise I wouldn't ask a question here (I need guidance).
|
I assume that CTS and CBC will always have the same result if the
input is 8 bits length. Is this just lucky/coincidence or is
fundamentally truth?
No, this is a false statement.
Here is the quote from Wikipedia:
Ciphertext stealing for CBC mode doesn't necessarily require the
plaintext to be longer than one block. In the case where the plaintext
is one block long or less, the Initialization vector (IV) can act as
the prior block of ciphertext.
So even for your case of 8-byte input, CTS algorithm comes into play and affects the output. Basically your statement about CTS and CBS equality could be reversed:
CTS and CBC will always have the same result up to last two blocks.
You could verify it with the following sample:
static byte[] EncryptData(byte[] input, string algorithm)
{
IBufferedCipher inCipher = CipherUtilities.GetCipher(algorithm);
var hashOfPrivateKey = HashValue(Encoding.ASCII.GetBytes("12345678"));
var key = new KeyParameter(hashOfPrivateKey);
var IV = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 };
var cipherParams = new ParametersWithIV(key, IV);
inCipher.Init(true, cipherParams);
return inCipher.DoFinal(input);
}
static void Main(string[] args)
{
var data = Encoding.ASCII.GetBytes("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF");
var ctsResult = EncryptData(data, "BLOWFISH/CTS");
var cbcResult = EncryptData(data, "BLOWFISH/CBC");
var equalPartLength = data.Length - 2 * 8;
var equal = ctsResult.Take(equalPartLength).SequenceEqual(cbcResult.Take(equalPartLength));
}
So this is basically the answer to your main question. You should not expect the same output for CTS and CBC on 8-byte input.
Here are answers (I hope) to your other questions:
If the CTS Mode used in Delphi Encryption Compendium uses CBC along
with CTS. I Couldn't find documented anywhere.
I haven't found any documentation for CTS mode in Delphi Encryption Compendium either, however there are such comments in the source code:
cmCTSx = double CBC, with CFS8 padding of truncated final block
Modes cmCTSx, cmCFSx, cmCFS8 are proprietary modes developed by me.
These modes works such as cmCBCx, cmCFBx, cmCFB8 but with double
XOR'ing of the inputstream into Feedback register.
So seems like CTS mode is implemented in custom way in Delphi Encryption Compendium which will not be compatible with standard implementation by Bouncy Castle.
The difference between calling just DoFinal() and ProcessBytes() then
DoFinal() in Bouncy Castle, I imagine that is required when the input
block is larger than engine block size, in this case they are the same
size.
Calls pair ProcessBytes() / DoFinal() is required if you encrypt data sequentially. It could be required for example if huge data is streamed. However if you have a routine that takes whole byte array for encryption, you could just call following convenient overload of DoFinal() once:
var encryptedData = inCipher.DoFinal(plainText);
This DoFinal() overload will calculate the size of output buffer and make required calls of ProcessBytes() and DoFinal() under the hood.
If Delphi Encryption Compendium is correct/wrong or If Bouncy Castle
is correct/wrong. I don't have enough knowledge in cryptography to
understand the implementation, otherwise I wouldn't ask a question
here (I need guidance).
Let's sum up here:
You should not expect the same output for CTS and CBC for 8-byte input.
Seems like Delphi Encryption Compendium uses custom algorithm for CTS. Since Bouncy Castle is implemented according to the standards, these libraries will produce different results. If your new application is not required to support encrypted data produced with legacy Delphi application, then you could just use Bouncy Castle and be OK. In other case, you should use the same custom CTS algorithm that Delphi Encryption Compendium uses, which will require port of its sources to C#, unfortunately.
UPDATE
(More details on Delphi Encryption Compendium implementation in version 3.0)
Here is a CTS encoding code from DEC version 3.0:
S := @Source;
D := @Dest;
// ...
begin
while DataSize >= FBufSize do
begin
XORBuffers(S, FFeedback, FBufSize, D);
Encode(D);
XORBuffers(D, FFeedback, FBufSize, FFeedback);
Inc(S, FBufSize);
Inc(D, FBufSize);
Dec(DataSize, FBufSize);
end;
if DataSize > 0 then
begin
Move(FFeedback^, FBuffer^, FBufSize);
Encode(FBuffer);
XORBuffers(S, FBuffer, DataSize, D);
XORBuffers(FBuffer, FFeedback, FBufSize, FFeedback);
end;
end;
Here we see double XOR'ing that was mentioned in DEC documentation. Basically this code implements the following algorithm:
C[i] = Encrypt( P[i] xor F[i-1] )
F[i] = F[i-1] xor C[i]
F[0] = IV
while standard algorithm would be:
C[i] = Encrypt( P[i] xor C[i-1] )
C[0] = IV
The step F[i] = F[i-1] xor C[i] is DEC author invention and makes the encryption results differ. The handling of last two blocks that is crucial for CTS mode is also implemented not by a standard.
Here is a comment from DEC v 3.0 ReadMe.txt that describes why the author added such modification:
cmCTS Mode, XOR's the Data before and now after the encryption. This
has better Securityeffect when using a InitVector, the Output is
secure when a bad InitVector is used, ca 1% Speed lossed
It's a very common mistake when authors of security libraries try to make underlying algorithms 'more secure' by such naive modifications. In many cases such changes have a reverse effect and decrease protection strength.
Another drawback of course is that encrypted data could not be decrypted by other libraries implemented according to the standard, like in your case.
| Bouncy Castle | 42,249,867 | 16 |
Can anyone show me (or provide a link to) an example of how to encrypt a file in Java using bouncy castle? I've looked over bouncycastle.org but cannot find any documentation of their API. Even just knowing which classes to use would be a big help for me to get started!
| What type of encryption do you want to perform? Password-based (PBE), symmetric, asymmetric? Its all in how you configure the Cipher.
You shouldn't have to use any BouncyCastle specific APIs, just the algorithms it provides. Here is an example that uses the BouncyCastle PBE cipher to encrypt a String:
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class PBE {
private static final String salt = "A long, but constant phrase that will be used each time as the salt.";
private static final int iterations = 2000;
private static final int keyLength = 256;
private static final SecureRandom random = new SecureRandom();
public static void main(String [] args) throws Exception {
Security.insertProviderAt(new BouncyCastleProvider(), 1);
String passphrase = "The quick brown fox jumped over the lazy brown dog";
String plaintext = "hello world";
byte [] ciphertext = encrypt(passphrase, plaintext);
String recoveredPlaintext = decrypt(passphrase, ciphertext);
System.out.println(recoveredPlaintext);
}
private static byte [] encrypt(String passphrase, String plaintext) throws Exception {
SecretKey key = generateKey(passphrase);
Cipher cipher = Cipher.getInstance("AES/CTR/NOPADDING");
cipher.init(Cipher.ENCRYPT_MODE, key, generateIV(cipher), random);
return cipher.doFinal(plaintext.getBytes());
}
private static String decrypt(String passphrase, byte [] ciphertext) throws Exception {
SecretKey key = generateKey(passphrase);
Cipher cipher = Cipher.getInstance("AES/CTR/NOPADDING");
cipher.init(Cipher.DECRYPT_MODE, key, generateIV(cipher), random);
return new String(cipher.doFinal(ciphertext));
}
private static SecretKey generateKey(String passphrase) throws Exception {
PBEKeySpec keySpec = new PBEKeySpec(passphrase.toCharArray(), salt.getBytes(), iterations, keyLength);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWITHSHA256AND256BITAES-CBC-BC");
return keyFactory.generateSecret(keySpec);
}
private static IvParameterSpec generateIV(Cipher cipher) throws Exception {
byte [] ivBytes = new byte[cipher.getBlockSize()];
random.nextBytes(ivBytes);
return new IvParameterSpec(ivBytes);
}
}
| Bouncy Castle | 2,052,213 | 15 |
I've being messing around the C# Bouncy Castle API to find how to do a PBKDF2 key derivation.
I am really clueless right now.
I tried reading through the Pkcs5S2ParametersGenerator.cs and PBKDF2Params.cs files but i really cant figure out how to do it.
According to the research I have done so far, PBKDF2 requires a string (or char[]) which is the password, a salt and an iteration count.
So far the most promising and most obvious i've come so far is the PBKDF2Params and Pkcs5S2ParametersGenerator.
None of these seems to be accepting a string or a char[].
Has anyone done this in C# or have any clue about this? Or perhaps someone who has implemented BouncyCastle in Java and can help?
Thanx a lot in advance :)
UPDATE: I have found how to do this in Bouncy Castle. Look below for answer :)
| After hours and hours of going through the code, I found that the easiest way to do this is to take a few parts of the code in Pkcs5S2ParametersGenerator.cs and create my own class which of course use other BouncyCastle API's. This works perfectly with the Dot Net Compact Framework (Windows Mobile). This is the equivalent of Rfc2898DeriveBytes class which is not present in the Dot Net Compact Framework 2.0/3.5. Well, maybe not the EXACT equivalent but does the job :)
This is PKCS5/PKCS#5
The PRF (Pseudo Random Function) which is used will be HMAC-SHA1
First things, first. Download the Bouncy Castle compiled assembly from http://www.bouncycastle.org/csharp/, add the BouncyCastle.Crypto.dll as a reference to your project.
After that create new class file with the code below.
using System;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
namespace PBKDF2_PKCS5
{
class PBKDF2
{
private readonly IMac hMac = new HMac(new Sha1Digest());
private void F(
byte[] P,
byte[] S,
int c,
byte[] iBuf,
byte[] outBytes,
int outOff)
{
byte[] state = new byte[hMac.GetMacSize()];
ICipherParameters param = new KeyParameter(P);
hMac.Init(param);
if (S != null)
{
hMac.BlockUpdate(S, 0, S.Length);
}
hMac.BlockUpdate(iBuf, 0, iBuf.Length);
hMac.DoFinal(state, 0);
Array.Copy(state, 0, outBytes, outOff, state.Length);
for (int count = 1; count != c; count++)
{
hMac.Init(param);
hMac.BlockUpdate(state, 0, state.Length);
hMac.DoFinal(state, 0);
for (int j = 0; j != state.Length; j++)
{
outBytes[outOff + j] ^= state[j];
}
}
}
private void IntToOctet(
byte[] Buffer,
int i)
{
Buffer[0] = (byte)((uint)i >> 24);
Buffer[1] = (byte)((uint)i >> 16);
Buffer[2] = (byte)((uint)i >> 8);
Buffer[3] = (byte)i;
}
// Use this function to retrieve a derived key.
// dkLen is in octets, how much bytes you want when the function to return.
// mPassword is the password converted to bytes.
// mSalt is the salt converted to bytes
// mIterationCount is the how much iterations you want to perform.
public byte[] GenerateDerivedKey(
int dkLen,
byte[] mPassword,
byte[] mSalt,
int mIterationCount
)
{
int hLen = hMac.GetMacSize();
int l = (dkLen + hLen - 1) / hLen;
byte[] iBuf = new byte[4];
byte[] outBytes = new byte[l * hLen];
for (int i = 1; i <= l; i++)
{
IntToOctet(iBuf, i);
F(mPassword, mSalt, mIterationCount, iBuf, outBytes, (i - 1) * hLen);
}
//By this time outBytes will contain the derived key + more bytes.
// According to the PKCS #5 v2.0: Password-Based Cryptography Standard (www.truecrypt.org/docs/pkcs5v2-0.pdf)
// we have to "extract the first dkLen octets to produce a derived key".
//I am creating a byte array with the size of dkLen and then using
//Buffer.BlockCopy to copy ONLY the dkLen amount of bytes to it
// And finally returning it :D
byte[] output = new byte[dkLen];
Buffer.BlockCopy(outBytes, 0, output, 0, dkLen);
return output;
}
}
}
So how to use this function? Simple! :)
This is a very simple example where the password and the salt is provided by the user.
private void cmdDeriveKey_Click(object sender, EventArgs e)
{
byte[] salt = ASCIIEncoding.UTF8.GetBytes(txtSalt.Text);
PBKDF2 passwordDerive = new PBKDF2();
// I want the key to be used for AES-128, thus I want the derived key to be
// 128 bits. Thus I will be using 128/8 = 16 for dkLen (Derived Key Length) .
//Similarly if you wanted a 256 bit key, dkLen would be 256/8 = 32.
byte[] result = passwordDerive.GenerateDerivedKey(16, ASCIIEncoding.UTF8.GetBytes(txtPassword.Text), salt, 1000);
//result would now contain the derived key. Use it for whatever cryptographic purpose now :)
//The following code is ONLY to show the derived key in a Textbox.
string x = "";
for (int i = 0; i < result.Length; i++)
{
x += result[i].ToString("X");
}
txtResult.Text = x;
}
How to check whether this is correct?
There is an online javascript implementation of PBKDF2
http://anandam.name/pbkdf2/
I got consistent results :)
Please report if anyone is getting an incorrect result :)
Hope this helps someone :)
UPDATE: Confirmed working with test vectors provided here
https://datatracker.ietf.org/doc/html/draft-josefsson-pbkdf2-test-vectors-00
UPDATE:
Alternatively, for the salt we can use a RNGCryptoServiceProvider. Make sure to reference the System.Security.Cryptography namespace.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] salt = new byte[16];
rng.GetBytes(salt);
| Bouncy Castle | 3,210,795 | 15 |
I want to use a self-signed signature for ssl connections. I'm following this post.
My problem: After creating the Keystore my integrity-check fails.
Keytool-Error: java.io.IOException: KeyStore integrity check failed.
I'm still searching but maybe someone can save me some time.
| Make sure you are using the right password to open the keystore. I was having this error and turns out I was still using the password from the example code in trusted.load()
| Bouncy Castle | 13,125,609 | 15 |
I'm trying to make an HTTPS connection to a server that has a certificate set to expire in April 2013 and uses GlobalSign as the root certificate.
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
// urlConnection.setSSLSocketFactory(sslSocketFactory);
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
// Send the POST data
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
out.write(postParamString.toString().getBytes("UTF8"));
// Read the reply
InputStream in = urlConnection.getInputStream();
As it stands, this throws javax.net.ssl.SSLHandshakeException: org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate signature. when getOutputStream() is called.
This same site and certificate are valid in the stock HTC web browser and desktop browsers. When I use the same code to access Google it works (but then complains about a 404 error). Various posts on StackOverflow imply that it should "just work" and others say to set up your own key store (or disable all HTTPS validation!) I assume the difference in behaviour is down to different root key stores in use (Can anyone clarify this?).
I've now tried creating a key store using bouncy castle but I can't get this to load on my device.
After exporting the certificate from Firefox, I create a key store using:
keytool.exe -import -alias onlinescoutmanager -file www.onlinescoutmanager.co.uk.crt -storetype BKS -keystore res\raw\keystore
This is then loaded and used in the application using:
InputStream stream = context.getResources().openRawResource(R.raw.keystore);
// BKS seems to be the default but we want to be explicit
KeyStore ks = KeyStore.getInstance("BKS");
ks.load(stream, "www.onlinescoutmanager.co.uk".toCharArray());
stream.close();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
SSLContext context2 = SSLContext.getInstance("TLS");
context2.init(null, new TrustManager[] { defaultTrustManager }, null);
sslSocketFactory = context2.getSocketFactory();
This is failing with java.io.IOException: Wrong version of key store. when keystore.Load() is called.
I have ensured I'm passing -storetype BKS, used a <=7 character keystore password, added the CA certs to the key store, and using both Bouncy Castle version 1.45 and 1.47 to create the key store with no change in the reported error message.
My environment is Eclipse Juno 4.2.1 with JRE 1.7u9b5 running on Windows 8. The device I'm testing on is an HTC sensation running stock Android 2.3. The application has a minimum SDK version of 7 and a target of 15.
If anyone can explain how to create a valid BKS key store on Windows 8 or how I can get Java to use the same key store as the browser(or system?) that would be appreciated.
You can download the entire project as it was at the time of writing, and the generated keystore if required.
| Thanks to various people for their hints on this, there are multiple things that all needed to be correct for it to work.
If the HTTPS site's certificate is signed by a trusted root certificate then it will work out of the box without a custom SSLSocketFactory.
The trusted root certificates CAN be different to that used by a browser so don't assume that if it works in the Android web browser then it will work in your app.
If it's not a trusted root certificate and you get exceptions like javax.net.ssl.SSLHandshakeException: org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate signature., then you need to create and load a key store as below.
The key store needs to be generated using the Bouncy Castle provider (1) by specifying -storetype bks on the keytool command line.
If Bouncy Castle is not installed correctly then this will fail with various exceptions including java.security.KeyStoreException: BKS not found.
If the key store is not created with the Bouncy Castle provider then you may get the java.io.IOException: Wrong version of key store. exception, causing confusion with the next case.
You need to use an appropriate version (1, 2, 3) of the Bouncy Castle provider. In most cases, this seems to be version 1.46.
This can be put into your JRE's lib/ext/ folder and the class name added to lib/security/java.security, or specified directly on the command line to keytool.
If it's an incompatible version (or store type) you will get exceptions along the lines of java.io.IOException: Wrong version of key store. again.
You must include all intermediary and the root certificate. If any are missing, you will get a javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. exception.
The certificate chain MUST be in order for them to be validated correctly. If they aren't you will either get javax.net.ssl.SSLHandshakeException: org.bouncycastle.jce.exception.ExtCertPathValidatorException: IssuerName(CN=XYZ) does not match SubjectName(CN=ABC) of signing certificate. or again, a generic javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
I have not found a way to order them in the key store so resorted to doing it in code at runtime.
Some people have suggested that using a keystore password longer than 7 characters will also cause it to fail, but that's not what I've found.
I think this covers every pitfall I found, but feel free to expand and add linsk to related questions.
| Bouncy Castle | 14,114,480 | 15 |
I want to convert -
RSA Public Key
modulus: 9699c3c4406464638d2b30dbed44ddee485b5f9a3d7491434049440d34eb1759376a8bac0e37cee5c18df69acfc60d7252634fd15c26ab2afa16ca831598381356209acea9cea9467acdbd2a9b6d8e7b38d1baa826b1fbce2c185ba324bd17c9fdd6558eb57a082ca8c37fccaa86d4f9ffdc4e5d4a4a7f8e5f5410f835f98c64776cfc3421f19db99f140590d871e5e53efce6be8b9daffa3ab876005a48d249378ecc766281e931921e2ef0105fb64fa26952f91ad1627fedbb429aba75d3788bf7c0324f9fc1b48a9f5490ee0ab42e9e4c88ea564943aa5d9f43f7421b7d28788496daf7426f2e193199d4a525b38f0f3f68ab3c37b09fba2cc21f38e7a769
public exponent: 10001
TO
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAh74GWHRE+YCdi539to51
xpXlJiBI0VvSLbnUwbdKi6UP3HuOPbhVVNNAqyCs/bVIcHdZIap+Pb70Ry04L17H
RsQTOPyl4Us5r7WlzHG4J6p8XU5bl8wS0SU848oABkOIa5D4q0ap0Ryx0SniWPGP
OvPN5qA+cSHwJFgT7Ba/MQB99nJm0iLhnw5QFbtFCb8rCPXHRNYeXwAxUp33oNqZ
IMIWb+DoyyQjwizemiSgQaAk2iEGf7L7N0drlBS9/L/DWvgOOLGNJrK3uZnewNuU
2gma21x60nmWvFBMn87ocGtA4CU6GRrWX0cOvEPL/qXYy/+yA2WpM3op3YW9Hg+i
HQIDAQAB
-----END PUBLIC KEY-----
Either using standard Java or BouncyCastle, any pointers would help.
| That is easy, you can create an RSAPublicKeySpec using the shown valus in BigInteger format. Then create a public key from it, get the encoded byte array and encode it using base64. The only thing you have to to is to add the "BEGIN" and "END" block and correct the line breaks.
KeyFactory f = KeyFactory.getInstance("RSA");
BigInteger modulus = new BigInteger(
"9699c3c4406464638d2b30dbed44ddee485b5f9a3d7491434049440d34eb1759376a8bac"
+ "0e37cee5c18df69acfc60d7252634fd15c26ab2afa16ca831598381356209acea9cea9467acdbd2a9b6d8e7b38d1baa826b1fb"
+ "ce2c185ba324bd17c9fdd6558eb57a082ca8c37fccaa86d4f9ffdc4e5d4a4a7f8e5f5410f835f98c64776cfc3421f19db99f140"
+ "590d871e5e53efce6be8b9daffa3ab876005a48d249378ecc766281e931921e2ef0105fb64fa26952f91ad1627fedbb429aba75"
+ "d3788bf7c0324f9fc1b48a9f5490ee0ab42e9e4c88ea564943aa5d9f43f7421b7d28788496daf7426f2e193199d4a525b38f0f3f"
+ "68ab3c37b09fba2cc21f38e7a769", 16);
BigInteger exp = new BigInteger("10001", 16);
RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exp);
PublicKey pub = f.generatePublic(spec);
byte[] data = pub.getEncoded();
String base64encoded = new String(Base64.getEncoder().encode(data));
System.out.println(base64encoded);
| Bouncy Castle | 20,635,455 | 15 |
I am trying to create a self-signed trusted certificate. I am using Bouncy Castle from nuget, and the answer on this question. This is the code on that page:
public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength = 2048)
{
// Generating Random Numbers
var randomGenerator = new CryptoApiRandomGenerator();
var random = new SecureRandom(randomGenerator);
// The Certificate Generator
var certificateGenerator = new X509V3CertificateGenerator();
// Serial Number
var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
certificateGenerator.SetSerialNumber(serialNumber);
// Signature Algorithm
const string signatureAlgorithm = "SHA256WithRSA";
certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
// Issuer and Subject Name
var subjectDN = new X509Name(subjectName);
var issuerDN = issuerName;
certificateGenerator.SetIssuerDN(issuerDN);
certificateGenerator.SetSubjectDN(subjectDN);
// Valid For
var notBefore = DateTime.UtcNow.Date;
var notAfter = notBefore.AddYears(2);
certificateGenerator.SetNotBefore(notBefore);
certificateGenerator.SetNotAfter(notAfter);
// Subject Public Key
AsymmetricCipherKeyPair subjectKeyPair;
var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
var keyPairGenerator = new RsaKeyPairGenerator();
keyPairGenerator.Init(keyGenerationParameters);
subjectKeyPair = keyPairGenerator.GenerateKeyPair();
certificateGenerator.SetPublicKey(subjectKeyPair.Public);
// Generating the Certificate
var issuerKeyPair = subjectKeyPair;
// selfsign certificate
var certificate = certificateGenerator.Generate(issuerPrivKey, random);
// correcponding private key
PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
// merge into X509Certificate2
var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
if (seq.Count != 9)
throw new PemException("malformed sequence in RSA private key");
var rsa = new RsaPrivateKeyStructure(seq);
RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);
x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
return x509;
}
public static AsymmetricKeyParameter GenerateCACertificate(string subjectName, int keyStrength = 2048)
{
// Generating Random Numbers
var randomGenerator = new CryptoApiRandomGenerator();
var random = new SecureRandom(randomGenerator);
// The Certificate Generator
var certificateGenerator = new X509V3CertificateGenerator();
// Serial Number
var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
certificateGenerator.SetSerialNumber(serialNumber);
// Signature Algorithm
const string signatureAlgorithm = "SHA256WithRSA";
certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
// Issuer and Subject Name
var subjectDN = new X509Name(subjectName);
var issuerDN = subjectDN;
certificateGenerator.SetIssuerDN(issuerDN);
certificateGenerator.SetSubjectDN(subjectDN);
// Valid For
var notBefore = DateTime.UtcNow.Date;
var notAfter = notBefore.AddYears(2);
certificateGenerator.SetNotBefore(notBefore);
certificateGenerator.SetNotAfter(notAfter);
// Subject Public Key
AsymmetricCipherKeyPair subjectKeyPair;
var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
var keyPairGenerator = new RsaKeyPairGenerator();
keyPairGenerator.Init(keyGenerationParameters);
subjectKeyPair = keyPairGenerator.GenerateKeyPair();
certificateGenerator.SetPublicKey(subjectKeyPair.Public);
// Generating the Certificate
var issuerKeyPair = subjectKeyPair;
// selfsign certificate
var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
// Add CA certificate to Root store
addCertToStore(cert, StoreName.Root, StoreLocation.CurrentUser);
return issuerKeyPair.Private;
}
So far, so good, but the "SetSignatureAlgorithm" and "Generate" methods are marked as obsolete. Intellisense suggests using an "ISignatureFactory", and that's where I got lost. Can someone point me in the right direction?
| static void Main()
{
//Console.WriteLine(ExecuteCommand("netsh http delete sslcert ipport=0.0.0.0:4443"));
var applicationId = ((GuidAttribute)typeof(Program).Assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0]).Value;
var certSubjectName = "TEST";
var sslCert = ExecuteCommand("netsh http show sslcert 0.0.0.0:4443");
Console.WriteLine();
if (sslCert.IndexOf(applicationId, StringComparison.OrdinalIgnoreCase) >= 0)
{
Console.WriteLine("This implies we can start running.");
Console.WriteLine(ExecuteCommand("netsh http delete sslcert ipport=0.0.0.0:4443"));
//store.Remove(certs.First(x => x.Subject.Contains(certSubjectName)));
}
AsymmetricKeyParameter myCAprivateKey = null;
Console.WriteLine("Creating CA");
X509Certificate2 certificateAuthorityCertificate = CreateCertificateAuthorityCertificate("CN=" + certSubjectName + "CA", ref myCAprivateKey);
Console.WriteLine("Adding CA to Store");
AddCertificateToSpecifiedStore(certificateAuthorityCertificate, StoreName.Root, StoreLocation.LocalMachine);
Console.WriteLine("Creating certificate based on CA");
X509Certificate2 certificate = CreateSelfSignedCertificateBasedOnCertificateAuthorityPrivateKey("CN=" + certSubjectName, "CN=" + certSubjectName + "CA", myCAprivateKey);
Console.WriteLine("Adding certificate to Store");
AddCertificateToSpecifiedStore(certificate, StoreName.My, StoreLocation.LocalMachine);
Console.WriteLine(ExecuteCommand($"netsh http add sslcert ipport=0.0.0.0:4443 certhash={certificate.Thumbprint} appid={{{applicationId}}}"));
// Check to see if our cert exists
// If the cert does not exist create it then bind it to the port
// If the cert does exist then check the port it is bound to
// If the port and thumbprint match and applicationId match continue
// Else throw exception
// See here for more netsh commands https://msdn.microsoft.com/en-us/library/ms733791(v=vs.110).aspx
}
public static X509Certificate2 CreateSelfSignedCertificateBasedOnCertificateAuthorityPrivateKey(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey)
{
const int keyStrength = 2048;
// Generating Random Numbers
CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
SecureRandom random = new SecureRandom(randomGenerator);
ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerPrivKey, random);
// The Certificate Generator
X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage((new ArrayList() { new DerObjectIdentifier("1.3.6.1.5.5.7.3.1") })));
// Serial Number
BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
certificateGenerator.SetSerialNumber(serialNumber);
// Signature Algorithm
//const string signatureAlgorithm = "SHA512WITHRSA";
//certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
// Issuer and Subject Name
X509Name subjectDN = new X509Name(subjectName);
X509Name issuerDN = new X509Name(issuerName);
certificateGenerator.SetIssuerDN(issuerDN);
certificateGenerator.SetSubjectDN(subjectDN);
// Valid For
DateTime notBefore = DateTime.UtcNow.Date;
DateTime notAfter = notBefore.AddYears(2);
certificateGenerator.SetNotBefore(notBefore);
certificateGenerator.SetNotAfter(notAfter);
// Subject Public Key
AsymmetricCipherKeyPair subjectKeyPair;
var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
var keyPairGenerator = new RsaKeyPairGenerator();
keyPairGenerator.Init(keyGenerationParameters);
subjectKeyPair = keyPairGenerator.GenerateKeyPair();
certificateGenerator.SetPublicKey(subjectKeyPair.Public);
// Generating the Certificate
AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;
// selfsign certificate
X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
// correcponding private key
PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
// merge into X509Certificate2
X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded());
Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded());
if (seq.Count != 9)
{
//throw new PemException("malformed sequence in RSA private key");
}
RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq); //new RsaPrivateKeyStructure(seq);
RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);
x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
return x509;
}
public static X509Certificate2 CreateCertificateAuthorityCertificate(string subjectName, ref AsymmetricKeyParameter CaPrivateKey)
{
const int keyStrength = 2048;
// Generating Random Numbers
CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
SecureRandom random = new SecureRandom(randomGenerator);
// The Certificate Generator
X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
// Serial Number
BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
certificateGenerator.SetSerialNumber(serialNumber);
// Signature Algorithm
//const string signatureAlgorithm = "SHA256WithRSA";
//certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
// Issuer and Subject Name
X509Name subjectDN = new X509Name(subjectName);
X509Name issuerDN = subjectDN;
certificateGenerator.SetIssuerDN(issuerDN);
certificateGenerator.SetSubjectDN(subjectDN);
// Valid For
DateTime notBefore = DateTime.UtcNow.Date;
DateTime notAfter = notBefore.AddYears(2);
certificateGenerator.SetNotBefore(notBefore);
certificateGenerator.SetNotAfter(notAfter);
// Subject Public Key
AsymmetricCipherKeyPair subjectKeyPair;
KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
keyPairGenerator.Init(keyGenerationParameters);
subjectKeyPair = keyPairGenerator.GenerateKeyPair();
certificateGenerator.SetPublicKey(subjectKeyPair.Public);
// Generating the Certificate
AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;
ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);
// selfsign certificate
X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded());
CaPrivateKey = issuerKeyPair.Private;
return x509;
//return issuerKeyPair.Private;
}
public static bool AddCertificateToSpecifiedStore(X509Certificate2 cert, StoreName st, StoreLocation sl)
{
bool bRet = false;
try
{
X509Store store = new X509Store(st, sl);
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
store.Close();
}
catch
{
Console.WriteLine("An error occured");
}
return bRet;
}
public static string ExecuteCommand(string action)
{
StringBuilder stringBuilder = new StringBuilder();
using (Process process = new Process
{
StartInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Normal,
FileName = "cmd.exe",
UseShellExecute = false,
RedirectStandardOutput = true,
Arguments = "/c " + action
}
})
{
Console.WriteLine("Executing Command:");
Console.WriteLine(action);
process.Start();
while (!process.StandardOutput.EndOfStream)
{
stringBuilder.AppendLine(process.StandardOutput.ReadLine());
}
process.Close();
}
return stringBuilder.ToString();
}
Here is a more complete answer. This gets rid of all the obsolete calls in both methods.
Note - I was using the NuGet Install-Package BouncyCastle.Crypto.dll
| Bouncy Castle | 36,712,679 | 15 |
I am having trouble mapping the following JDK JCE encryption code to Bouncy Castles Light-weight API:
public String dec(String password, String salt, String encString) throws Throwable {
// AES algorithm with CBC cipher and PKCS5 padding
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
// Construct AES key from salt and 50 iterations
PBEKeySpec pbeEKeySpec = new PBEKeySpec(password.toCharArray(), toByte(salt), 50, 256);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
SecretKeySpec secretKey = new SecretKeySpec(keyFactory.generateSecret(pbeEKeySpec).getEncoded(), "AES");
// IV seed for first block taken from first 32 bytes
byte[] ivData = toByte(encString.substring(0, 32));
// AES encrypted data
byte[] encData = toByte(encString.substring(32));
cipher.init( Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec( ivData ) );
return new String( cipher.doFinal( encData ) );
}
The above works great, but is not very portable due to Oracle's restriction on encryption strengths. I've made several attempts at porting to Bouncy Castles Light-weight API but without success.
public String decrypt1(String password, String salt, String encString) throws Exception {
byte[] ivData = toByte(encString.substring(0, 32));
byte[] encData = toByte(encString.substring(32));
PKCS12ParametersGenerator gen = new PKCS12ParametersGenerator(new SHA256Digest());
gen.init(password.getBytes(), toByte(salt), 50);
CBCBlockCipher cbcBlockcipher = new CBCBlockCipher(new RijndaelEngine(256));
CipherParameters params = gen.generateDerivedParameters(256, 256);
cbcBlockcipher.init(false, params);
PaddedBufferedBlockCipher aesCipher = new PaddedBufferedBlockCipher(cbcBlockcipher, new PKCS7Padding());
byte[] plainTemp = new byte[aesCipher.getOutputSize(encData.length)];
int offset = aesCipher.processBytes(encData, 0, encData.length, plainTemp, 0);
int last = aesCipher.doFinal(plainTemp, offset);
byte[] plain = new byte[offset + last];
System.arraycopy(plainTemp, 0, plain, 0, plain.length);
return new String(plain);
}
The above attempt results in a org.bouncycastle.crypto.DataLengthException: last block incomplete in decryption.
I have searched for examples online, but there isn't many examples of providing your own IV data for 256bit AES with CBC using PKCS5/PKCS7 as padding.
NB: The toByte function converts a String into a byte array using base64 or similar.
| This should work for you:
public String dec(String password, String salt, String encString)
throws Exception {
byte[] ivData = toByte(encString.substring(0, 32));
byte[] encData = toByte(encString.substring(32));
// get raw key from password and salt
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(),
toByte(salt), 50, 256);
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
SecretKeySpec secretKey = new SecretKeySpec(keyFactory.generateSecret(
pbeKeySpec).getEncoded(), "AES");
byte[] key = secretKey.getEncoded();
// setup cipher parameters with key and IV
KeyParameter keyParam = new KeyParameter(key);
CipherParameters params = new ParametersWithIV(keyParam, ivData);
// setup AES cipher in CBC mode with PKCS7 padding
BlockCipherPadding padding = new PKCS7Padding();
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESEngine()), padding);
cipher.reset();
cipher.init(false, params);
// create a temporary buffer to decode into (it'll include padding)
byte[] buf = new byte[cipher.getOutputSize(encData.length)];
int len = cipher.processBytes(encData, 0, encData.length, buf, 0);
len += cipher.doFinal(buf, len);
// remove padding
byte[] out = new byte[len];
System.arraycopy(buf, 0, out, 0, len);
// return string representation of decoded bytes
return new String(out, "UTF-8");
}
I assume that you're actually doing hex encoding for toByte() since your code uses 32 characters for the IV (which provides the necessary 16 bytes). While I don't have the code you used to do the encryption, I did verify that this code will give the same decrypted output as your code.
| Bouncy Castle | 5,641,326 | 14 |
I create a certificate using BouncyCastle
var keypairgen = new RsaKeyPairGenerator();
keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));
var keypair = keypairgen.GenerateKeyPair();
var gen = new X509V3CertificateGenerator();
var CN = new X509Name("CN=" + certName);
var SN = BigInteger.ProbablePrime(120, new Random());
gen.SetSerialNumber(SN);
gen.SetSubjectDN(CN);
gen.SetIssuerDN(CN);
gen.SetNotAfter(DateTime.Now.AddYears(1));
gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7,0,0,0)));
gen.SetSignatureAlgorithm("MD5WithRSA");
gen.SetPublicKey(keypair.Public);
gen.AddExtension(
X509Extensions.AuthorityKeyIdentifier.Id,
false,
new AuthorityKeyIdentifier(
SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keypair.Public),
new GeneralNames(new GeneralName(CN)),
SN
));
gen.AddExtension(
X509Extensions.ExtendedKeyUsage.Id,
false,
new ExtendedKeyUsage(new ArrayList()
{
new DerObjectIdentifier("1.3.6.1.5.5.7.3.1")
}));
var newCert = gen.Generate(keypair.Private);
This end with
X509Certificate2 certificate = new X509Certificate2(DotNetUtilities.ToX509Certificate((Org.BouncyCastle.X509.X509Certificate)newCert));
Now, because my assignment tells me to store both the Certificate and the PrivateKey in the X509Certificate2 object I need a way to convert the keypair.Private into a X509Certificate2.Private. Any ideas?
Thanks.
| Just be be verbose, this is the full code to add after creation of X509Certificate2 certificate:
RSA rsaPriv = DotNetUtilities.ToRSA(keypair.Private as RsaPrivateCrtKeyParameters);
certificate.PrivateKey = rsaPriv;
(Which of course can be optimised into one line.)
| Bouncy Castle | 6,128,541 | 14 |
I created an OCSP client using Bouncy castle API. I am having a trouble in finding the Certificate Status (Saying whether its revoked or not) from the OCSP response I get. The value returned from resp.getCertStatus() is always null.
This is how I create the OCSP request.
private OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber)
throws CertificateVerificationException {
//Add provider BC
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
try {
// CertID structure is used to uniquely identify certificates that are the subject of
// an OCSP request or response and has an ASN.1 definition. CertID structure is defined in RFC 2560
CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber);
// basic request generation with nonce
OCSPReqGenerator generator = new OCSPReqGenerator();
generator.addRequest(id);
// create details for nonce extension. The nonce extension is used to bind
// a request to a response to prevent replay attacks. As the name implies,
// the nonce value is something that the client should only use once within a reasonably small period.
BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
Vector objectIdentifiers = new Vector();
Vector values = new Vector();
//to create the request Extension
objectIdentifiers.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray())));
generator.setRequestExtensions(new X509Extensions(objectIdentifiers, values));
return generator.generate();
}
catch (OCSPException e) {
e.printStackTrace();
throw new CertificateVerificationException("Cannot generate OSCP Request with the given certificate",e);
}
}
I get the OCSP response from the service URL as follows.
private OCSPResp getOCSPResponce(String serviceUrl, OCSPReq request) throws CertificateVerificationException {
try {
byte[] array = request.getEncoded();
if (serviceUrl.startsWith("http")) {
HttpURLConnection con;
URL url = new URL(serviceUrl);
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Content-Type", "application/ocsp-request");
con.setRequestProperty("Accept", "application/ocsp-response");
con.setDoOutput(true);
OutputStream out = con.getOutputStream();
DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out));
dataOut.write(array);
dataOut.flush();
dataOut.close();
//Get Response
InputStream in = (InputStream) con.getContent();
OCSPResp ocspResponse = new OCSPResp(in);
return ocspResponse;
}
else {
throw new CertificateVerificationException("Only http is supported for ocsp calls");
}
} catch (IOException e) {
e.printStackTrace();
throw new CertificateVerificationException("Cannot get ocspResponse from url: "+ serviceUrl, e);
}
}
Revocation status is checked as follows. Here the SingleResp object (resp) taken from the BasicOCSPResp object (basicResponse) should have the status of the Certificate (good,revoked or unknown). But here status is always null.
public void checkRevocationStatus(X509Certificate peerCert, X509Certificate issuerCert)
throws CertificateVerificationException {
try {
OCSPReq request = generateOCSPRequest(issuerCert, peerCert.getSerialNumber());
List<String> locations = getAIALocations(peerCert);
Iterator it = locations.iterator();
if (it.hasNext()) {
String serviceUrl = (String) it.next();
OCSPResp ocspResponse = getOCSPResponce(serviceUrl, request);
if(OCSPRespStatus.SUCCESSFUL==ocspResponse.getStatus())
System.out.println("server gave response fine");
BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();
SingleResp[] responses = (basicResponse==null) ? null : basicResponse.getResponses();
if (responses!=null && responses.length == 1) {
SingleResp resp = responses[0];
Object status = resp.getCertStatus();
if(status!=null) {
if (status == CertificateStatus.GOOD) {
System.out.println("OCSP Status is good!");
} else if (status instanceof org.bouncycastle.ocsp.RevokedStatus) {
System.out.println("OCSP Status is revoked!");
} else if (status instanceof org.bouncycastle.ocsp.UnknownStatus) {
System.out.println("OCSP Status is unknown!");
}
}
}
}
}
catch (Exception e) {
System.out.println(e);
}
}
I really appreciate your help. Thanks a lot.
| Actually, if you take a look at the actual value of CertificateStatus.GOOD, you will see that it is, in fact, null. In other words, resp.getCertStatus() returns null meaning GOOD.
So you probably just need to take out that (status != null) check.
| Bouncy Castle | 15,083,181 | 14 |
I have successfully written to public and private key files with OpenSSL format.
Files:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpHCHYgawzNlxVebSKXL7vfc/i
hP+dQgMxlaPEi7/vpQtV2szHjIP34MnUKelXFuIETJjOgjWAjTTJoj38MQUWc3u7
SRXaGVggqQEKH+cRi5+UcEObIfpi+cIyAm9MJqKabfJK2e5X/OS7FgAwPjgtDbZO
ZxamOrWWL8KGB+lH+QIDAQAB
-----END PUBLIC KEY-----
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCpHCHYgawzNlxVebSKXL7vfc/ihP+dQgMxlaPEi7/vpQtV2szH
jIP34MnUKelXFuIETJjOgjWAjTTJoj38MQUWc3u7SRXaGVggqQEKH+cRi5+UcEOb
Ifpi+cIyAm9MJqKabfJK2e5X/OS7FgAwPjgtDbZOZxamOrWWL8KGB+lH+QIDAQAB
AoGBAIXtL6jFWVjdjlZrIl4JgXUtkDt21PD33IuiVKZNft4NOWLu+wp17/WZYn3S
C2fbSXfaKZIycKi0K8Ab6zcUo0+QZKMoaG5GivnqqTPVAuZchkuMUSVgjGvKAC/D
12/b+w+Shs9pvqED1CxfvtePXNwL6ZNuaREFC5hF/YpMVyg5AkEA3BUCZYJ+Ec96
2cwsdY6HocW8Kn+RIqMjkNtyLA19cQV5mpIP7kAiW6drBDlraVANi+5AgK2zQ+ZT
hYzs/JfRKwJBAMS1g5/B7XXnfC6VTRs8AMveZudi5wS/aGpaApybsfx1NTLLsm3l
GmGTkbCr+EPzvJ5zRSIAHAA6N6NdORwzEWsCQHTli+JTD5dyNvScaDkAvbYFi06f
d32IXYnBpcEUYT65A8BAOMn5ssYwBL23qf/ED431vLkcig1Ut6RGGFKKaQUCQEfa
UdkSWm39/5N4f/DZyySs+YO90csfK8HlXRzdlnc0TRlf5K5VyHwqDkatmoMfzh9G
1dLknVXL7jTjQZA2az8CQG0jRSQ599zllylMPPVibW98701Mdhb1u20p1fAOkIrz
+BNEdOPqPVIyqIP830nnFsJJgTG2eKB59ym+ypffRmA=
-----END RSA PRIVATE KEY-----
And public key contains just the public key portion of course.
After encrypting my message using the public key. I want to read the private key file
and decrypt it but it's not working. I'm getting exceptions trying to read the private key saying can't cast object to asymmetriccipherkey.
Here is my code:
public static AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename)
{
var fileStream = System.IO.File.OpenText(pemFilename);
var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(fileStream);
var KeyParameter = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)pemReader.ReadObject();
return KeyParameter;
}
static void Encrypt2(string publicKeyFileName, string inputMessage, string encryptedFileName)
{
UTF8Encoding utf8enc = new UTF8Encoding();
FileStream encryptedFile = null;
try
{
// Converting the string message to byte array
byte[] inputBytes = utf8enc.GetBytes(inputMessage);
// RSAKeyPairGenerator generates the RSA Key pair based on the random number and strength of key required
/*RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();
rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512));
Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();
*/
AsymmetricKeyParameter publicKey = ReadAsymmetricKeyParameter(publicKeyFileName);
// Creating the RSA algorithm object
IAsymmetricBlockCipher cipher = new RsaEngine();
// Initializing the RSA object for Encryption with RSA public key. Remember, for encryption, public key is needed
cipher.Init(true, publicKey);
//Encrypting the input bytes
byte[] cipheredBytes = cipher.ProcessBlock(inputBytes, 0, inputMessage.Length);
//Write the encrypted message to file
// Write encrypted text to file
encryptedFile = File.Create(encryptedFileName);
encryptedFile.Write(cipheredBytes, 0, cipheredBytes.Length);
}
catch (Exception ex)
{
// Any errors? Show them
Console.WriteLine("Exception encrypting file! More info:");
Console.WriteLine(ex.Message);
}
finally
{
// Do some clean up if needed
if (encryptedFile != null)
{
encryptedFile.Close();
}
}
}
Here is the decrypt function. 2nd one is without using Bouncy Castle, however, I'd rather use Bouncy Castle since later I'll be also encrypting and decrypting in Java.
static void Decrypt2(string privateKeyFileName, string encryptedFileName, string plainTextFileName)
{
UTF8Encoding utf8enc = new UTF8Encoding();
FileStream encryptedFile = null;
StreamWriter plainFile = null;
byte[] encryptedBytes = null;
string plainText = "";
try
{
// Converting the string message to byte array
//byte[] inputBytes = utf8enc.GetBytes(inputMessage);
// RSAKeyPairGenerator generates the RSA Key pair based on the random number and strength of key required
/*RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();
rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512));
Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();
*/
StreamReader sr = File.OpenText(privateKeyFileName);
PemReader pr = new PemReader(sr);
PemReader pemReader = new PemReader(new StringReader(privateKeyFileName));
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
Console.WriteLine(keyPair.ToString());
AsymmetricKeyParameter privatekey = keyPair.Private;
Console.WriteLine(pr.ReadPemObject());
AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();
AsymmetricKeyParameter privateKey = ReadAsymmetricKeyParameter(privateKeyFileName);
// Creating the RSA algorithm object
IAsymmetricBlockCipher cipher = new RsaEngine();
Console.WriteLine("privateKey: " + privateKey.ToString());
// Initializing the RSA object for Decryption with RSA private key. Remember, for decryption, private key is needed
//cipher.Init(false, KeyPair.Private);
//cipher.Init(false, KeyPair.Private);
cipher.Init(false, keyPair.Private);
// Read encrypted text from file
encryptedFile = File.OpenRead(encryptedFileName);
encryptedBytes = new byte[encryptedFile.Length];
encryptedFile.Read(encryptedBytes, 0, (int)encryptedFile.Length);
//Encrypting the input bytes
//byte[] cipheredBytes = cipher.ProcessBlock(inputBytes, 0, inputMessage.Length);
byte[] cipheredBytes = cipher.ProcessBlock(encryptedBytes, 0, encryptedBytes.Length);
//Write the encrypted message to file
// Write encrypted text to file
plainFile = File.CreateText(plainTextFileName);
plainText = Encoding.Unicode.GetString(cipheredBytes);
plainFile.Write(plainText);
}
catch (Exception ex)
{
// Any errors? Show them
Console.WriteLine("Exception encrypting file! More info:");
Console.WriteLine(ex.Message);
}
finally
{
// Do some clean up if needed
if (plainFile != null)
{
plainFile.Close();
}
if (encryptedFile != null)
{
encryptedFile.Close();
}
}
}
// Decrypt a file
static void Decrypt(string privateKeyFileName, string encryptedFileName, string plainFileName)
{
// Variables
CspParameters cspParams = null;
RSACryptoServiceProvider rsaProvider = null;
StreamReader privateKeyFile = null;
FileStream encryptedFile = null;
StreamWriter plainFile = null;
string privateKeyText = "";
string plainText = "";
byte[] encryptedBytes = null;
byte[] plainBytes = null;
try
{
// Select target CSP
cspParams = new CspParameters();
cspParams.ProviderType = 1; // PROV_RSA_FULL
//cspParams.ProviderName; // CSP name
rsaProvider = new RSACryptoServiceProvider(cspParams);
// Read private/public key pair from file
privateKeyFile = File.OpenText(privateKeyFileName);
privateKeyText = privateKeyFile.ReadToEnd();
// Import private/public key pair
rsaProvider.FromXmlString(privateKeyText);
// Read encrypted text from file
encryptedFile = File.OpenRead(encryptedFileName);
encryptedBytes = new byte[encryptedFile.Length];
encryptedFile.Read(encryptedBytes, 0, (int)encryptedFile.Length);
// Decrypt text
plainBytes = rsaProvider.Decrypt(encryptedBytes, false);
// Write decrypted text to file
plainFile = File.CreateText(plainFileName);
plainText = Encoding.Unicode.GetString(plainBytes);
plainFile.Write(plainText);
}
catch (Exception ex)
{
// Any errors? Show them
Console.WriteLine("Exception decrypting file! More info:");
Console.WriteLine(ex.Message);
}
finally
{
// Do some clean up if needed
if (privateKeyFile != null)
{
privateKeyFile.Close();
}
if (encryptedFile != null)
{
encryptedFile.Close();
}
if (plainFile != null)
{
plainFile.Close();
}
}
} // Decrypt
| I figured this out. Basically to read a private openssl key using BouncyCastle and C# is like this:
static AsymmetricKeyParameter readPrivateKey(string privateKeyFileName)
{
AsymmetricCipherKeyPair keyPair;
using (var reader = File.OpenText(privateKeyFileName))
keyPair = (AsymmetricCipherKeyPair)new PemReader(reader).ReadObject();
return keyPair.Private;
}
Then this key can be used to decrypt data such as below:
AsymmetricKeyParameter key = readPrivateKey(pemFilename);
RsaEngine e = new RsaEngine();
e.Init(false, key);
byte[] decipheredBytes = e.ProcessBlock(cipheredData, 0, cipheredData.Length);
| Bouncy Castle | 15,629,551 | 14 |
I am trying to create an online database application using PHP for the server and C# form application for the client.
On the server I encrypt a simple string using a public RSA key with the PHPSecLib. Then the C# application receives the string and tries to decrypt it using the corresponding private key.
The bytes are base64 encoded on the server and decoded to bytes again by C#. I created the key pair using the PHPSecLib.
This is the code I use on the client application:
public string rsa_decrypt(string encryptedText, string privateKey) {
byte[] bytesToDecrypt = Convert.FromBase64String(encryptedText);
Pkcs1Encoding decrypter = new Pkcs1Encoding(new RsaEngine());
//the error occurs on this line:
AsymmetricCipherKeyPair RSAParams = (AsymmetricCipherKeyPair)new PemReader(new StringReader(privateKey)).ReadObject();
decrypter.Init(false, RSAParams.Private);
byte[] decryptedBytes = decrypter.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length);
string decryptedString = Convert.ToBase64String(decryptedBytes);
return decryptedString;
}
But, I get the following error on the line specified above^.
An unhandled exception of type 'System.IO.IOException' occurred in
BouncyCastle.Crypto.dll
Additional information: -----END RSA PRIVATE KEY not found
I believe there's nothing wrong with the key pair combo as I get an error before I even try to decrypt anything.
The privateKey parameter is currently hardcoded into the script using this format:
string privateKey = "-----BEGIN RSA PRIVATE KEY-----XXXXXXXX-----END RSA PRIVATE KEY-----";
So it seems to me the footer actually is included in the string... I have debugged and googled everywhere but I can't seem to solve it. I'm pretty new to RSA&Bouncycastle so maybe I'm just using wrong methods.
Hope you can help, thanks!
- G4A
P.S. This is my first Stackoverflow question, I just created an account, so if you could also give me some feedback on the way I formulated this question; great!
| You need to add a new line between the pre/post encapsulation boundary text and the Base64 data, so:
string privateKey = "-----BEGIN RSA PRIVATE KEY-----\r\nXXX\r\n-----END RSA PRIVATE KEY-----";
This is because the pem specification allows for the existence of other textual headers between the two.
| Bouncy Castle | 33,301,427 | 14 |
I need to create a PBKDF2-SHA256 password hash, but am having some trouble.
I downloaded the Bouncy Castle repo, but got a bit stuck finding what I was looking for in the Unit Tests.
Found some sample code here, but this only does SHA1. The key bit of code is:
/// <summary>
/// Computes the PBKDF2-SHA1 hash of a password.
/// </summary>
/// <param name="password">The password to hash.</param>
/// <param name="salt">The salt.</param>
/// <param name="iterations">The PBKDF2 iteration count.</param>
/// <param name="outputBytes">The length of the hash to generate, in bytes.</param>
/// <returns>A hash of the password.</returns>
private static byte[] PBKDF2(string password, byte[] salt, int iterations, int outputBytes)
{
var pdb = new Pkcs5S2ParametersGenerator();
pdb.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt,
iterations);
var key = (KeyParameter)pdb.GenerateDerivedMacParameters(outputBytes * 8);
return key.GetKey();
}
I need to change this from SHA1 to SHA256.
From the Java documentation and this post, it looked like the following would be possible, but there is no overload on the constructor in the C# library.
var pdb = new Pkcs5S2ParametersGenerator(new Sha256Derived());
Finding another article on stack overflow, i thought the following might be possible, but the SHA hashing algorithms are not in the lookup list ,so the following will not work.
var bcparam = (KeyParameter)pdb.GenerateDerivedParameters("sha256", outputBytes * 8);
What do I need to do to get this working please?
Note: If you read this and don't know how in Bouncy Castle, but do know another way, I'd still appreciate your help.
| EDIT (Previous answer history removed for brevity)
There is now a Bouncy Castle Crypto API NuGet package that can be used. Alternatively, you can get the source directly from GitHub, which will work. I had got the standard Bouncy Castle from NuGet, which had not been updated to 1.8.1 at the time of writing.
For the benefit of searchers, here is a C# helper class for hashing. Have tested on multiple threads and seems fine.
NOTE: This class also works for the .NET Core version of the library BouncyCastle.NetCore
/// <summary>
/// Contains the relevant Bouncy Castle Methods required to encrypt a password.
/// References NuGet Package BouncyCastle.Crypto.dll
/// </summary>
public class BouncyCastleHashing
{
private SecureRandom _cryptoRandom;
public BouncyCastleHashing()
{
_cryptoRandom = new SecureRandom();
}
/// <summary>
/// Random Salt Creation
/// </summary>
/// <param name="size">The size of the salt in bytes</param>
/// <returns>A random salt of the required size.</returns>
public byte[] CreateSalt(int size)
{
byte[] salt = new byte[size];
_cryptoRandom.NextBytes(salt);
return salt;
}
/// <summary>
/// Gets a PBKDF2_SHA256 Hash (Overload)
/// </summary>
/// <param name="password">The password as a plain text string</param>
/// <param name="saltAsBase64String">The salt for the password</param>
/// <param name="iterations">The number of times to encrypt the password</param>
/// <param name="hashByteSize">The byte size of the final hash</param>
/// <returns>A base64 string of the hash.</returns>
public string PBKDF2_SHA256_GetHash(string password, string saltAsBase64String, int iterations, int hashByteSize)
{
var saltBytes = Convert.FromBase64String(saltAsBase64String);
var hash = PBKDF2_SHA256_GetHash(password, saltBytes, iterations, hashByteSize);
return Convert.ToBase64String(hash);
}
/// <summary>
/// Gets a PBKDF2_SHA256 Hash (CORE METHOD)
/// </summary>
/// <param name="password">The password as a plain text string</param>
/// <param name="salt">The salt as a byte array</param>
/// <param name="iterations">The number of times to encrypt the password</param>
/// <param name="hashByteSize">The byte size of the final hash</param>
/// <returns>A the hash as a byte array.</returns>
public byte[] PBKDF2_SHA256_GetHash(string password, byte[] salt, int iterations, int hashByteSize)
{
var pdb = new Pkcs5S2ParametersGenerator(new Org.BouncyCastle.Crypto.Digests.Sha256Digest());
pdb.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt,
iterations);
var key = (KeyParameter)pdb.GenerateDerivedMacParameters(hashByteSize * 8);
return key.GetKey();
}
/// <summary>
/// Validates a password given a hash of the correct one. (OVERLOAD)
/// </summary>
/// <param name="password">The original password to hash</param>
/// <param name="salt">The salt that was used when hashing the password</param>
/// <param name="iterations">The number of times it was encrypted</param>
/// <param name="hashByteSize">The byte size of the final hash</param>
/// <param name="hashAsBase64String">The hash the password previously provided as a base64 string</param>
/// <returns>True if the hashes match</returns>
public bool ValidatePassword(string password, string salt, int iterations, int hashByteSize, string hashAsBase64String)
{
byte[] saltBytes = Convert.FromBase64String(salt);
byte[] actualHashBytes = Convert.FromBase64String(hashAsBase64String);
return ValidatePassword(password, saltBytes, iterations, hashByteSize, actualHashBytes);
}
/// <summary>
/// Validates a password given a hash of the correct one (MAIN METHOD).
/// </summary>
/// <param name="password">The password to check.</param>
/// <param name="correctHash">A hash of the correct password.</param>
/// <returns>True if the password is correct. False otherwise.</returns>
public bool ValidatePassword(string password, byte[] saltBytes, int iterations, int hashByteSize, byte[] actualGainedHasAsByteArray)
{
byte[] testHash = PBKDF2_SHA256_GetHash(password, saltBytes, iterations, hashByteSize);
return SlowEquals(actualGainedHasAsByteArray, testHash);
}
/// <summary>
/// Compares two byte arrays in length-constant time. This comparison
/// method is used so that password hashes cannot be extracted from
/// on-line systems using a timing attack and then attacked off-line.
/// </summary>
/// <param name="a">The first byte array.</param>
/// <param name="b">The second byte array.</param>
/// <returns>True if both byte arrays are equal. False otherwise.</returns>
private bool SlowEquals(byte[] a, byte[] b)
{
uint diff = (uint)a.Length ^ (uint)b.Length;
for (int i = 0; i < a.Length && i < b.Length; i++)
diff |= (uint)(a[i] ^ b[i]);
return diff == 0;
}
}
Usage Example
public void CreatePasswordHash_Single()
{
int iterations = 100000; // The number of times to encrypt the password - change this
int saltByteSize = 64; // the salt size - change this
int hashByteSize = 128; // the final hash - change this
BouncyCastleHashing mainHashingLib = new BouncyCastleHashing();
var password = "password"; // That's really secure! :)
byte[] saltBytes = mainHashingLib.CreateSalt(saltByteSize);
string saltString = Convert.ToBase64String(saltBytes);
string pwdHash = mainHashingLib.PBKDF2_SHA256_GetHash(password, saltString, iterations, hashByteSize);
var isValid = mainHashingLib.ValidatePassword(password, saltBytes, iterations, hashByteSize, Convert.FromBase64String(pwdHash));
}
| Bouncy Castle | 34,950,611 | 14 |
I have the following code which generates a nice self-signed cert, works great, but I'd like to update to the latest BouncyCastle (1.8.1.0) and I'm getting warnings about obsolete usage:
var persistedCertificateFilename = "ClientCertificate.pfx";
if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["PersistedCertificateFilename"])) { persistedCertificateFilename = ConfigurationManager.AppSettings["PersistedCertificateFilename"].Trim(); }
if (persistCertificateToDisk)
{
if (File.Exists(persistedCertificateFilename))
{
var certBytes = File.ReadAllBytes(persistedCertificateFilename);
this.clientCertificate = new X509Certificate2(certBytes, (string) null, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
}
}
if (this.clientCertificate == null)
{
// Initialize the new secure keys
KeyGenerator keyGenerator = KeyGenerator.Create();
KeyPair keyPair = keyGenerator.GenerateKeyPair();
this.privateKey = keyPair.ToEncryptedPrivateKeyString(privateKeySecret);
this.publicKey = keyPair.ToPublicKeyString();
// Client certificate permissions
var certificatePermissions = new ArrayList()
{
KeyPurposeID.IdKPCodeSigning,
KeyPurposeID.IdKPServerAuth,
KeyPurposeID.IdKPTimeStamping,
KeyPurposeID.IdKPOcspSigning,
KeyPurposeID.IdKPClientAuth
};
// Initialize the certificate generation
var certificateGenerator = new X509V3CertificateGenerator();
BigInteger serialNo = BigInteger.ProbablePrime(128, new Random());
certificateGenerator.SetSerialNumber(serialNo);
certificateGenerator.SetSubjectDN(GetLicenseeDN());
certificateGenerator.SetIssuerDN(GetLicencerDN());
certificateGenerator.SetNotAfter(DateTime.Now.AddYears(100));
certificateGenerator.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
//ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", keyPair.PrivateKey); // ??
certificateGenerator.SetSignatureAlgorithm("SHA512withRSA");
certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(certificatePermissions));
var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.PublicKey));
certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifier);
certificateGenerator.SetPublicKey(keyPair.PublicKey);
var result = certificateGenerator.Generate(keyPair.PrivateKey);
var secure = new SecureString();
foreach (char c in privateKeySecret)
{
secure.AppendChar(c);
}
X509KeyStorageFlags flags = X509KeyStorageFlags.MachineKeySet;
if (persistCertificateToDisk) { flags |= X509KeyStorageFlags.Exportable; flags |= X509KeyStorageFlags.PersistKeySet; }
this.clientCertificate = new X509Certificate2(Org.BouncyCastle.Security.DotNetUtilities.ToX509Certificate(result).Export(X509ContentType.Cert), secure, flags);
// This section allows us to use this certificate on Azure (no file access required)
CspParameters cspParams;
const int PROVIDER_RSA_FULL = 1;
cspParams = new CspParameters(PROVIDER_RSA_FULL);
cspParams.KeyContainerName = new Guid().ToString();
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
var rule = new CryptoKeyAccessRule("everyone", CryptoKeyRights.FullControl, AccessControlType.Allow);
cspParams.CryptoKeySecurity = new CryptoKeySecurity();
cspParams.CryptoKeySecurity.SetAccessRule(rule);
// Set the private key
var tempRcsp = (RSACryptoServiceProvider) Org.BouncyCastle.Security.DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters) keyPair.PrivateKey);
var rcsp = new RSACryptoServiceProvider(cspParams);
rcsp.ImportCspBlob(tempRcsp.ExportCspBlob(true));
this.clientCertificate.PrivateKey = rcsp;
if (persistCertificateToDisk)
{
if (!File.Exists(persistedCertificateFilename))
{
File.WriteAllBytes(persistedCertificateFilename, this.clientCertificate.Export(X509ContentType.Pkcs12, (string) null));
}
}
}
Specifically, the warnings are:
'X509V3CertificateGenerator.SetSignatureAlgorithm(string)' is
obsolete: 'Not needed if Generate used with an ISignatureFactory'
and
'X509V3CertificateGenerator.Generate(AsymmetricKeyParameter)' is
obsolete: 'Use Generate with an ISignatureFactory'
So, my questions are:
Do I need to worry about these warnings?
If so, what lines change?
If I do update this code, is there a performance benefit?
Note: If any one is curious, the reason I'm persisting this to disk is that this code created a cert every time the client was instantiated, and this was particularly harsh due to the min key size being 2048 and the performance of 1.7.0.
| I struggled with this for some time, too.
I finally have a solution for this.
Let's take one of the errors:
'X509V3CertificateGenerator.Generate(AsymmetricKeyParameter)' is obsolete: 'Use Generate with an ISignatureFactory'
You are basically using (i was doing the same thing) the Generate method like this:
var certificate = certificateGenerator.Generate(issuerCertificate.PrivateKey, random);
where certificateGenerator is instance of class CertificateContainer
Error says that: 'Use Generate with an ISignatureFactory'
So for this let us create first an instance to ISignatureFactory.
ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);
And for this to work correctly before this you should also declare the followings:
var randomGenerator = new CryptoApiRandomGenerator();
var random = new SecureRandom(randomGenerator);
AsymmetricCipherKeyPair subjectKeyPair = default(AsymmetricCipherKeyPair);
var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
keyPairGenerator.Init(keyGenerationParameters);
subjectKeyPair = keyPairGenerator.GenerateKeyPair();
AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;
And now after these changes, change the method Generate from:
var certificate = certificateGenerator.Generate(issuerCertificate.PrivateKey, random);
to:
var certificate = certificateGenerator.Generate(signatureFactory);
I hope it helps.
| Bouncy Castle | 36,942,094 | 14 |
I follow this instruction to add bouncycastle:
http://www.bouncycastle.org/wiki/display/JA1/Provider+Installation
but I have still one problem. Sometimes when I redeploy my application this provider isnt found so then my application throw exception. This problem occurs just one per 100 redeploy (maybe less). When I restart my server - weblogic then it start working again. I will be very grateful for any advice why this problem occurs
EDIT:
I am using both method in link above because when I use just one of them then it doesnt work
I add to java.security this provder and then in my class I registered this provder:
static {
Security.addProvider(new BouncyCastleProvider());
}
| You probably got a NoClassDefFoundError. This is a known issue with JSSE implementations.
Here is the scenario:
Your container loads bouncy castle classes in an application specific ClassLoader
The provider instance you create depends on that classes and so on that ClassLoader
Then the provider is registered into JRE API thanks to static fields in top level JVM ClassLoader
When redeploying, the container discards the application ClassLoader to create a new one
As the algorithm is already known, the second provider insertion fails silently
When using the algorithm the provider instance is simply unusable because the ClassLoader has been discarded
Then the only option is to restart the container to get the situation fixed.
As there is no standard listener for the undeploy event, it is not possible to trigger the JSSE provider removal at time.
The recommended way to avoid that trouble is to have bouncy castle classes in your JVM ClassPath or in your container ClassPath. You have to remove it from your application. Now you need to register BC provider with an alternate option to the static initializer. WebLogic provides ways to trigger code at server startup (I have used server startup class), this code will be responsible to register JSSE providers for the whole server/JVM lifetime.
An alternate option is to add the following line in JRE java.security file with bouncy castle jar in jre/lib/ext but I do not like that way because it may be lost when updating: security.provider.7=org.bouncycastle.jce.provider.BouncyCastleProvider
So then the application simply expects implementations are there, it may be a good idea to add tests for algorithm availability to report any troubles to operators and users.
| Bouncy Castle | 10,379,799 | 13 |
I'm stuck at the creation of an SSLContext (which I want to use to instantiate an SSLEngine to handle encrypted transport via the java-nio):
The code
String protocol = "TLSv1.2";
Provider provider = new BouncyCastleProvider();
Security.addProvider(provider);
sslContext = SSLContext.getInstance(protocol,provider.getName());
throws the following exception:
Exception in thread "main" java.lang.RuntimeException: java.security.NoSuchAlgorithmException: no such algorithm: SSL for provider BC
at org.bitmash.network.tcp.ssl.SslTransferFactory.<init>(SslTransferFactory.java:43)
at org.bitmash.network.http.HttpsServer.<init>(HttpsServer.java:19)
I attached Bouncy Castle's current provider package 'bcprov-jdk15on-150.jar' (which I got from here) to the applications classpath as well as to its bootclasspath (via VM-Option -Xbootclasspath/p), but neither solved the problem. I also tried different values for protocol (i. e. 'SSL' and 'TLSv1') without any effect.
Also, I found people with similar problems here and here. But in contrast to them, I'm targeting (and I'm using) Java 7 (or greater), but I still have this problem. Is it -in general- even feasible to use Bouncy Castle this way, or do I have to rewrite my protocol using their respective API instead of oracle's NIO via SSLEngine (which is the way I'm doing it right now)?
Thank you so much for any help here.
| I know this is kind of an old question, but I needed an answer (so I am creating one):
[Is it possible to] create an SSLContext instance using a Bouncy Castle provider [?]
No
Why not?
Debugging this line of code:
Provider [] providers = Security.getProviders();
the default SunJSSE version 1.7 implements the following SSLContext values:
Alg.Alias.SSLContext.SSL=TLSv1
Alg.Alias.SSLContext.SSLv3=TLSv1
SSLContext.Default=sun.security.ssl.SSLContextImpl$DefaultSSLContext
SSLContext.TLSv1=sun.security.ssl.SSLContextImpl$TLS10Context
SSLContext.TLSv1.1=sun.security.ssl.SSLContextImpl$TLS11Context
SSLContext.TLSv1.2=sun.security.ssl.SSLContextImpl$TLS12Context
using bcprov-jdk15on-152.jar and adding a new BouncyCastleProvider() to Security, one can observe that there are no SSLContext values available.
This should make sense since Bouncy Castle is a JCE implementation, not a JSSE implementation.
| Bouncy Castle | 23,906,736 | 13 |
I am trying to determine the best method for code-signing an executable using Bouncy Castle, managed code, or un-managed code from C#. Since CAPICOM is now deprecated, I imagine one of the SignerSign methods from mssign32.dll is the best way to go if it needs to be done unmanaged.
This answer (https://stackoverflow.com/a/3952235/722078) seems close, but it produces a .p7m file, which, while appearing to be the right size, will not run correctly (obviously renamed to .exe before running).
The solution given by the question-asker here (API/Library to replace signtool.exe) seemed promising and managed, but like Tom Canham mentions in the comments below, "it appears that this is for signing enveloped messages. Authenticode -- the code-signing that signtool does -- is different, which is why the EXE doesn't run after the signing." I receive the same error that Tom does when I sign using either the question-asker's solution or the previously referenced Bouncy Castle solution.
The only option that I have not attempted yet is given here (https://stackoverflow.com/a/6429860/722078), and while it looks promising, I am not positive that it uses "authenticode" code-signing as opposed "enveloped message" code-signing. This answer also has the benefit of not using the CAPICOM interop methods which are now deprecated, so I imagine I will report back on my results using this method today. If this is the best option, could anybody out there speak to the differences between SignerSign, SignerSignEx, and SignerSignEx2 functions that are exported from mssign32.dll? I have read that SignerSignEx2 should be used with Windows 8 and higher...
Long story short, I would like to replicate the ability of signtool.exe to sign an executable given a .exe file, .pfx file, and password like so:
signtool sign /f cert.pfx /p password application.exe
I am looking for the best option to programmatically code-sign an executable (PE if it matters) using authenticode signing, and I would prefer to use bouncy castle or managed code if possible, although I will use something unmanaged if it works and is not currently deprecated.
Thanks!
| As far as I can tell, SignSigner and SignSignerEx are available as of Windows XP, which is the oldest operating system I care to support. Because I do not need to worry about Windows App Store publication, this answer is limited to SignSigner and SignSignerEx, although the import for SignSignerEx2 is very similar to SignSignerEx, and I wouldn't expect it to cause any problems.
The following class allows you to sign an executable with a .pfx by calling:
SignWithCert(string appPath, string certPath, string certPassword, string timestampUrl);
It also allows you to sign an executable with a certificate from a key store by calling:
SignWithThumbPrint(string appPath, string thumbprint, string timestampUrl);
If you want to sign using a cert installed into a key store, you may need to update FindCertByThumbPrint(string thumbPrint) to check more key stores than I care to check. 99.5% of the time, our customers sign with a .pfx and not with a thumbprint.
For the sake of illustration, SignWithCert() utilizes SignerSignEx and SignerTimeStampEx, while SignWithThumbPrint() utilizes SignerSign and SignerTimeStamp.
They're easily interchanged. SignerSignEx and SignerTimeStampEx give you back a SIGNER_CONTEXT pointer and allow you to modify the behavior of the functions with the dwFlags argument (if you're signing a portable executable). Valid flag options are listed at here. Basically, if you pass 0x0 as the dwFlags to SignerSignEx, the output will be identical to just using SignerSign. In my case, I imagine I'll be using SignerSign because I don't believe I need a pointer to the signer context for any conceivable reason.
Anyway, here is the class. This is my first time posting code here, so I hope I haven't broken it in formatting.
The code works as expected, and the executable runs fine and signed, BUT the binary output of the signature block differs slightly from the binary output of signtool.exe (in that test, a timestamp was used by neither tool). I attribute this to the fact that signtool.exe appears to use CAPICOM for signing and this uses Mssign32.dll, but all in all, I am pretty pleased with it in the initial set of tests.
The error handling obviously needs improvement.
Thanks to GregS and everybody out there who's posted code samples previously.
Here's the relevant stuff. I will update this block with comments and improvements when I get the chance to do so.
Update 1: Added somewhat better error handling and comments, along with some reformatting of the thumbprint in FindCertByThumbprint(string thumbprint) to allow the cert to be found on Windows 8 and Windows 10 (public preview). Those OSes wouldn't return a match when spaces were left in the thumbprint, so I am now fixing them before searching.
using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Utilities
{
internal static class SignTool
{
#region Structures
[StructLayoutAttribute(LayoutKind.Sequential)]
struct SIGNER_SUBJECT_INFO
{
public uint cbSize;
public IntPtr pdwIndex;
public uint dwSubjectChoice;
public SubjectChoiceUnion Union1;
[StructLayoutAttribute(LayoutKind.Explicit)]
internal struct SubjectChoiceUnion
{
[FieldOffsetAttribute(0)]
public System.IntPtr pSignerFileInfo;
[FieldOffsetAttribute(0)]
public System.IntPtr pSignerBlobInfo;
};
}
[StructLayoutAttribute(LayoutKind.Sequential)]
struct SIGNER_CERT
{
public uint cbSize;
public uint dwCertChoice;
public SignerCertUnion Union1;
[StructLayoutAttribute(LayoutKind.Explicit)]
internal struct SignerCertUnion
{
[FieldOffsetAttribute(0)]
public IntPtr pwszSpcFile;
[FieldOffsetAttribute(0)]
public IntPtr pCertStoreInfo;
[FieldOffsetAttribute(0)]
public IntPtr pSpcChainInfo;
};
public IntPtr hwnd;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
struct SIGNER_SIGNATURE_INFO
{
public uint cbSize;
public uint algidHash; // ALG_ID
public uint dwAttrChoice;
public IntPtr pAttrAuthCode;
public IntPtr psAuthenticated; // PCRYPT_ATTRIBUTES
public IntPtr psUnauthenticated; // PCRYPT_ATTRIBUTES
}
[StructLayoutAttribute(LayoutKind.Sequential)]
struct SIGNER_FILE_INFO
{
public uint cbSize;
public IntPtr pwszFileName;
public IntPtr hFile;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
struct SIGNER_CERT_STORE_INFO
{
public uint cbSize;
public IntPtr pSigningCert; // CERT_CONTEXT
public uint dwCertPolicy;
public IntPtr hCertStore;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
struct SIGNER_CONTEXT
{
public uint cbSize;
public uint cbBlob;
public IntPtr pbBlob;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
struct SIGNER_PROVIDER_INFO
{
public uint cbSize;
public IntPtr pwszProviderName;
public uint dwProviderType;
public uint dwKeySpec;
public uint dwPvkChoice;
public SignerProviderUnion Union1;
[StructLayoutAttribute(LayoutKind.Explicit)]
internal struct SignerProviderUnion
{
[FieldOffsetAttribute(0)]
public IntPtr pwszPvkFileName;
[FieldOffsetAttribute(0)]
public IntPtr pwszKeyContainer;
};
}
#endregion
#region Imports
[DllImport("Mssign32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int SignerSign(
IntPtr pSubjectInfo, // SIGNER_SUBJECT_INFO
IntPtr pSignerCert, // SIGNER_CERT
IntPtr pSignatureInfo, // SIGNER_SIGNATURE_INFO
IntPtr pProviderInfo, // SIGNER_PROVIDER_INFO
string pwszHttpTimeStamp, // LPCWSTR
IntPtr psRequest, // PCRYPT_ATTRIBUTES
IntPtr pSipData // LPVOID
);
[DllImport("Mssign32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int SignerSignEx(
uint dwFlags, // DWORD
IntPtr pSubjectInfo, // SIGNER_SUBJECT_INFO
IntPtr pSignerCert, // SIGNER_CERT
IntPtr pSignatureInfo, // SIGNER_SIGNATURE_INFO
IntPtr pProviderInfo, // SIGNER_PROVIDER_INFO
string pwszHttpTimeStamp, // LPCWSTR
IntPtr psRequest, // PCRYPT_ATTRIBUTES
IntPtr pSipData, // LPVOID
out SIGNER_CONTEXT ppSignerContext // SIGNER_CONTEXT
);
[DllImport("Mssign32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int SignerTimeStamp(
IntPtr pSubjectInfo, // SIGNER_SUBJECT_INFO
string pwszHttpTimeStamp, // LPCWSTR
IntPtr psRequest, // PCRYPT_ATTRIBUTES
IntPtr pSipData // LPVOID
);
[DllImport("Mssign32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int SignerTimeStampEx(
uint dwFlags, // DWORD
IntPtr pSubjectInfo, // SIGNER_SUBJECT_INFO
string pwszHttpTimeStamp, // LPCWSTR
IntPtr psRequest, // PCRYPT_ATTRIBUTES
IntPtr pSipData, // LPVOID
out SIGNER_CONTEXT ppSignerContext // SIGNER_CONTEXT
);
[DllImport("Crypt32.dll", EntryPoint = "CertCreateCertificateContext", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr CertCreateCertificateContext(
int dwCertEncodingType,
byte[] pbCertEncoded,
int cbCertEncoded);
#endregion
#region public methods
// Call SignerSignEx and SignerTimeStampEx for a given .pfx
public static void SignWithCert(string appPath, string certPath, string certPassword, string timestampUrl)
{
IntPtr pSignerCert = IntPtr.Zero;
IntPtr pSubjectInfo = IntPtr.Zero;
IntPtr pSignatureInfo = IntPtr.Zero;
IntPtr pProviderInfo = IntPtr.Zero;
try
{
// Grab the X509Certificate from the .pfx file.
X509Certificate2 cert = new X509Certificate2(certPath, certPassword);
pSignerCert = CreateSignerCert(cert);
pSubjectInfo = CreateSignerSubjectInfo(appPath);
pSignatureInfo = CreateSignerSignatureInfo();
pProviderInfo = GetProviderInfo(cert);
SIGNER_CONTEXT signerContext;
SignCode(0x0, pSubjectInfo, pSignerCert, pSignatureInfo, pProviderInfo, out signerContext);
// Only attempt to timestamp if we've got a timestampUrl.
if (!string.IsNullOrEmpty(timestampUrl))
{
TimeStampSignedCode(0x0, pSubjectInfo, timestampUrl, out signerContext);
}
}
catch (CryptographicException ce)
{
string exception;
// do anything with this useful information?
switch (Marshal.GetHRForException(ce))
{
case -2146885623:
exception = string.Format(@"An error occurred while attempting to load the signing certificate. ""{0}"" does not appear to contain a valid certificate.", certPath);
break;
case -2147024810:
exception = string.Format(@"An error occurred while attempting to load the signing certificate. The specified password was incorrect.");
break;
default:
exception = string.Format(@"An error occurred while attempting to load the signing certificate. {0}", ce.Message);
break;
}
}
catch (Exception e)
{
// do anything with this useful information?
string exception = e.Message;
}
finally
{
if (pSignerCert != IntPtr.Zero)
{
Marshal.DestroyStructure(pSignerCert, typeof(SIGNER_CERT));
}
if (pSubjectInfo != IntPtr.Zero)
{
Marshal.DestroyStructure(pSubjectInfo, typeof(SIGNER_SUBJECT_INFO));
}
if (pSignatureInfo != IntPtr.Zero)
{
Marshal.DestroyStructure(pSignatureInfo, typeof(SIGNER_SIGNATURE_INFO));
}
if (pProviderInfo != IntPtr.Zero)
{
Marshal.DestroyStructure(pSignatureInfo, typeof(SIGNER_PROVIDER_INFO));
}
}
}
// Call SignerSign and SignerTimeStamp for a given thumbprint.
public static void SignWithThumbprint(string appPath, string thumbprint, string timestampUrl)
{
IntPtr pSignerCert = IntPtr.Zero;
IntPtr pSubjectInfo = IntPtr.Zero;
IntPtr pSignatureInfo = IntPtr.Zero;
IntPtr pProviderInfo = IntPtr.Zero;
try
{
pSignerCert = CreateSignerCert(thumbprint);
pSubjectInfo = CreateSignerSubjectInfo(appPath);
pSignatureInfo = CreateSignerSignatureInfo();
SignCode(pSubjectInfo, pSignerCert, pSignatureInfo, pProviderInfo);
// Only attempt to timestamp if we've got a timestampUrl.
if (!string.IsNullOrEmpty(timestampUrl))
{
TimeStampSignedCode(pSubjectInfo, timestampUrl);
}
}
catch (CryptographicException ce)
{
// do anything with this useful information?
string exception = string.Format(@"An error occurred while attempting to load the signing certificate. {0}", ce.Message);
}
catch (Exception e)
{
// do anything with this useful information?
string exception = e.Message;
}
finally
{
if (pSignerCert != IntPtr.Zero)
{
Marshal.DestroyStructure(pSignerCert, typeof(SIGNER_CERT));
}
if (pSubjectInfo != IntPtr.Zero)
{
Marshal.DestroyStructure(pSubjectInfo, typeof(SIGNER_SUBJECT_INFO));
}
if (pSignatureInfo != IntPtr.Zero)
{
Marshal.DestroyStructure(pSignatureInfo, typeof(SIGNER_SIGNATURE_INFO));
}
}
}
#endregion
#region private methods
private static IntPtr CreateSignerSubjectInfo(string pathToAssembly)
{
SIGNER_SUBJECT_INFO info = new SIGNER_SUBJECT_INFO
{
cbSize = (uint)Marshal.SizeOf(typeof(SIGNER_SUBJECT_INFO)),
pdwIndex = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(uint)))
};
var index = 0;
Marshal.StructureToPtr(index, info.pdwIndex, false);
info.dwSubjectChoice = 0x1; //SIGNER_SUBJECT_FILE
IntPtr assemblyFilePtr = Marshal.StringToHGlobalUni(pathToAssembly);
SIGNER_FILE_INFO fileInfo = new SIGNER_FILE_INFO
{
cbSize = (uint)Marshal.SizeOf(typeof(SIGNER_FILE_INFO)),
pwszFileName = assemblyFilePtr,
hFile = IntPtr.Zero
};
info.Union1 = new SIGNER_SUBJECT_INFO.SubjectChoiceUnion
{
pSignerFileInfo = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SIGNER_FILE_INFO)))
};
Marshal.StructureToPtr(fileInfo, info.Union1.pSignerFileInfo, false);
IntPtr pSubjectInfo = Marshal.AllocHGlobal(Marshal.SizeOf(info));
Marshal.StructureToPtr(info, pSubjectInfo, false);
return pSubjectInfo;
}
private static X509Certificate2 FindCertByThumbprint(string thumbprint)
{
try
{
// Remove spaces convert to upper. Windows 10 (preview) and Windows 8 will not return a cert
// unless it is a perfect match with no spaces and all uppercase characters.
string thumbprintFixed = thumbprint.Replace(" ", string.Empty).ToUpperInvariant();
// Check common store locations for the corresponding code-signing cert.
X509Store[] stores = new X509Store[4] { new X509Store(StoreName.My, StoreLocation.CurrentUser),
new X509Store(StoreName.My, StoreLocation.LocalMachine),
new X509Store(StoreName.TrustedPublisher, StoreLocation.CurrentUser),
new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine) };
foreach (X509Store store in stores)
{
store.Open(OpenFlags.ReadOnly);
// Find the cert!
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprintFixed, false);
store.Close();
// If we didn't find the cert, try the next store.
if (certs.Count < 1)
{
continue;
}
// Return the cert (first one if there is more than one identical cert in the collection).
return certs[0];
}
// No cert was found. Return null.
throw new Exception(string.Format(@"A certificate matching the thumbprint: ""{0}"" could not be found. Make sure that a valid certificate matching the provided thumbprint is installed.", thumbprint));
}
catch (Exception e)
{
throw new Exception(string.Format("{0}", e.Message));
}
}
private static IntPtr CreateSignerCert(X509Certificate2 cert)
{
SIGNER_CERT signerCert = new SIGNER_CERT
{
cbSize = (uint)Marshal.SizeOf(typeof(SIGNER_CERT)),
dwCertChoice = 0x2,
Union1 = new SIGNER_CERT.SignerCertUnion
{
pCertStoreInfo = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SIGNER_CERT_STORE_INFO)))
},
hwnd = IntPtr.Zero
};
const int X509_ASN_ENCODING = 0x00000001;
const int PKCS_7_ASN_ENCODING = 0x00010000;
IntPtr pCertContext = CertCreateCertificateContext(
X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
cert.GetRawCertData(),
cert.GetRawCertData().Length);
SIGNER_CERT_STORE_INFO certStoreInfo = new SIGNER_CERT_STORE_INFO
{
cbSize = (uint)Marshal.SizeOf(typeof(SIGNER_CERT_STORE_INFO)),
pSigningCert = pCertContext,
dwCertPolicy = 0x2, // SIGNER_CERT_POLICY_CHAIN
hCertStore = IntPtr.Zero
};
Marshal.StructureToPtr(certStoreInfo, signerCert.Union1.pCertStoreInfo, false);
IntPtr pSignerCert = Marshal.AllocHGlobal(Marshal.SizeOf(signerCert));
Marshal.StructureToPtr(signerCert, pSignerCert, false);
return pSignerCert;
}
private static IntPtr CreateSignerCert(string thumbprint)
{
SIGNER_CERT signerCert = new SIGNER_CERT
{
cbSize = (uint)Marshal.SizeOf(typeof(SIGNER_CERT)),
dwCertChoice = 0x2,
Union1 = new SIGNER_CERT.SignerCertUnion
{
pCertStoreInfo = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SIGNER_CERT_STORE_INFO)))
},
hwnd = IntPtr.Zero
};
const int X509_ASN_ENCODING = 0x00000001;
const int PKCS_7_ASN_ENCODING = 0x00010000;
X509Certificate2 cert = FindCertByThumbprint(thumbprint);
IntPtr pCertContext = CertCreateCertificateContext(
X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
cert.GetRawCertData(),
cert.GetRawCertData().Length);
SIGNER_CERT_STORE_INFO certStoreInfo = new SIGNER_CERT_STORE_INFO
{
cbSize = (uint)Marshal.SizeOf(typeof(SIGNER_CERT_STORE_INFO)),
pSigningCert = pCertContext,
dwCertPolicy = 0x2, // SIGNER_CERT_POLICY_CHAIN
hCertStore = IntPtr.Zero
};
Marshal.StructureToPtr(certStoreInfo, signerCert.Union1.pCertStoreInfo, false);
IntPtr pSignerCert = Marshal.AllocHGlobal(Marshal.SizeOf(signerCert));
Marshal.StructureToPtr(signerCert, pSignerCert, false);
return pSignerCert;
}
private static IntPtr CreateSignerSignatureInfo()
{
SIGNER_SIGNATURE_INFO signatureInfo = new SIGNER_SIGNATURE_INFO
{
cbSize = (uint)Marshal.SizeOf(typeof(SIGNER_SIGNATURE_INFO)),
algidHash = 0x00008004, // CALG_SHA1
dwAttrChoice = 0x0, // SIGNER_NO_ATTR
pAttrAuthCode = IntPtr.Zero,
psAuthenticated = IntPtr.Zero,
psUnauthenticated = IntPtr.Zero
};
IntPtr pSignatureInfo = Marshal.AllocHGlobal(Marshal.SizeOf(signatureInfo));
Marshal.StructureToPtr(signatureInfo, pSignatureInfo, false);
return pSignatureInfo;
}
private static IntPtr GetProviderInfo(X509Certificate2 cert)
{
if (cert == null || !cert.HasPrivateKey)
{
return IntPtr.Zero;
}
ICspAsymmetricAlgorithm key = (ICspAsymmetricAlgorithm)cert.PrivateKey;
const int PVK_TYPE_KEYCONTAINER = 2;
if (key == null)
{
return IntPtr.Zero;
}
SIGNER_PROVIDER_INFO providerInfo = new SIGNER_PROVIDER_INFO
{
cbSize = (uint)Marshal.SizeOf(typeof(SIGNER_PROVIDER_INFO)),
pwszProviderName = Marshal.StringToHGlobalUni(key.CspKeyContainerInfo.ProviderName),
dwProviderType = (uint)key.CspKeyContainerInfo.ProviderType,
dwPvkChoice = PVK_TYPE_KEYCONTAINER,
Union1 = new SIGNER_PROVIDER_INFO.SignerProviderUnion
{
pwszKeyContainer = Marshal.StringToHGlobalUni(key.CspKeyContainerInfo.KeyContainerName)
},
};
IntPtr pProviderInfo = Marshal.AllocHGlobal(Marshal.SizeOf(providerInfo));
Marshal.StructureToPtr(providerInfo, pProviderInfo, false);
return pProviderInfo;
}
// Use SignerSign
private static void SignCode(IntPtr pSubjectInfo, IntPtr pSignerCert, IntPtr pSignatureInfo, IntPtr pProviderInfo)
{
int hResult = SignerSign(
pSubjectInfo,
pSignerCert,
pSignatureInfo,
pProviderInfo,
null,
IntPtr.Zero,
IntPtr.Zero
);
if (hResult != 0)
{
// See if we can get anything useful. Jury's still out on this one.
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
}
// Use SignerSignEx
private static void SignCode(uint dwFlags, IntPtr pSubjectInfo, IntPtr pSignerCert, IntPtr pSignatureInfo, IntPtr pProviderInfo, out SIGNER_CONTEXT signerContext)
{
int hResult = SignerSignEx(
dwFlags,
pSubjectInfo,
pSignerCert,
pSignatureInfo,
pProviderInfo,
null,
IntPtr.Zero,
IntPtr.Zero,
out signerContext
);
if (hResult != 0)
{
// See if we can get anything useful. Jury's still out on this one.
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
}
// Use SignerTimeStamp
private static void TimeStampSignedCode(IntPtr pSubjectInfo, string timestampUrl)
{
int hResult = SignerTimeStamp(
pSubjectInfo,
timestampUrl,
IntPtr.Zero,
IntPtr.Zero
);
if (hResult != 0)
{
// We can't get anything useful from GetHRForLastWin32Error, so let's throw our own.
//Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
throw new Exception(string.Format(@"""{0}"" could not be used at this time. If necessary, check the timestampUrl, internet connection, and try again.", timestampUrl));
}
}
// Use SignerTimeStampEx
private static void TimeStampSignedCode(uint dwFlags, IntPtr pSubjectInfo, string timestampUrl, out SIGNER_CONTEXT signerContext)
{
int hResult = SignerTimeStampEx(
dwFlags,
pSubjectInfo,
timestampUrl,
IntPtr.Zero,
IntPtr.Zero,
out signerContext
);
if (hResult != 0)
{
// We can't get anything useful from GetHRForLastWin32Error, so let's throw our own.
//Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
throw new Exception(string.Format(@"""{0}"" could not be used at this time. If necessary, check the timestampUrl, internet connection, and try again.", timestampUrl));
}
}
#endregion
}
}
| Bouncy Castle | 26,344,271 | 13 |
I try to use Jasypt with Bouncy Castle crypro provides (128Bit AES) in a Spring Application to decrypt entity properties while saving them with Hibernate. But I always get this org.jasypt.exceptions.EncryptionOperationNotPossibleException when try to save the entrity.
org.jasypt.exceptions.EncryptionOperationNotPossibleException
Encryption raised an exception. A possible cause is you are using strong encryption
algorithms and you have not installed the Java Cryptography Extension (JCE) Unlimited
Strength Jurisdiction Policy Files in this Java Virtual Machine
at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.handleInvalidKeyException(StandardPBEByteEncryptor.java:1073)
at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.encrypt(StandardPBEByteEncryptor.java:924)
at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.encrypt(StandardPBEStringEncryptor.java:642)
at org.jasypt.hibernate4.type.AbstractEncryptedAsStringType.nullSafeSet(AbstractEncryptedAsStringType.java:155)
at org.hibernate.type.CustomType.nullSafeSet(CustomType.java:158)
(full stacktrace below)
I do not use Java Cryptography Extension (JCE), thats why I try to use Bouncy Castle
I think there is something wrong with the spring configuration, does anybody find the problem?
My spring Configuration is:
<bean id="bouncyCastleProvider" class="org.bouncycastle.jce.provider.BouncyCastleProvider"/>
<bean class="org.jasypt.hibernate4.encryptor.HibernatePBEStringEncryptor" depends-on="bouncyCastleProvider">
<property name="provider" ref="bouncyCastleProvider"/>
<property name="providerName" value="BC"/>
<property name="saltGenerator">
<bean class="org.jasypt.salt.RandomSaltGenerator"/>
</property>
<property name="registeredName" value="STRING_ENCRYPTOR"/>
<property name="algorithm" value="PBEWITHSHA256AND128BITAES-CBC-BC"/>
<property name="password" value="sEcRET1234"/>
</bean>
Usage:
@Entity
@TypeDef(name = "encryptedString", typeClass = EncryptedStringType.class, parameters = { @Parameter(name = "encryptorRegisteredName", value = "STRING_ENCRYPTOR") })
public class SubscriptionProcess {
...
@Type(type = "encryptedString")
private String debitAccountIban;
...
}
pom/dependenies
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt-hibernate4</artifactId>
<version>1.9.2</version>
</dependency>
...
<dependency>
<groupId>org.bouncycastle</groupId>
<!-- I use an older version of bouncy castle that is also used by tika -->
<artifactId>bcprov-jdk15</artifactId>
<version>1.45</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcmail-jdk15</artifactId>
<version>1.45</version>
</dependency>
Full Stack Trace
org.jasypt.exceptions.EncryptionOperationNotPossibleException: Encryption raised an exception. A possible cause is you are using strong encryption algorithms and you have not installed the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files in this Java Virtual Machine
at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.handleInvalidKeyException(StandardPBEByteEncryptor.java:1073)
at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.encrypt(StandardPBEByteEncryptor.java:924)
at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.encrypt(StandardPBEStringEncryptor.java:642)
at org.jasypt.hibernate4.type.AbstractEncryptedAsStringType.nullSafeSet(AbstractEncryptedAsStringType.java:155)
at org.hibernate.type.CustomType.nullSafeSet(CustomType.java:158)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2843)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2818)
at org.hibernate.persister.entity.AbstractEntityPersister$4.bindValues(AbstractEntityPersister.java:3025)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3556)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:97)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:480)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:191)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:175)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:210)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:807)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:780)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:785)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:291)
at com.sun.proxy.$Proxy78.persist(Unknown Source)
at com.demo.base.user.BaseUserDomainCreatorUtil$Persistent.postCreate(BaseUserDomainCreatorUtil.java:424)
at com.demo.base.user.BaseUserDomainCreatorUtil.createSafeCustodyAccount(BaseUserDomainCreatorUtil.java:321)
at com.demo.base.user.BaseUserDomainCreatorUtil.createSafeCustodyAccount(BaseUserDomainCreatorUtil.java:329)
at com.demo.base.user.BaseUserDomainCreatorUtil.createSafeCustodyAccount(BaseUserDomainCreatorUtil.java:333)
at com.demo.base.user.BaseUserDomainCreatorUtil.createUserWithSafeCustodyAccount(BaseUserDomainCreatorUtil.java:128)
at com.demo.app.asset.AssetTestScenario.<init>(AssetTestScenario.java:66)
at com.demo.app.asset.dao.SubscriptionProcessDaoSpringTest.testPersistence_aroundBody0(SubscriptionProcessDaoSpringTest.java:62)
at com.demo.app.asset.dao.SubscriptionProcessDaoSpringTest$AjcClosure1.run(SubscriptionProcessDaoSpringTest.java:1)
at org.springframework.transaction.aspectj.AbstractTransactionAspect.ajc$around$org_springframework_transaction_aspectj_AbstractTransactionAspect$1$2a73e96cproceed(AbstractTransactionAspect.aj:60)
at org.springframework.transaction.aspectj.AbstractTransactionAspect$AbstractTransactionAspect$1.proceedWithInvocation(AbstractTransactionAspect.aj:66)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:267)
at org.springframework.transaction.aspectj.AbstractTransactionAspect.ajc$around$org_springframework_transaction_aspectj_AbstractTransactionAspect$1$2a73e96c(AbstractTransactionAspect.aj:64)
at com.demo.app.asset.dao.SubscriptionProcessDaoSpringTest.testPersistence(SubscriptionProcessDaoSpringTest.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:217)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
| Jasypt is designed to be used with JCE providers, the terminology that this project uses on its web may be confusing you since there is the follow sentence:
Open API for use with any JCE provider, and not only the default Java
VM one. Jasypt can be easily used with well-known providers like
Bouncy Castle
From this sentence maybe you're understanding that Jasypt can be used with JCE or with BouncyCastle like both are working differently or something like that; however, what this sentence means is that there are many JCE providers, default providers which come with default java installation and non-default ones, however both accomplish the JCA/JCE specification and both can work with Jasypt.
As I said BouncyCastle has a JCE provider, from the bouncycastle you can see:
A provider for the Java Cryptography Extension and the Java
Cryptography Architecture.
So if you're trying to make encrypt/decrypt operations using org.bouncycastle.jce.provider.BouncyCastleProvider as provider you've got the same restrictions that all JCE providers have, respect to available algorithms and key length.
To avoid this restrictions about key length and algorithms and to pass the errors you have, you must install Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files for your jvm version.
For example for java 1.7 you can download the files from here. And then copy the jars in $JAVA_HOME\jre\lib\security overwriting the existing local_policy.jar and US_export_policy.jar.
Hope this helps.
| Bouncy Castle | 30,278,104 | 13 |
We have a Java application where a job is scheduled to run every 5 minutes. In that job, there is a security component that does the following every time it is executed:
java.security.Security
.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
My questions are:
Is it required to add the security provider multiple times in the application? Does it serve any purpose? To me, it doesn't make sense and adding it once should suffice.
Is it a candidate for a potential memory leak in the application?
To clarify, I want to add Bouncy Castle security provider programmatically in my application and not statically via JRE. IMO, adding Bouncy Castle security provider once in the application is enough and I need not do in multiple times.
| According to addProvider's javadoc:
Returns:
the preference position in which the provider was added, or -1 if the provider was not added because it is already installed
addProvider already checks if the provider is installed, so, even if you have multiple calls across your application, it will just be added once. And after you add it, it will remain there until the JVM stops (or if someone calls removeProvider).
Of course you can optimize it and put just a single call in a main class (some class that you know it's always loaded at application startup), but I wouldn't worry much about that.
I had worked with systems that had more than one call to addProvider in different parts (because they could be called in any order and were independent from each other), all running in the same JVM, and it never got any memory leaks. Of course it's just my case, but I'm not aware of this causing leaks.
If you want to call addProvider only if the provider is not added yet, you can call Security.getProvider() to check that. If the provider is not in the JVM, it returns null:
// add provider only if it's not in the JVM
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
| Bouncy Castle | 45,197,948 | 13 |
Is Bouncy Castle API Thread Safe ? Especially,
org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher
org.bouncycastle.crypto.paddings.PKCS7Padding
org.bouncycastle.crypto.engines.AESFastEngine
org.bouncycastle.crypto.modes.CBCBlockCipher
I am planning to write a singleton Spring bean for basic level cryptography support in my app. Since it is a web application, there are greater chances of multiple threads accessing this component at a time. So tread safety is essential here.
Please let me know if you have come across such situations using Bouncy Castle.
| It really does not matter if the API/Code is thread safe. CBC encryption in itself is not thread safe.
Some terminology -
E(X) = Enctrypt message X
D(X) = Dectrypt X. (Note that D(E(X)) = X)
IV = Initialization vector. A random sequence to bootstrap the CBC algorithm
CBC = Cipher block chaining.
A really simple CBC implementation can look like:
P1, P2, P3 = Plain text messages
1. Generate an IV, just random bits.
2. Calculate E( P1 xor IV) call this C1
3. Calculate E( P2 xor C1) call this C2
4. Calculate E( P3 xor C2) call this C3.
As you can see, the result of encrypting P1, P2 and P3 (in that order) is different from encrypting P2, P1 and P3 (in that order).
So, in a CBC implementation, order is important. Any algorithm where order is important can not, by definition, be thread safe.
You can make a Singleton factory that delivers encryption objects, but you cant trust them to be thread safe.
| Bouncy Castle | 49,473 | 12 |
This unit test is failing:
public void testDigest() throws NoSuchAlgorithmException {
String hashExpected = "150a14ed5bea6cc731cf86c41566ac427a8db48ef1b9fd626664b3bfbb99071fa4c922f33dde38719b8c8354e2b7ab9d77e0e67fc12843920a712e73d558e197";
MessageDigest md = new MessageDigest();
String hashActual = new String(md.digest("hi"));
Assert.assertEquals(hashExpected, hashActual);
}
Below is my implementation of my MessageDigest class:
import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA512Digest;
import org.bouncycastle.crypto.io.DigestInputStream;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class MessageDigest {
private Digest messageDigest;
public MessageDigest() throws NoSuchAlgorithmException {
Security.addProvider(new BouncyCastleProvider());
messageDigest = new SHA512Digest();
}
public byte[] digest(String message) {
byte[] retValue = new byte[messageDigest.getDigestSize()];
messageDigest.update(message.getBytes(), 0, message.length());
messageDigest.doFinal(retValue, 0);
return retValue;
}
}
The test fails with the following reason:
junit.framework.ComparisonFailure: expected:<150a14ed5bea6cc731cf86c41566ac427a8db48ef1b9fd626664b3bfbb99071fa4c922f33dde38719b8c8354e2b7ab9d77e0e67fc12843920a712e73d558e197> but was:<
í[êlÇ1φÄf¬Bz�´Žñ¹ýbfd³¿»™¤É"ó=Þ8q›ŒƒTâ·«�wàæÁ(C’
q.sÕXá
I have a feeling I'm not using the right encoding scheme when I convert my byte[] digest into a string. Any help would be appreciated.
| The value you're expecting is a Hex-encoded value. You're creating a String based on the raw bytes, which won't work.
You should use the standard Java Crypto API whenever possible instead of BouncyCastle specific APIs.
Try the following (the Hex library comes from commons-codec):
Security.addProvider(new BouncyCastleProvider());
String data = "hello world";
MessageDigest mda = MessageDigest.getInstance("SHA-512", "BC");
byte [] digesta = mda.digest(data.getBytes());
MessageDigest mdb = MessageDigest.getInstance("SHA-512", "BC");
byte [] digestb = mdb.digest(data.getBytes());
System.out.println(MessageDigest.isEqual(digesta, digestb));
System.out.println(Hex.encodeHex(digesta));
| Bouncy Castle | 2,208,374 | 12 |
I am trying to write a small application using bouncycastle algorithm, from the BouncyCastleProvider.java it says we have to import and add the provider during runtime by the following code
import org.bouncycastle.jce.provider.BouncyCastleProvider;
Security.addProvider(new BouncyCastleProvider());
error - The import org.bouncycastle cannot be resolved; during import
error - BouncyCastleProvider cannot be resolved to a type; when calling addProvider
I though bouncycastle is not provided with the Android 1.6 SDK, so thought of installing separately. how should i do this?
If Bouncycastle is shipped along with SDK, what should i do to avoid these errors?
I am using Android 1.6, eclipse-V3.4.0 on winXP .
Thanks in advance
| None of these answers is accurate in 2021 or even several years prior.
Neither using Spongy Castle nor recompiling Bouncy Castle with a different package namespace are necessary since the package name conflicts on Android platform were resolved in Honeycomb (unless you still support pre-honeycomb devices). For details why see: https://github.com/rtyley/spongycastle/issues/34
The correct solution is to include the standard Bouncy Castle libraries in your Android application as follows.
The first step is to include the necessary libraries in your gradle file. You can get standard Bouncy Castle from maven, no need to download and check-in the JARs into your project.
When building with gradle add the following to your dependencies section in your gradle project file:
// See https://www.bouncycastle.org/releasenotes.html for latest revision
implementation 'org.bouncycastle:bcpkix-jdk15to18:1.68'
implementation 'org.bouncycastle:bcprov-jdk15to18:1.68'
Depending on your needs you may not need to actually add the Java security provider from the officially released Bouncy Castle. If you just want to use Bouncy Castle classes directly you may do so now. For example I can write this code that builds an X500Name object without installing the security provider:
X500NameBuilder nameBuilder = new X500NameBuilder();
nameBuilder.addRDN(BCStyle.PSEUDONYM, "xyz");
nameBuilder.addRDN(BCStyle.E, "e@example.com");
X500Name name = nameBuilder.build();
On the other hand if you want to write code that takes advantage of Bouncy Castle via the security provider then you should first replace the built-in Android Bouncy Castle security provider with the standard one since Java does not allow two security providers with the same name. This should be done as early as possible during application startup:
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class MyApplication extends Application {
static {
Security.removeProvider("BC");
// Confirm that positioning this provider at the end works for your needs!
Security.addProvider(new BouncyCastleProvider());
}
}
Note that Java security providers rely heavily on reflection. If you are using obfuscation or shrinking your project then the Bouncy Castle classes will end being culled or renamed inappropriately, to prevent that you need to add the following or similar to proguard.pro file:
-keep class org.bouncycastle.jcajce.provider.** { *; }
-keep class org.bouncycastle.jce.provider.** { *; }
Finally you can write code that will use the standard Bouncy Castle security provider under the hood:
// MD2 hash is not secure, just demonstrating...
MessageDigest md = MessageDigest.getInstance("MD2");
byte[] messageDigest = md.digest(byteData);
Since MD2 isn't provided by any of the Android built-in security providers it will only be found if you've added the Bouncy Castle security provider as described above.
| Bouncy Castle | 2,584,401 | 12 |
I am trying to generate X509 certificates with bouncycastle 1.46, with the code below.
The issue I have is that when a certificate is written in a JKS and then reread, the DNs are reversed.
For instance, if I run the code below, I get the following output:
CN=test,O=gina
CN=test,O=gina
CN=test,O=gina
O=gina, CN=test
Does anybody know the reason for this? how to avoid it?
Thanks in advance.
Code:
public static void main(String[] args) {
try {
Security.addProvider(new BouncyCastleProvider());
KeyPair pair = generateKeyPair("RSA", 1024);
X500Name principal = new X500Name("cn=test,o=gina");
System.out.println(principal);
BigInteger sn = BigInteger.valueOf(1234);
Date start = today();
Date end = addYears(start, 2);
X509Certificate cert = generateCert(principal, pair, sn, start, end,
"SHA1withRSA");
cert.verify(pair.getPublic());
System.out.println(cert.getSubjectDN());
// Store the certificate in the JKS
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
ks.setKeyEntry("alias", pair.getPrivate(), KEY_PWD,
new X509Certificate[] {cert});
X509Certificate c
= (X509Certificate)ks.getCertificateChain("alias")[0];
System.out.println(c.getSubjectDN());
OutputStream out = new FileOutputStream("text.jks");
try {
ks.store(out, KEYSTORE_PWD);
} finally {
out.close();
}
// Reread the JKS
ks = KeyStore.getInstance("JKS");
InputStream in = new FileInputStream("text.jks");
try {
ks.load(in, KEYSTORE_PWD);
} finally {
in.close();
}
c = (X509Certificate)ks.getCertificateChain("alias")[0];
c.verify(pair.getPublic());
System.out.println(c.getSubjectDN());
} catch (Exception e) {
e.printStackTrace();
}
}
private static X509Certificate generateCert(X500Name principal,
KeyPair pair, BigInteger sn, Date start, Date end, String sigalg)
throws OperatorCreationException, CertificateException {
JcaX509v3CertificateBuilder certGen
= new JcaX509v3CertificateBuilder(principal, sn, start, end,
principal, pair.getPublic());
JcaContentSignerBuilder builder
= new JcaContentSignerBuilder(sigalg);
builder.setProvider("BC");
ContentSigner signr = builder.build(pair.getPrivate());
X509CertificateHolder certHolder = certGen.build(signr);
JcaX509CertificateConverter conv
= new JcaX509CertificateConverter();
conv.setProvider("BC");
return conv.getCertificate(certHolder);
}
private static KeyPair generateKeyPair(String algorithm, int keySize)
throws NoSuchAlgorithmException {
KeyPairGenerator gen = KeyPairGenerator.getInstance(algorithm);
gen.initialize(keySize);
return gen.generateKeyPair();
}
private static Date today() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
private static Date addYears(Date date, int count) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, count);
return cal.getTime();
}
| This may be a bit simpler. At least in BC 1.48+, you can construct the X500Name thusly, and the OIDs will be ordered in the expected way (or at least, the way you specify them):
final X500Name subject = new X500Name(RFC4519Style.INSTANCE, "CN=test,O=gina");
| Bouncy Castle | 7,567,837 | 12 |
Hy Guys! I'm trying to create x.509 certificate using bouncycastle, which should be signed by another certificate and store it PEM base 64 format.
I've already have self-signed certificate (public and private key). Now I want to create new one and sign it with existing self-signed certificate.
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
X500Principal dnName = new X500Principal("CN=Sergey");
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setSubjectDN(dnName);
certGen.setIssuerDN(caCert.getSubjectX500Principal());
certGen.setNotBefore(validityBeginDate);
certGen.setNotAfter(validityEndDate);
certGen.setPublicKey(keyPair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic()));
X509Certificate cert = certGen.generate(caCertPrivateKey, "BC");
Verification passed without exceptions, which means from my point of view that it was successfully signed by caCert:
cert.verify(caCert.getPublicKey());
Then I decode it to the PEM base 64:
PEMWriter pemWriter = new PEMWriter(new PrintWriter(System.out));
pemWriter.writeObject(cert);
pemWriter.flush();
I get something like this in the output:
-----BEGIN CERTIFICATE-----
MIIDDjCCAnegAwIBAgIBFDAN........
-----END CERTIFICATE-----
When I open it, I see the next:
Why there is no certification chain if it was successfully signed by caCert?
What need to be changed in my code to see certification chain as I expected?
| I was able to find solution. Actually code works as expected. I didn't see chain of certificates because my caRoot certificate wasn't added to the trusted store. After I add my sel-signed certificate to the trusted root certified centers I see the whole certification chain as I expected.
| Bouncy Castle | 15,142,577 | 12 |
I have been trying to put together an in-memory public-key encryption infrastructure using OpenPGP via Bouncy Castle. One of our vendors uses OpenPGP public key encryption to encrypt all their feeds, and requires us to do the same, so I'm stuck with the technology and the implementation. So now I'm coding an OpenPGP encryption/ decryption toolkit for automating these feeds.
The examples at bouncycastle.org inexplicably default to writing encrypted data to and collecting keys from a file system; this is not what I want to do, so I've been trying to get everything stream-based.
I have gotten to the point where I can actually get my code to compile and run, but my encrypted payload is empty. I think I'm missing something silly, but after several days of trying this and that, I have lost the ability to objectively examine this.
My utility class contains these methods:
public static PgpPublicKey ImportPublicKey(
this Stream publicIn)
{
var pubRings =
new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicIn)).GetKeyRings().OfType<PgpPublicKeyRing>();
var pubKeys = pubRings.SelectMany(x => x.GetPublicKeys().OfType<PgpPublicKey>());
var pubKey = pubKeys.FirstOrDefault();
return pubKey;
}
public static Stream Streamify(this string theString, Encoding encoding = null)
{
encoding = encoding ?? Encoding.UTF8;
var stream = new MemoryStream(encoding.GetBytes(theString));
return stream;
}
public static string Stringify(this Stream theStream,
Encoding encoding = null)
{
encoding = encoding ?? Encoding.UTF8;
using (var reader = new StreamReader(theStream, encoding))
{
return reader.ReadToEnd();
}
}
public static byte[] ReadFully(this Stream stream)
{
if (!stream.CanRead) throw new ArgumentException("This is not a readable stream.");
var buffer = new byte[32768];
using (var ms = new MemoryStream())
{
while (true)
{
var read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public static void PgpEncrypt(
this Stream toEncrypt,
Stream outStream,
PgpPublicKey encryptionKey,
bool armor = true,
bool verify = true,
CompressionAlgorithmTag compressionAlgorithm = CompressionAlgorithmTag.Zip)
{
if (armor) outStream = new ArmoredOutputStream(outStream);
var compressor = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
outStream = compressor.Open(outStream);
var data = toEncrypt.ReadFully();
var encryptor = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, verify, new SecureRandom());
encryptor.AddMethod(encryptionKey);
outStream = encryptor.Open(outStream, data.Length);
outStream.Write(data, 0, data.Length);
}
My test method looks like this:
private static void EncryptMessage()
{
var pubKey = @"<public key text>";
var clearText = "This is an encrypted message. There are many like it but this one is cryptic.";
using (var stream = pubKey.Streamify())
{
var key = stream.ImportPublicKey();
using (var clearStream = clearText.Streamify())
using (var cryptoStream = new MemoryStream())
{
clearStream.PgpEncrypt(cryptoStream,key);
cryptoStream.Position = 0;
Console.WriteLine(cryptoStream.Stringify());
Console.WriteLine("Press any key to continue.");
}
}
Console.ReadKey();
}
The result I get looks like this:
-----BEGIN PGP MESSAGE-----
Version: BCPG C# v1.7.4114.6378
Press any key to continue.
Can someone tell me what I am doing wrong?
| OK, I managed to get this working. There were several problems with this implementation. One problem was that certain things had to be done in order. Here is what seems to need to happen:
The raw data needs to be put into a PgpLiteralData object
The literal data needs to be encrypted.
The encrypted data needs to be compressed.
The compressed data (optionally) needs to be armored.
The underlying streams need to be closed in order of usage.
There should be a more elegant way to do this, but the streams used by the BouncyCastle library are all frustratingly one-way, and at several points, I needed to convert the stream to a byte array to get another part to work. I include the code I used and independently verified; if someone has a verifyably better way of doing this, I would be quite interested.
public static class OpenPgpUtility
{
public static void ExportKeyPair(
Stream secretOut,
Stream publicOut,
AsymmetricKeyParameter publicKey,
AsymmetricKeyParameter privateKey,
string identity,
char[] passPhrase,
bool armor)
{
if (armor)
{
secretOut = new ArmoredOutputStream(secretOut);
}
var secretKey = new PgpSecretKey(
PgpSignature.DefaultCertification,
PublicKeyAlgorithmTag.RsaGeneral,
publicKey,
privateKey,
DateTime.UtcNow,
identity,
SymmetricKeyAlgorithmTag.Cast5,
passPhrase,
null,
null,
new SecureRandom()
);
secretKey.Encode(secretOut);
if (armor)
{
secretOut.Close();
publicOut = new ArmoredOutputStream(publicOut);
}
var key = secretKey.PublicKey;
key.Encode(publicOut);
if (armor)
{
publicOut.Close();
}
}
public static PgpPublicKey ImportPublicKey(
this Stream publicIn)
{
var pubRings =
new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicIn)).GetKeyRings().OfType<PgpPublicKeyRing>();
var pubKeys = pubRings.SelectMany(x => x.GetPublicKeys().OfType<PgpPublicKey>());
var pubKey = pubKeys.FirstOrDefault();
return pubKey;
}
public static PgpSecretKey ImportSecretKey(
this Stream secretIn)
{
var secRings =
new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(secretIn)).GetKeyRings().OfType<PgpSecretKeyRing>();
var secKeys = secRings.SelectMany(x => x.GetSecretKeys().OfType<PgpSecretKey>());
var secKey = secKeys.FirstOrDefault();
return secKey;
}
public static Stream Streamify(this string theString, Encoding encoding = null)
{
encoding = encoding ?? Encoding.UTF8;
var stream = new MemoryStream(encoding.GetBytes(theString));
return stream;
}
public static string Stringify(this Stream theStream,
Encoding encoding = null)
{
encoding = encoding ?? Encoding.UTF8;
using (var reader = new StreamReader(theStream, encoding))
{
return reader.ReadToEnd();
}
}
public static byte[] ReadFully(this Stream stream, int position = 0)
{
if (!stream.CanRead) throw new ArgumentException("This is not a readable stream.");
if (stream.CanSeek) stream.Position = 0;
var buffer = new byte[32768];
using (var ms = new MemoryStream())
{
while (true)
{
var read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public static void PgpEncrypt(
this Stream toEncrypt,
Stream outStream,
PgpPublicKey encryptionKey,
bool armor = true,
bool verify = false,
CompressionAlgorithmTag compressionAlgorithm = CompressionAlgorithmTag.Zip)
{
var encryptor = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, verify, new SecureRandom());
var literalizer = new PgpLiteralDataGenerator();
var compressor = new PgpCompressedDataGenerator(compressionAlgorithm);
encryptor.AddMethod(encryptionKey);
//it would be nice if these streams were read/write, and supported seeking. Since they are not,
//we need to shunt the data to a read/write stream so that we can control the flow of data as
//we go.
using (var stream = new MemoryStream()) // this is the read/write stream
using (var armoredStream = armor ? new ArmoredOutputStream(stream) : stream as Stream)
using (var compressedStream = compressor.Open(armoredStream))
{
//data is encrypted first, then compressed, but because of the one-way nature of these streams,
//other "interim" streams are required. The raw data is encapsulated in a "Literal" PGP object.
var rawData = toEncrypt.ReadFully();
var buffer = new byte[1024];
using (var literalOut = new MemoryStream())
using (var literalStream = literalizer.Open(literalOut, 'b', "STREAM", DateTime.UtcNow, buffer))
{
literalStream.Write(rawData, 0, rawData.Length);
literalStream.Close();
var literalData = literalOut.ReadFully();
//The literal data object is then encrypted, which flows into the compressing stream and
//(optionally) into the ASCII armoring stream.
using (var encryptedStream = encryptor.Open(compressedStream, literalData.Length))
{
encryptedStream.Write(literalData, 0, literalData.Length);
encryptedStream.Close();
compressedStream.Close();
armoredStream.Close();
//the stream processes are now complete, and our read/write stream is now populated with
//encrypted data. Convert the stream to a byte array and write to the out stream.
stream.Position = 0;
var data = stream.ReadFully();
outStream.Write(data, 0, data.Length);
}
}
}
}
}
My test method looked like this:
private static void EncryptMessage()
{
var pubKey = @"<public key text here>";
var clearText = @"<message text here>";
using (var stream = pubKey.Streamify())
{
var key = stream.ImportPublicKey();
using (var clearStream = clearText.Streamify())
using (var cryptoStream = new MemoryStream())
{
clearStream.PgpEncrypt(cryptoStream, key);
cryptoStream.Position = 0;
var cryptoString = cryptoStream.Stringify();
Console.WriteLine(cryptoString);
Console.WriteLine("Press any key to continue.");
}
}
Console.ReadKey();
}
Since someone asked, my decryption algorithm looked like this:
public static Stream PgpDecrypt(
this Stream encryptedData,
string armoredPrivateKey,
string privateKeyPassword,
Encoding armorEncoding = null)
{
armorEncoding = armorEncoding ?? Encoding.UTF8;
var stream = PgpUtilities.GetDecoderStream(encryptedData);
var layeredStreams = new List<Stream> { stream }; //this is to clean up/ dispose of any layered streams.
var dataObjectFactory = new PgpObjectFactory(stream);
var dataObject = dataObjectFactory.NextPgpObject();
Dictionary<long, PgpSecretKey> secretKeys;
using (var privateKeyStream = armoredPrivateKey.Streamify(armorEncoding))
{
var secRings =
new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)).GetKeyRings()
.OfType<PgpSecretKeyRing>();
var pgpSecretKeyRings = secRings as PgpSecretKeyRing[] ?? secRings.ToArray();
if (!pgpSecretKeyRings.Any()) throw new ArgumentException("No secret keys found.");
secretKeys = pgpSecretKeyRings.SelectMany(x => x.GetSecretKeys().OfType<PgpSecretKey>())
.ToDictionary(key => key.KeyId, value => value);
}
while (!(dataObject is PgpLiteralData) && dataObject != null)
{
try
{
var compressedData = dataObject as PgpCompressedData;
var listedData = dataObject as PgpEncryptedDataList;
//strip away the compression stream
if (compressedData != null)
{
stream = compressedData.GetDataStream();
layeredStreams.Add(stream);
dataObjectFactory = new PgpObjectFactory(stream);
}
//strip the PgpEncryptedDataList
if (listedData != null)
{
var encryptedDataList = listedData.GetEncryptedDataObjects()
.OfType<PgpPublicKeyEncryptedData>().First();
var decryptionKey = secretKeys[encryptedDataList.KeyId]
.ExtractPrivateKey(privateKeyPassword.ToCharArray());
stream = encryptedDataList.GetDataStream(decryptionKey);
layeredStreams.Add(stream);
dataObjectFactory = new PgpObjectFactory(stream);
}
dataObject = dataObjectFactory.NextPgpObject();
}
catch (Exception ex)
{
//Log exception here.
throw new PgpException("Failed to strip encapsulating streams.", ex);
}
}
foreach (var layeredStream in layeredStreams)
{
layeredStream.Close();
layeredStream.Dispose();
}
if (dataObject == null) return null;
var literalData = (PgpLiteralData)dataObject;
var ms = new MemoryStream();
using (var clearData = literalData.GetInputStream())
{
Streams.PipeAll(clearData, ms);
}
ms.Position = 0;
return ms;
}
| Bouncy Castle | 18,856,937 | 12 |
I'm currently implementing password hashing using scrypt. I have already found a nice scrypt implementation on GitHub. To my surprise I have also discovered a scrypt implementation in the Bouncy Castle library. The class is not documented, Wikipedia didn't mention Bouncy Castle as scrypt implementation provider and I had real trouble finding any code examples of someone using Bouncy Castles scrypt, so this looks somehow suspicious to me.
On the other hand if I had to choose between a GitHubs crypto implementation and Bouncy Castle, I would prefer Bouncy Castle.
So is the Bouncy Castles scrypt the 'real thing'? And can I use Bouncy Castles scrypt over the JCA provider API (or do I need to call it directly like here: AES-256 encryption workflow in scala with bouncy castle: salt and IV usage and transfer/storage)?
EDIT: Best answer I could get by now: https://www.bouncycastle.org/devmailarchive/msg13653.html
| So that people don't have to go to an external site for an answer:
Make sure bouncy castle jars are on your build path
Import SCrypt like so:
import org.bouncycastle.crypto.generators.SCrypt;
Use SCrypt like so:
byte[] sCryptHash = SCrypt.generate(plaintext.getBytes(), salt.getBytes(), cpuDifficultyFactor, memoryDifficultyFactor, parallelismDifficultyFactor, outputLength);
| Bouncy Castle | 22,226,867 | 12 |
I've been trying to use the BouncyCastle library to do PGP encryption/decryption. I have some code that I need to modify to use streams only - no files.
I tried removing the PgpUtilities.WriteFileToLiteralData() and then making it return a stream, but it didn't work (output stream was empty).
To be more clear here is what the method should be:
public static Stream EncryptFile(MemoryStream inputStream, PgpPublicKey encKey, bool withIntegrityCheck)
Here is the code I need to modify:
private static void EncryptFile(Stream outputStream, string fileName, PgpPublicKey encKey, bool armor, bool withIntegrityCheck)
{
if (armor)
outputStream = new ArmoredOutputStream(outputStream);
try
{
MemoryStream bOut = new MemoryStream();
PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(
CompressionAlgorithmTag.Zip);
PgpUtilities.WriteFileToLiteralData(
comData.Open(bOut),
PgpLiteralData.Binary,
new FileInfo(fileName));
comData.Close();
PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(
SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());
cPk.AddMethod(encKey);
byte[] bytes = bOut.ToArray();
Stream cOut = cPk.Open(outputStream, bytes.Length);
cOut.Write(bytes, 0, bytes.Length);
cOut.Close();
if (armor)
outputStream.Close();
}
catch (PgpException e)
{
Console.Error.WriteLine(e);
Exception underlyingException = e.InnerException;
if (underlyingException != null)
{
Console.Error.WriteLine(underlyingException.Message);
Console.Error.WriteLine(underlyingException.StackTrace);
}
}
}
public void EncryptFile(string filePath, string publicKeyFile, string pathToSaveFile)
{
Stream keyIn, fos;
keyIn = File.OpenRead(publicKeyFile);
string[] fileSplit = filePath.Split('\\');
string fileName = fileSplit[fileSplit.Length - 1];
fos = File.Create(pathToSaveFile + fileName + ".asc");
EncryptFile(fos, filePath, ReadPublicKey(keyIn), true, true);
keyIn.Close();
fos.Close();
}
| I got it working. The code uses byte[] for input and output of both decryption and encryption - no files.
Here is the full class:
class PGP
{
public PGP() { }
/**
* A simple routine that opens a key ring file and loads the first available key suitable for
* encryption.
*
* @param in
* @return
* @m_out
* @
*/
public static PgpPublicKey ReadPublicKey(Stream inputStream)
{
inputStream = PgpUtilities.GetDecoderStream(inputStream);
PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(inputStream);
//
// we just loop through the collection till we find a key suitable for encryption, in the real
// world you would probably want to be a bit smarter about this.
//
//
// iterate through the key rings.
//
foreach (PgpPublicKeyRing kRing in pgpPub.GetKeyRings())
{
foreach (PgpPublicKey k in kRing.GetPublicKeys())
{
if (k.IsEncryptionKey)
return k;
}
}
throw new ArgumentException("Can't find encryption key in key ring.");
}
/**
* Search a secret key ring collection for a secret key corresponding to
* keyId if it exists.
*
* @param pgpSec a secret key ring collection.
* @param keyId keyId we want.
* @param pass passphrase to decrypt secret key with.
* @return
*/
private static PgpPrivateKey FindSecretKey(PgpSecretKeyRingBundle pgpSec, long keyId, char[] pass)
{
PgpSecretKey pgpSecKey = pgpSec.GetSecretKey(keyId);
if (pgpSecKey == null)
return null;
return pgpSecKey.ExtractPrivateKey(pass);
}
/**
* Decrypt the byte array passed into inputData and return it as
* another byte array.
*
* @param inputData - the data to decrypt
* @param keyIn - a stream from your private keyring file
* @param passCode - the password
* @return - decrypted data as byte array
*/
public static byte[] Decrypt(byte[] inputData, Stream keyIn, string passCode)
{
byte[] error = Encoding.ASCII.GetBytes("ERROR");
Stream inputStream = new MemoryStream(inputData);
inputStream = PgpUtilities.GetDecoderStream(inputStream);
MemoryStream decoded = new MemoryStream();
try
{
PgpObjectFactory pgpF = new PgpObjectFactory(inputStream);
PgpEncryptedDataList enc;
PgpObject o = pgpF.NextPgpObject();
//
// the first object might be a PGP marker packet.
//
if (o is PgpEncryptedDataList)
enc = (PgpEncryptedDataList)o;
else
enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
//
// find the secret key
//
PgpPrivateKey sKey = null;
PgpPublicKeyEncryptedData pbe = null;
PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(
PgpUtilities.GetDecoderStream(keyIn));
foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
{
sKey = FindSecretKey(pgpSec, pked.KeyId, passCode.ToCharArray());
if (sKey != null)
{
pbe = pked;
break;
}
}
if (sKey == null)
throw new ArgumentException("secret key for message not found.");
Stream clear = pbe.GetDataStream(sKey);
PgpObjectFactory plainFact = new PgpObjectFactory(clear);
PgpObject message = plainFact.NextPgpObject();
if (message is PgpCompressedData)
{
PgpCompressedData cData = (PgpCompressedData)message;
PgpObjectFactory pgpFact = new PgpObjectFactory(cData.GetDataStream());
message = pgpFact.NextPgpObject();
}
if (message is PgpLiteralData)
{
PgpLiteralData ld = (PgpLiteralData)message;
Stream unc = ld.GetInputStream();
Streams.PipeAll(unc, decoded);
}
else if (message is PgpOnePassSignatureList)
throw new PgpException("encrypted message contains a signed message - not literal data.");
else
throw new PgpException("message is not a simple encrypted file - type unknown.");
if (pbe.IsIntegrityProtected())
{
if (!pbe.Verify())
MessageBox.Show(null, "Message failed integrity check.", "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
MessageBox.Show(null, "Message integrity check passed.", "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(null, "No message integrity check.", "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decoded.ToArray();
}
catch (Exception e)
{
if (e.Message.StartsWith("Checksum mismatch"))
MessageBox.Show(null, "Likely invalid passcode. Possible data corruption.", "Invalid Passcode", MessageBoxButtons.OK, MessageBoxIcon.Error);
else if (e.Message.StartsWith("Object reference not"))
MessageBox.Show(null, "PGP data does not exist.", "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else if (e.Message.StartsWith("Premature end of stream"))
MessageBox.Show(null, "Partial PGP data found.", "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
MessageBox.Show(null, e.Message, "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Exception underlyingException = e.InnerException;
if (underlyingException != null)
MessageBox.Show(null, underlyingException.Message, "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return error;
}
}
/**
* Encrypt the data.
*
* @param inputData - byte array to encrypt
* @param passPhrase - the password returned by "ReadPublicKey"
* @param withIntegrityCheck - check the data for errors
* @param armor - protect the data streams
* @return - encrypted byte array
*/
public static byte[] Encrypt(byte[] inputData, PgpPublicKey passPhrase, bool withIntegrityCheck, bool armor)
{
byte[] processedData = Compress(inputData, PgpLiteralData.Console, CompressionAlgorithmTag.Uncompressed);
MemoryStream bOut = new MemoryStream();
Stream output = bOut;
if (armor)
output = new ArmoredOutputStream(output);
PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());
encGen.AddMethod(passPhrase);
Stream encOut = encGen.Open(output, processedData.Length);
encOut.Write(processedData, 0, processedData.Length);
encOut.Close();
if (armor)
output.Close();
return bOut.ToArray();
}
private static byte[] Compress(byte[] clearData, string fileName, CompressionAlgorithmTag algorithm)
{
MemoryStream bOut = new MemoryStream();
PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(algorithm);
Stream cos = comData.Open(bOut); // open it with the final destination
PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();
// we want to Generate compressed data. This might be a user option later,
// in which case we would pass in bOut.
Stream pOut = lData.Open(
cos, // the compressed output stream
PgpLiteralData.Binary,
fileName, // "filename" to store
clearData.Length, // length of clear data
DateTime.UtcNow // current time
);
pOut.Write(clearData, 0, clearData.Length);
pOut.Close();
comData.Close();
return bOut.ToArray();
}
}
| Bouncy Castle | 25,441,366 | 12 |
I noticed that there are two bouncycastle provider libraries for Java; bcprov and bcprov-ext. How do they differ? How do I choose which to use?
| bcprov is typically the library you want.
bcprov-ext includes some obscure crypto algorithms that haven't been part of the main release since v1.4.0.
This is briefly explained on the latest releases page:
From release 1.40 some implementations of encryption algorithms were removed from the regular jar files at the request of a number of users. Jars with names of the form *-ext-* still include these (at the moment the list is: NTRU).
NTRU seems to be this algorithm. Personally I'd never heard of it before...
| Bouncy Castle | 29,211,582 | 12 |
Is there any way to convert a Org.BouncyCastle.X509.X509Certificate to System.Security.Cryptography.X509Certificates.X509Certificate2?
The inverse operation is easy, combining Org.BouncyCastle.X509.X509CertificateParser with
System.Security.Cryptography.X509Certificates.X509Certificate2.Export().
| Easy!!
using B = Org.BouncyCastle.X509; //Bouncy certificates
using W = System.Security.Cryptography.X509Certificates;
W.X509Certificate2 certificate = new W.X509Certificate2(pdfCertificate.GetEncoded());
And now I can validate certificate chain in the server:
W.X509Chain ch = new W.X509Chain();
ch.ChainPolicy.RevocationMode = W.X509RevocationMode.NoCheck;
if (!ch.Build(certificate))
res |= ErroresValidacion.CAInvalida;
Useful to validate pdf certifcates extracted with iTextSharp.
| Bouncy Castle | 8,136,651 | 11 |
I am trying to debug an issue with bouncy castle 1.47. I can find a debug jar for 'bcprov' but not for {org.bouncycastle:bcpkix-jdk15on:1.47:jar}.
Is there any other place to download bcpkix-jdk15on-1.47.jar with debug information?
or
Is there a tool that can generate line numbers from a jar (containing .class files) without line numbers and also generated sources for the same generated jar?
or
I had been trying to build the jars from source 1 but the build cannot find the test jars I suppose from the errors.
[javadoc] /tickets/bouncycastle/src-cvs/java/crypto/build/artifacts/jdk1.5/bcprov-jdk15on-147/src/org/bouncycastle/jce/provider/test/AllTests.java:5: package junit.framework does not exist
[javadoc] import junit.framework.Test;
[javadoc] ^
[javadoc] /tickets/bouncycastle/src-cvs/java/crypto/build/artifacts/jdk1.5/bcprov-jdk15on-147/src/org/bouncycastle/jce/provider/test/AllTests.java:6: package junit.framework does not exist
[javadoc] import junit.framework.TestCase;
[javadoc] ^
[javadoc] /tickets/bouncycastle/src-cvs/java/crypto/build/artifacts/jdk1.5/bcprov-jdk15on-147/src/org/bouncycastle/jce/provider/test/AllTests.java:7: package junit.framework does not exist
[javadoc] import junit.framework.TestSuite;
Any help is appreciated.
| I have managed to generate jar with debug information from bouncy castle source.
in ROOT_SRC/bc-build.properties, set release.debug to true
release.suffix: 147
release.name: 1.47
release.debug: true
The build expects mail (sun implementation) and junit jars to be available in classpath. I have put them on to jdk/jre/lib/ext and the build worked. the artifacts were generated in the ROOT_SRC/build directory.
| Bouncy Castle | 12,894,129 | 11 |
I am using RESTEasy encryption. For that I have to generate x.509 certificate by the Java 'keytool' command-line interface.
Please help me
Thank you
| This is the command to generate self signed certificates. All in one line
keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks
-storepass password -validity 360 -keysize 2048
When you run this command, it will ask you for the details of the signatory. These will be the details of your organization. Provide all the details and it will create a new self signed certificate in keystore keystore for you.
NOTE: When it ask for your first and last name, give the domain name of the server which will be the entry point for your users. i.e. www.myserver.com
If you already have a keystore then you can use your existing keystore to add new certificate otherwise this command will create the keystore keystore.jks with the password and add the certificate to the new keystore. Note that if you already have a keystore then you need to provide the password of the existing keystore in -storepass parameter of this command.
For more details, see the keytool man page:
http://docs.oracle.com/javase/1.5.0/docs/tooldocs/solaris/keytool.html
Here you will find details of all the available options you can use with the keytool command.
| Bouncy Castle | 16,851,903 | 11 |
I'm pretty new to BouncyCastle and pgp. I've seen many articles and samples on the internet. Almost every encryption sample contains the code snipped below
if (armor)
out = new ArmoredOutputStream(out);
It seems that my local test passed with both armor and none-armor. I googled around but found few useful and the javadoc of ArmoredOutputStream only shows This is basic output stream.
So what's the difference and when to use it?
Complete code sample:
public static void encryptFile(String decryptedFilePath,
String encryptedFilePath,
String encKeyPath,
boolean armor,
boolean withIntegrityCheck)
throws Exception{
OutputStream out = new FileOutputStream(encryptedFilePath);
FileInputStream pubKey = new FileInputStream(encKeyPath);
PGPPublicKey encKey = readPublicKeyFromCollection2(pubKey);
Security.addProvider(new BouncyCastleProvider());
if (armor)
out = new ArmoredOutputStream(out);
// Init encrypted data generator
PGPEncryptedDataGenerator encryptedDataGenerator =
new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, withIntegrityCheck, new SecureRandom(),"BC");
encryptedDataGenerator.addMethod(encKey);
OutputStream encryptedOut = encryptedDataGenerator.open(out, new byte[BUFFER_SIZE]);
// Init compression
PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
OutputStream compressedOut = compressedDataGenerator.open(encryptedOut);
PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, decryptedFilePath, new Date(), new byte[BUFFER_SIZE]);
FileInputStream inputFileStream = new FileInputStream(decryptedFilePath);
byte[] buf = new byte[BUFFER_SIZE];
int len;
while((len = inputFileStream.read(buf))>0){
literalOut.write(buf,0,len);
}
literalOut.close();
literalDataGenerator.close();
compressedOut.close();
compressedDataGenerator.close();
encryptedOut.close();
encryptedDataGenerator.close();
inputFileStream.close();
out.close();
}
}
| ArmoredOutputStream uses an encoding similar to Base64, so that binary non-printable bytes are converted to something text friendly. You'd do this if you wanted to send the data over email, or post on a site, or some other text medium.
It doesn't make a difference in terms of security. There is a slight expansion of the message size though. The choice really just depends on what you want to do with the output.
| Bouncy Castle | 24,358,996 | 11 |
I am trying to generate a shared secret in my app like this:
public static byte[] generateSharedSecret(PrivateKey privateKey PublicKey publicKey) {
KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH", "SC");
keyAgreement.init(privateKey);
keyAgreement.doPhase(publicKey, true);
return keyAgreement.generateSecret();
}
This is working fine, but the PublicKey I use here should be coming from the backend.
The backend just sends me the x and y value of a point on an elliptic curve and now I am supposed to generate the PublicKey from that. But I just can't figure it out! How can I create a PublicKey instance just from those two values?
| It's actually quite simple! But you need one more thing besides the x and y values. You also need an ECParameterSpec! The ECParameterSpec describes the elliptic curve you are using and your app has to use the same ECParameterSpec as your backend does!
With the x and y values you can create an ECPoint instance and together with your ECParameterSpec you can create an ECPublicKeySpec:
ECParameterSpec ecParameters = ...;
BigInteger x = ...;
BigInteger y = ...;
ECPoint ecPoint = new ECPoint(x, y);
ECPublicKeySpec keySpec = new ECPublicKeySpec(ecPoint, ecParameters);
And now with that ECPublicKeySpec you can generate the PublicKey using a KeyFactory:
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
You can find more information about this topic here.
| Bouncy Castle | 30,116,758 | 11 |
I was attempting to generate a public ECDSA key from a private key, and I haven't managed to find much help on the internet as to how to do this. Pretty much everything is for generating a public key from a public key spec, and I don't know how to get that. So far, this is what I've put together:
public void setPublic() throws GeneralSecurityException {
ECNamedCurveParameterSpec params = ECNamedCurveTable.getParameterSpec("secp256k1");
KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC");
ECCurve curve = params.getCurve();
java.security.spec.EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, params.getSeed());
java.security.spec.ECPoint point = ECPointUtil.decodePoint(ellipticCurve, this.privateKey.getEncoded());
java.security.spec.ECParameterSpec params2=EC5Util.convertSpec(ellipticCurve, params);
java.security.spec.ECPublicKeySpec keySpec = new java.security.spec.ECPublicKeySpec(point,params2);
this.publicKey = fact.generatePublic(keySpec);
}
However, when running, I get the following error:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid point encoding 0x30
at org.bouncycastle.math.ec.ECCurve.decodePoint(Unknown Source)
at org.bouncycastle.jce.ECPointUtil.decodePoint(Unknown Source)
at Wallet.Wallet.setPublic(Wallet.java:125)
What am I doing wrong? Is there a better/easier way to do this?
EDIT: I've managed to get some code to compile, but it does not work correctly:
public void setPublic() throws GeneralSecurityException {
BigInteger privKey = new BigInteger(getHex(privateKey.getEncoded()),16);
X9ECParameters ecp = SECNamedCurves.getByName("secp256k1");
ECPoint curvePt = ecp.getG().multiply(privKey);
BigInteger x = curvePt.getX().toBigInteger();
BigInteger y = curvePt.getY().toBigInteger();
byte[] xBytes = removeSignByte(x.toByteArray());
byte[] yBytes = removeSignByte(y.toByteArray());
byte[] pubKeyBytes = new byte[65];
pubKeyBytes[0] = new Byte("04");
System.arraycopy(xBytes, 0, pubKeyBytes, 1, xBytes.length);
System.arraycopy(yBytes, 0, pubKeyBytes, 33, xBytes.length);
ECNamedCurveParameterSpec params = ECNamedCurveTable.getParameterSpec("secp256k1");
KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC");
ECCurve curve = params.getCurve();
java.security.spec.EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, params.getSeed());
java.security.spec.ECPoint point = ECPointUtil.decodePoint(ellipticCurve, pubKeyBytes);
java.security.spec.ECParameterSpec params2 = EC5Util.convertSpec(ellipticCurve, params);
java.security.spec.ECPublicKeySpec keySpec = new java.security.spec.ECPublicKeySpec(point,params2);
this.publicKey = fact.generatePublic(keySpec);
}
private byte[] removeSignByte(byte[] arr)
{
if(arr.length==33)
{
byte[] newArr = new byte[32];
System.arraycopy(arr, 1, newArr, 0, newArr.length);
return newArr;
}
return arr;
}
When I run it, it generates a publicKey, but it's not the same one that the private key corresponds to.
| So after a while, I figured out a solution and decided to post it in case anyone else has the same issue as me:
KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256k1");
ECPoint Q = ecSpec.getG().multiply(((org.bouncycastle.jce.interfaces.ECPrivateKey) this.privateKey).getD());
ECPublicKeySpec pubSpec = new ECPublicKeySpec(Q, ecSpec);
PublicKey publicKeyGenerated = keyFactory.generatePublic(pubSpec);
this.publicKey = publicKeyGenerated;
EDIT: Removed the code decoding the ECPoint as per @MaartenBodewes comment.
| Bouncy Castle | 49,204,787 | 11 |
I am wondering if this is a correct way to create PrivateKey object in Java from HEX string from this website: https://kjur.github.io/jsrsasign/sample/sample-ecdsa.html
Create a BigInteger from a HEX String:
BigInteger priv = new BigInteger(privateKeyFromSite, 16);
And pass to this method:
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPrivateKeySpec;
public static PrivateKey getPrivateKeyFromECBigIntAndCurve(BigInteger s, String curveName) {
ECParameterSpec ecParameterSpec = ECNamedCurveTable.getParameterSpec(curveName);
ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(s, ecParameterSpec);
try {
KeyFactory keyFactory = KeyFactory.getInstance(EC);
return keyFactory.generatePrivate(privateKeySpec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
return null;
}
}
| Yes it's correct, an EC private key is just a number. If you print out your PrivateKey, you'll see the X and Y coordinates of the corresponding public key.
For example, let's say the following key pair was generated (secp256r1):
EC Private Key:
1b9cdf53588f99cea61c6482c4549b0316bafde19f76851940d71babaec5e569
EC Public Key:
0458ff2cd70c9a0897eb90a7c43d6a656bd76bb8089d52c259db6d9a45bfb37eb9882521c3b1e20a8bae181233b939174ee95e12a47bf62f41a62f1a20381a6f03
We plug the private key bytes into your function:
BigInteger priv = new BigInteger("1b9cdf53588f99cea61c6482c4549b0316bafde19f76851940d71babaec5e569", 16);
PrivateKey privateKey = getPrivateKeyFromECBigIntAndCurve(priv, "secp256r1");
System.out.println(privateKey);
And print it:
EC Private Key [91:05:8a:28:94:f9:5c:cb:c4:34:b8:69:e4:39:d4:57:59:c7:51:35]
X: 58ff2cd70c9a0897eb90a7c43d6a656bd76bb8089d52c259db6d9a45bfb37eb9
Y: 882521c3b1e20a8bae181233b939174ee95e12a47bf62f41a62f1a20381a6f03
As you can see, if you concatenate 04 + X + Y, you'll get the original public key, (04 is the uncompressed EC point tag).
| Bouncy Castle | 52,004,341 | 11 |
I need to code this openssl-sign-instruction in java.
openssl dgst -sha256 -binary -out "signaturefile".sig -sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:-1 -sign "privatekey".pem "file2sign"
This instruction comes from Bundeszentralamt für Steuern (BZSt) - ELMA-File-Upload.
Bitte stellen Sie die Signaturerstellung daher auf RSASSA-PSS mit folgenden Parametern um:
Hashverfahren: SHA-256
Mask Generation Function: MGF1 mit SHA-256 Länge des Salts: 32 Byte Trailer Field: 0xBC
I've already tried different signature algorithms (with and without bouncycastle) but didn't get the same signature-result as with openssl.
This is what I'm doing.
public class SignTest {
public static void main(String[] args){
Security.addProvider(new BouncyCastleProvider());
Signature signatureSHA256Java = Signature.getInstance("SHA256withRSA/PSS");
signatureSHA256Java.setParameter(new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1));
signatureSHA256Java.initSign(KeyManagerHelper.getPrivateKeyFromKeyStore("privatekey"));
signatureSHA256Java.update(byteArray);
byte[] signSHA256Java = signatureSHA256Java.sign();
// after that I compare the Java-sign-bytearry with the openssl one
System.out.println("signSHA256Java == signSHA256Openssl:\n" + Arrays.equals(signSHA256Java, signSHA256Openssl));
}
}
| I edited my question with the correct algorithm to create the signature with java bouncycastle.
Signature signatureSHA256Java = Signature.getInstance("SHA256withRSA/PSS");
signatureSHA256Java.setParameter(new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1));
You can verify the java generated signature with openssl like that
openssl dgst -sha256 -sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:-1 -verify "publickey".pem -signature "signaturefile".sig "file2sign"
| Bouncy Castle | 53,728,536 | 11 |
I'm trying to generate a certificate self-signed by a KeyPair stored in Azure KeyVault.
My end result is a certificate with an invalid signature:
Generating the certificate parameters:
DateTime startDate = DateTime.Now.AddDays(-30);
DateTime expiryDate = startDate.AddYears(100);
BigInteger serialNumber = new BigInteger(32, new Random());
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
X509Name selfSignedCA = new X509Name("CN=Test Root CA");
certGen.SetSerialNumber(serialNumber);
certGen.SetIssuerDN(selfSignedCA); //Self Signed
certGen.SetNotBefore(startDate);
certGen.SetNotAfter(expiryDate);
certGen.SetSubjectDN(selfSignedCA);
Fetching a reference to the Azure KeyVault stored key (HSM like service):
//Create a client connector to Azure KeyVault
var keyClient = new Azure.Security.KeyVault.Keys.KeyClient(
vaultUri: new Uri("https://xxxx.vault.azure.net/"),
credential: new ClientSecretCredential(
tenantId: "xxxx", //Active Directory
clientId: "xxxx", //Application id?
clientSecret: "xxxx"
)
);
var x = keyClient.GetKey("key-new-ec"); //Fetch the reference to the key
The key is successfully retrieved.
I then try to generate a ECPublicKeyParameters object with the key's public data:
X9ECParameters x9 = ECNamedCurveTable.GetByName("P-256");
Org.BouncyCastle.Math.EC.ECCurve curve = x9.Curve;
var ecPoint = curve.CreatePoint(new Org.BouncyCastle.Math.BigInteger(1, x.Value.Key.X), new Org.BouncyCastle.Math.BigInteger(1, x.Value.Key.Y));
ECDomainParameters dParams = new ECDomainParameters(curve, ecPoint, x9.N);
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(ecPoint, dParams);
certGen.SetPublicKey(pubKey); //Setting the certificate's public key with the fetched one
Next step is generating a certificate signed with the key. I implemented a new ISignatureFactory object that should sign with an external signature function of KeyVault:
AzureKeyVaultSignatureFactory customSignatureFactory = new AzureKeyVaultSignatureFactory(1);
Org.BouncyCastle.X509.X509Certificate cert = certGen.Generate(customSignatureFactory);
This is my custom AzureKeyVaultSignatureFactory:
public class AzureKeyVaultSignatureFactory : ISignatureFactory
{
private readonly int _keyHandle;
public AzureKeyVaultSignatureFactory(int keyHandle)
{
this._keyHandle = keyHandle;
}
public IStreamCalculator CreateCalculator()
{
var sig = new CustomAzureKeyVaultDigestSigner(this._keyHandle);
sig.Init(true, null);
return new DefaultSignatureCalculator(sig);
}
internal class CustomAzureKeyVaultDigestSigner : ISigner
{
private readonly int _keyHandle;
private byte[] _input;
public CustomAzureKeyVaultDigestSigner(int keyHandle)
{
this._keyHandle = keyHandle;
}
public void Init(bool forSigning, ICipherParameters parameters)
{
this.Reset();
}
public void Update(byte input)
{
return;
}
public void BlockUpdate(byte[] input, int inOff, int length)
{
this._input = input.Skip(inOff).Take(length).ToArray();
}
public byte[] GenerateSignature()
{
//Crypto Client (Specific Key)
try
{
//Crypto Client (Specific Key)
CryptographyClient identitiesCAKey_cryptoClient = new CryptographyClient(
keyId: new Uri("https://xxxx.vault.azure.net/keys/key-new-ec/xxxx"),
credential: new ClientSecretCredential(
tenantId: "xxxx", //Active Directory
clientId: "xxxx", //Application id?
clientSecret: "xxxx"
)
);
SignResult signResult = identitiesCAKey_cryptoClient.SignData(SignatureAlgorithm.ES256, this._input);
return signResult.Signature;
}
catch (Exception ex)
{
throw ex;
}
return null;
}
public bool VerifySignature(byte[] signature)
{
return false;
}
public void Reset() { }
public string AlgorithmName => "SHA-256withECDSA";
}
public object AlgorithmDetails => new AlgorithmIdentifier(X9ObjectIdentifiers.ECDsaWithSha256, DerNull.Instance);
}
Then I convert and write the certificate to a file:
//convert to windows type 2 and get Base64
X509Certificate2 cert2 = new X509Certificate2(DotNetUtilities.ToX509Certificate(cert));
byte[] encoded = cert2.GetRawCertData();
string certOutString = Convert.ToBase64String(encoded);
System.IO.File.WriteAllBytes(@"test-signed2.cer", encoded); //-this is good!
What am I doing wrong? Maybe constructing the ECCurve from X/Y is not enough?
Thanks!
| The problem is that the signature being returned by key vault is in a "raw" (64-byte) format, where the first 32 are R and the last 32 are S. For this to work in bouncycastle, your GenerateSignature method needs to return this in an ASN.1 formatted byte array, which in the end will be somewhere between 70 and 72 bytes.
You can look around online on what this practically means, but you will want to:
Create a new byte array for your result
split the output from key vault into two initially 32-bit arrays, R and S
If the 0th element of either of the R or S arrays has a high MSB, you need to insert a 0 before the start of the respective array (otherwise do nothing and the array stays 32 bytes long).
Build the necessary ASN.1 headers (either manually like I showed below, or maybe bouncycastle has some library features to create an ASN.1 message). So at the end, the output byte array should contain
0x30
one byte containing the length of the rest of the array*
0x02
a byte containing the length of the R array (either 32 or 33 depending on if + or -)
0x02
a byte containing the length of the S array (either 32 or 33 depending on if + or -)
the entire S array
Return this array as the output of GenerateSignature
* so the entire length will be length of R + length of S + 4 header bytes (R length, R header, S length, S header)
I have tested this approach with a key of my own as returned by a cloud service which also returns the 64 byte R+S response and it works.
| Bouncy Castle | 63,268,843 | 11 |
I'm familiar with basic cryptography in java But have zero experience in bouncycastle, Recently I came across a requirement that needs to read an encrypted and signed file from FTP.
The sender has directed me to use bcfips ebook for reading those encrypted and signed files.
I went through the download page of the bouncy castle website, But I'm confused by a lot of jargon that I can't understand and I don't know which jar file should I use.
I'm wondering what's the difference between bcprov and bcpkix and bcfips?
I appreciate it if someone points me on the correct path.
| First of all, bcprov contains the Java security provider as well as the "lightweight API". Quite often this library is simply referred to as "Bouncy Castle", shortened to the acronym "BC" as provider name in Java. These providers provide SPI's (service provider implementations) or implementation classes that allow specific algorithms to be used by the Cipher, Signature, MessageDigest and Mac classes (etc.) that provide a unified API for your applications.
The Bouncy Castle library has it's own specific architecture and API. It is this public API is generally revered to as the "lightweight API". The Bouncy Castle library provides most of this functionality as services that are registered using the Bouncy Castle provider implementation. That way the supplied algorithms can be used from generic classes such as Cipher.
The library also contains a lot of utility classes, some of which are simply required to implement the provider. All the implementation classes are available to the user, which means that the lightweight API is a bit of a maze. It also means that there is a chance that updates break software that make use of the lightweight API. For instance, there have been a few updates of the ASN.1 encoder / decoder that weren't backwards compatible.
The main reason to use the Bouncy Castle library is the extended functionality that is provided. For instance, the Bouncy Castle provider provides a lot of ciphers that are not present in the standard Java runtime. However, you should keep in mind that the algorithms that are provided by the Java runtime can be optimized to use CPU speedups and may receive better testing. So before choosing it you should definitely check if the algorithms are not present in the Java provided algorithms.
A relatively new development is the support for CPU hardware acceleration when using an LTS release - currently only on Linux.
bcfips is the certified FIPS provider. FIPS uses a specific set of algorithms defined by NIST and bcfips therefore contains a subset of the functionality provided by bcprov. FIPS also has strict rules when it comes to e.g. destruction of key material. FIPS certification is rather expensive and time consuming and BC would want you to get a support contract when using their FIPS provider.
You may need this library if your software is required to use FIPS certified algorithm implementations. Note that they will still be implemented in software and will therefore e.g. not use AES acceleration.
Now bcpkixis a different beast altogether. It provides support for "PKIX/CMS/EAC/PKCS/OCSP/TSP/OPENSSL" protocols and container formats.
The following modules are present:
PKIX (in the cert package) means "X.509 based Public Key Infrastructure and contains support for certificates, certificate requests, CRL's etc.; the same type of certificates that are used for TLS that is used for HTTPS, i.e. the secure connections that your browser uses. There are some separate related packages inside the main package:
cmc: Certificate Management over CMS
dvcs: Data Validation and Certification Server Protocols
est: Enrollment over Secure Transport
CMS means Cryptographic Message Syntax, a format to envelope (i.e. encrypt) and sign messages in a structural way. CMS is also known as PKSC#7 (.p7 file extension) which is the standard in which it is defined. CMS is a flexible, descriptive format, i.e. it indicates which algorithms are used and helps with key management. It uses X.509 certificates and is based on the same technology.
MIME: related to CMS, SMIME is the use of CMS within the email protocols.
EAC is a technology used for European ePassports. It stands for Extended Access Control, which can be used to gain access to e.g. the fingerprint or - in the case of the German passport - additional personal information, assuming you've got the right set of certificates and keys of course.
PKCS stands for Public Key Cryptographic Standards, historically created by "RSA Laboratories", however the classes mainly seem to support PKCS#8 (private key storage), PKSC#10 (certification requests) and PKCS#12 (key / trust stores). This adds support to create and parse files with .p8, .p10 / .csr and .12 / .pfx file extensions.
OCSP is the Online Certificate Status Protocol, used to check the status of X.509 certificates, e.g. when using TLS.
TSP means Time Stamping Protocol, a method of signing messages together with a date / time from a trusted source (it can also mean Trusted Service Provider, but here it doesn't).
OpenSSL is of course a library and application. It has some specific / proprietary methods concerning key derivation from passwords and the application of these to encrypt / decrypt PKCS#8 private keys.
The operator in the PKIX library seems to be a way to operate directly on the "lightweight API" or on the JCA provided API using a generalized interface (basically a way of performing dependency injection).
You'd use this library if you need to implement any of the higher level protocols / container formats. Many of these formats are relatively old, so you might be looking for e.g. NaCL instead of CMS. That said, CMS certainly can be secured and having these protocols implemented is great for (backwards) compatibility with existing systems.
If I'm not mistaken the PKIX library can be used without installing the Bouncy Castle ("BC") provider, except when you're using specific algorithms not provided by the existing providers in your Java runtime.
Unfortunately the documentation of Bouncy Castle is very sparse, most packages do not even explain what they are for or how they can be used. There isn't a huge amount of JUnit tests or demo applications either.
| Bouncy Castle | 73,010,512 | 11 |
In Java I have a ECDH public Key that I am sending as a byte array.
Once I have received the byte array how can I turn it back into a public key?
I am using Bouncy Castle but a Java solution would be just as useful.
Thanks
| When you got the encoded key, assuming you used the default "[your keyPair].getPublic().getEncoded()" method, this will work.
X509EncodedKeySpec ks = new X509EncodedKeySpec(pubKeyByteString.toByteArray());
KeyFactory kf;
try {
kf = java.security.KeyFactory.getInstance("ECDH");
} catch (NoSuchAlgorithmException e) {
log.error("Cryptography error: could not initialize ECDH keyfactory!", e);
return;
}
ECPublicKey remotePublicKey;
try {
remotePublicKey = (ECPublicKey)kf.generatePublic(ks);
} catch (InvalidKeySpecException e) {
log.warn("Received invalid key specification from client",e);
return;
} catch (ClassCastException e) {
log.warn("Received valid X.509 key from client but it was not EC Public Key material",e);
return;
}
| Bouncy Castle | 2,218,879 | 10 |
I have a block of ciphertext that was created using the JCE algorithim "PBEWithSHA256And256BitAES-CBC-BC". The provider is BouncyCastle. What I'd like to do it decrypt this ciphertext using the BouncyCastle lightweight API. I don't want to use JCE because that requires installing the Unlimited Strength Jurisdiction Policy Files.
Documentation seems to be thin on the ground when it comes to using BC with PBE and AES.
Here's what I have so far. The decryption code runs without exception but returns rubbish.
The encryption code,
String password = "qwerty";
String plainText = "hello world";
byte[] salt = generateSalt();
byte[] cipherText = encrypt(plainText, password.toCharArray(), salt);
private static byte[] generateSalt() throws NoSuchAlgorithmException {
byte salt[] = new byte[8];
SecureRandom saltGen = SecureRandom.getInstance("SHA1PRNG");
saltGen.nextBytes(salt);
return salt;
}
private static byte[] encrypt(String plainText, char[] password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Security.addProvider(new BouncyCastleProvider());
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
Cipher encryptionCipher = Cipher.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
encryptionCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
return encryptionCipher.doFinal(plainText.getBytes());
}
The decryption code,
byte[] decryptedText = decrypt(cipherText, password.getBytes(), salt);
private static byte[] decrypt(byte[] cipherText, byte[] password, byte[] salt) throws DataLengthException, IllegalStateException, InvalidCipherTextException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
BlockCipher engine = new AESEngine();
CBCBlockCipher cipher = new CBCBlockCipher(engine);
PKCS5S1ParametersGenerator keyGenerator = new PKCS5S1ParametersGenerator(new SHA256Digest());
keyGenerator.init(password, salt, 20);
CipherParameters keyParams = keyGenerator.generateDerivedParameters(256);
cipher.init(false, keyParams);
byte[] decryptedBytes = new byte[cipherText.length];
int numBytesCopied = cipher.processBlock(cipherText, 0, decryptedBytes, 0);
return decryptedBytes;
}
| I tried this and it seemed to work. Borrowed heavily from the BC class org.bouncycastle.jce.provider.test.PBETest
private byte[] decryptWithLWCrypto(byte[] cipher, String password, byte[] salt, final int iterationCount)
throws Exception
{
PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(new SHA256Digest());
char[] passwordChars = password.toCharArray();
final byte[] pkcs12PasswordBytes = PBEParametersGenerator
.PKCS12PasswordToBytes(passwordChars);
pGen.init(pkcs12PasswordBytes, salt, iterationCount);
CBCBlockCipher aesCBC = new CBCBlockCipher(new AESEngine());
ParametersWithIV aesCBCParams = (ParametersWithIV) pGen.generateDerivedParameters(256, 128);
aesCBC.init(false, aesCBCParams);
PaddedBufferedBlockCipher aesCipher = new PaddedBufferedBlockCipher(aesCBC,
new PKCS7Padding());
byte[] plainTemp = new byte[aesCipher.getOutputSize(cipher.length)];
int offset = aesCipher.processBytes(cipher, 0, cipher.length, plainTemp, 0);
int last = aesCipher.doFinal(plainTemp, offset);
final byte[] plain = new byte[offset + last];
System.arraycopy(plainTemp, 0, plain, 0, plain.length);
return plain;
}
| Bouncy Castle | 2,957,513 | 10 |
I've been pouring through article after article on x509 cert creation, signing, etc. but I've yet to find a solution to my problem - wondering if anyone can point me in the right direction because I'm thoroughly confused at this point. Here's what I'm trying to do:
For the client app:
Generate a public/private keypair
Grab the keys as byte[] and store them on the file system.
Generate an x509 certificate
Generate a signing request
For the server app:
Generate a public/private keypair
Grab the keys as byte[] and store them on the file system.
Create a self-signed X509 certificate
Sign client certificates
Validate client certificates as being signed by self-signed cert in #3 above.
I need to do this all programmatically in .Net and without external .exe's like makecert.exe or openssl.exe - I need to use an in-process library, etc.
I have bits and pieces worked out using various libs like Bouncy Castle, .Net Crypto, openssl, etc. - but I always hit a roadblock either with lack of documention or not being able to get to the keypairs as byte[] so I can persist them, etc. Either I'm making this a lot harder than it is, or there's a severe lack of documentation out there - or both.
I figure someone has to have done this before and I'd really appreciate some help - I'm open to any and all suggestions - thanks!
.. and PKIBlackbox isn't an option - it costs too much :(
| You can use the Bouncycastle C# library. Documentation is not good, but I believe it is not too difficult to work with. You can first go to the Javadocs for the java version of the library; the java and C# version are very similar. Secondly, look at the source code, as it is relatively easy to read.
The class you want is Org.BouncyCastle.X509.X509V3CertificateGenerator. There are some java examples out there on the net that you can use as a guide to creating a C# version. Here is one simple straightforward one.
Finally, Bouncycastle has a very useful class Org.BouncyCastle.Security.DotNetUtilities that helps to map between Bouncycastle objects and .NET objects. One such pair of methods are ToX509Certificate() and FromX509Certificate(). Also, note that the .NET X509Certificate class has Import() and Export() methods.
Together these should be sufficient to allow you to solve your problem.
| Bouncy Castle | 4,637,543 | 10 |
Okay, I'll say now that I know very little about Java. I was given the Bouncy Castle Jar and told that would contain what I needed to do this assignment. The Jar file is bcprov-jdk15on-147.jar. I'm also doing this on a Unix machine maintained by my school, so I can't go in and play with all of the Java files.
When I compile my class using Javac (specifically I use the command javac -classpath bcprov-jdk15on-147.jar encrypt.java), it compiles without error, but when I go to run the program afterward using the command java encrypt, I get this error message:
Exception in thread "main" java.lang.NoClassDefFoundError: org/bouncycastle/jce/provider/BouncyCastleProvider
Caused by: java.lang.ClassNotFoundException: org.bouncycastle.jce.provider.BouncyCastleProvider
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
My Jar file is located in my main folder with all of my other files, just in case it has to go somewhere special and that's what I didn't do.
When I do java -classpath bcprov-jdk15on-147.jar encrypt this is the error I get:
Exception in thread "main" java.lang.NoClassDefFoundError: encrypt
Caused by: java.lang.ClassNotFoundException: encrypt
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
Why am I having trouble running the compiled program?
| Type this for running the program:
java -classpath bcprov-jdk15on-147.jar:. encrypt
That's because your program also needs to have any libraries it uses as part of the classpath at the time of running, not only at compile time.
| Bouncy Castle | 10,134,161 | 10 |
I'm trying to generate cryptographically secure random numbers using Java and using the following code section to create a SecureRandom object to view its provider and algorithm:
Provider prov=new org.spongycastle.jce.provider.BouncyCastleProvider();
Security.insertProviderAt(prov, 1);
SecureRandom sr=new SecureRandom();
srProvider=sr.getProvider().toString();
srAlgorithm=sr.getAlgorithm();
(spongy castle is bouncy castle equivalent for android made by Roberto Tyley - https://github.com/rtyley)
When I display provider and algorithm, it shows: Crypto version 1.0 SHA1PRNG
What surprises me is that the provider isn't Spongycastle even if it is installed as the first provider in the code. I'd like to ask you a) Isn't SecureRandom implemented in Spongy Castle (or Bouncy Castle). b) What "Crypto version 1.0" exactly is (I mean is it Sun JCE provider or what?)
Thanks...
Rubi
| Bouncy Castle does provide a set of Pseudo Random Number Generators (PRNGs). There are many names for PRNG's; NIST calls them Deterministic Random Bit Generators (DRBGs). They are however only available in the "Lightweight" API of Bouncy Castle, in the package org.bouncycastle.crypto.prng.
However, Bouncy Castle is a software-only implementation of cryptographic algorithms. This means that it doesn't contain a source for entropy. Entropy cannot be generated by software alone as software algorithms themselves are deterministic. So even if the Bouncy Castle provider would register some of the generators in its "BC" provider (or Spongy provider for Android) then it would still have to rely on the same entropy source as the platform SecureRandom implementation.
As the entropy source is likely the culprit for most performance issues, you should not expect wonders of Bouncy Castle with regards to random number generation efficiency.
Currently (v1.54) the Bouncy Castle provider doesn't register any SecureRandom implementations at all, so there's that.
| Bouncy Castle | 10,259,780 | 10 |
Here is my implementation of a AES 256 encrypt and decrypt, developed with the native library of JDK 5:
public static String encrypt(String key, String toEncrypt) throws Exception {
Key skeySpec = generateKeySpec(key);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
byte[] encryptedValue = Base64.encodeBase64(encrypted);
return new String(encryptedValue);
}
public static String decrypt(String key, String encrypted) throws Exception {
Key skeySpec = generateKeySpec(key);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decodedBytes = Base64.decodeBase64(encrypted.getBytes());
byte[] original = cipher.doFinal(decodedBytes);
return new String(original);
}
I want to implement the same methods with the Boucy Castle API (Java): I've searched a lot, tested a lot, without results ... can someone help me?
Thanks
| You would either use
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES", "BC");
or else
Cipher cipher = Cipher.getInstance("AES", new BouncyCastleProvider());
That said, Cipher.getInstance("AES") uses Electronic Codebook, which is insecure. You either want Cipher Block Chaining (Cipher.getInstance("AES/CBC/PKCS5Padding")) or Counter (Cipher.getInstance("AES/CTR/NoPadding")) modes; they are both secure, the primary difference being that CBC requires padding while CTR does not.
| Bouncy Castle | 15,925,029 | 10 |
I need to export and import generated certificates with private keys to and from byte arrays, and I don't have any problems unless I use .NET framework 4.0 and 4.5. I'm generating self-signed certificates with BouncyCastle library and then converting them to .NET format (X509Certificate2 object). Unfortunately with the upgrade to a newest framework I cannot export private keys. Here is the code:
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
namespace X509CertificateExport
{
class Program
{
static void Main(string[] args)
{
var certificate = Generate();
var exported = certificate.Export(X509ContentType.Pfx);
var imported = new X509Certificate2(exported, (string)null, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
Console.WriteLine("Certificate has private key: " + imported.HasPrivateKey);
Console.ReadKey();
}
public static X509Certificate2 Generate()
{
var keyPairGenerator = new RsaKeyPairGenerator();
var secureRandom = new SecureRandom(new CryptoApiRandomGenerator());
keyPairGenerator.Init(new KeyGenerationParameters(secureRandom, 1024));
var keyPair = keyPairGenerator.GenerateKeyPair();
var publicKey = keyPair.Public;
var privateKey = (RsaPrivateCrtKeyParameters)keyPair.Private;
var generator = new X509V3CertificateGenerator();
generator.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
generator.SetSubjectDN(new X509Name("CN=Test"));
generator.SetIssuerDN(new X509Name("CN=Test"));
generator.SetNotAfter(DateTime.Now + new TimeSpan(10, 10, 10, 10));
generator.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
generator.SetSignatureAlgorithm("MD5WithRSA");
generator.SetPublicKey(publicKey);
var newCert = generator.Generate(privateKey);
var dotNetPrivateKey = ToDotNetKey(privateKey);
var dotNetCert = new X509Certificate2(DotNetUtilities.ToX509Certificate(newCert));
dotNetCert.PrivateKey = dotNetPrivateKey;
return dotNetCert;
}
public static AsymmetricAlgorithm ToDotNetKey(RsaPrivateCrtKeyParameters privateKey)
{
var rsaProvider = new RSACryptoServiceProvider();
var parameters = new RSAParameters
{
Modulus = privateKey.Modulus.ToByteArrayUnsigned(),
P = privateKey.P.ToByteArrayUnsigned(),
Q = privateKey.Q.ToByteArrayUnsigned(),
DP = privateKey.DP.ToByteArrayUnsigned(),
DQ = privateKey.DQ.ToByteArrayUnsigned(),
InverseQ = privateKey.QInv.ToByteArrayUnsigned(),
D = privateKey.Exponent.ToByteArrayUnsigned(),
Exponent = privateKey.PublicExponent.ToByteArrayUnsigned()
};
rsaProvider.ImportParameters(parameters);
return rsaProvider;
}
}
}
After a closer look to the generated certificate I've noticed that PrivateKey.CspKeyContainerInfo.Exportable flag is true for .NET framework 3.5, but for later versions it throws:
'Exportable' threw an exception of type
'System.Security.Cryptography.CryptographicException' / Key does not exist
The only difference I see is in PrivateKey.CspKeyContainerInfo.m_parameters.Flags:
.NET 3.5 - 'NoFlags';
.NET 4.5 - 'CreateEphemeralKey'.
Documentation states that 'CreateEphemeralKey' creates a temporary key that is released when the associated RSA object is closed. It was introduced with 4.0 framework and didn't exist before. I've tried to get rid off this flag by creating CspParameters explicitly:
public static AsymmetricAlgorithm ToDotNetKey(RsaPrivateCrtKeyParameters privateKey)
{
var cspParams = new CspParameters
{
Flags = CspProviderFlags.UseMachineKeyStore
};
var rsaProvider = new RSACryptoServiceProvider(cspParams);
// ...
but with no luck. 'CreateEphemeralKey' is added anyway, so I'm getting as a result UseMachineKeyStore | CreateEphemeralKey flags and I don't see how I can remove it. Is there a way I can ignore this flag and export the certificate with private key normally?
| I haven't noticed that CspKeyContainerInfo.CspParameters.KeyContainerName is empty after key creation in .NET 4.0 and .NET 4.5, but it was autogenerated in .NET 3.5. I've set a unique name for container and now I'm able to export the private key.
public static AsymmetricAlgorithm ToDotNetKey(RsaPrivateCrtKeyParameters privateKey)
{
var cspParams = new CspParameters
{
KeyContainerName = Guid.NewGuid().ToString(),
KeyNumber = (int)KeyNumber.Exchange,
Flags = CspProviderFlags.UseMachineKeyStore
};
var rsaProvider = new RSACryptoServiceProvider(cspParams);
// ...
| Bouncy Castle | 16,419,911 | 10 |
We have an application that uses Bouncy Castle to encrypt data using PBEWITHSHA256AND128BITAES-CBC-BC algorithm. It works fine on Ubuntu running OpenJDK 1.7. But when when we move it to RedHat 6.4 also running OpenJDK 1.7, we get the following exception:
java.security.NoSuchAlgorithmException
Any thoughts on what could be causing this. How can we add PBEWITHSHA256AND128BITAES-CBC-BC algorithm to RedHat 6.4?
p.s. the application is running in JBoss.
private String cryptoAlgorithm = "PBEWITHSHA256AND128BITAES-CBC-BC";
Security.addProvider(new BouncyCastleProvider());
// load passPhrase from configured external file to char array.
char[] passPhrase = null;
try {
passPhrase = loadPassPhrase(passPhraseFile);
} catch (FileNotFoundException e) {
throw BeanHelper.logException(LOG, methodName, new EJBException("The file not found: " + passPhraseFile, e));
} catch (IOException e) {
throw BeanHelper.logException(LOG, methodName, new EJBException("Error in reading file: " + passPhraseFile, e));
}
PBEKeySpec pbeKeySpec = new PBEKeySpec(passPhrase);
try {
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(cryptoAlgorithm);
SecretKey newSecretKey = secretKeyFactory.generateSecret(pbeKeySpec);
return newSecretKey;
} catch (NoSuchAlgorithmException e) {
throw BeanHelper.logException(LOG, methodName, new EJBException("The algorithm is not found: " + cryptoAlgorithm, e));
} catch (InvalidKeySpecException e) {
throw BeanHelper.logException(LOG, methodName, new EJBException("The key spec is invalid", e));
}
(On RH 6.4)
#java -version
java version "1.7.0_19"
OpenJDK Runtime Environment (rhel-2.3.9.1.el6_4-x86_64)
OpenJDK 64-Bit Server VM (build 23.7-b01, mixed mode)
(On Ubuntu 12.04)
#java version "1.7.0_15"
OpenJDK Runtime Environment (IcedTea7 2.3.7) (7u15-2.3.7-0ubuntu1~12.04)
OpenJDK 64-Bit Server VM (build 23.7-b01, mixed mode)
| Do you have the BouncyCastle provider JAR (e.g. bcprov-jdk15on-149.jar) in your classpath?
I tested your scenario with a minimal CentOS 6.4 (64-bit) installation, OpenJDK 1.7 and BouncyCastle 1.49, and found no issues with it.
I placed the JAR in the JRE lib/ext directory:
/usr/lib/jvm/java-1.7.0-openjdk.x86_64/jre/lib/ext
| Bouncy Castle | 16,857,723 | 10 |
I am trying to implement ECDSA (Elliptic Curve Digital Signature Algorithm) but I couldn't find any examples in Java which use Bouncy Castle. I created the keys, but I really don't know what kind of functions I should use to create a signature and verify it.
public static KeyPair GenerateKeys()
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException
{
ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("B-571");
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
g.initialize(ecSpec, new SecureRandom());
return g.generateKeyPair();
}
| owlstead is correct. And to elaborate a bit more, you can do this:
KeyPair pair = GenerateKeys();
Signature ecdsaSign = Signature.getInstance("SHA256withECDSA", "BC");
ecdsaSign.initSign(pair.getPrivate());
ecdsaSign.update(plaintext.getBytes("UTF-8"));
byte[] signature = ecdsaSign.sign();
And to verify:
Signature ecdsaVerify = Signature.getInstance("SHA256withECDSA", "BC");
ecdsaVerify.initVerify(pair.getPublic());
ecdsaVerify.update(plaintext.getBytes("UTF-8"));
boolean result = ecdsaVerify.verify(signature);
| Bouncy Castle | 18,244,630 | 10 |
I wanted to code from this answer but i have error The import org.bouncycastle.openssl cannot be resolved The import org.bouncycastle.openssl cannot be resolved and i have no idea how coudl i repair this becouse other bouncycastle libs are detected correctly.
I will be grateful for any ideas whats wrong. Im using eclipse and i have instaled bouncycastle like in this instruction itcsoultions
| In addition to the provider (a.k.a. bcprov) and lightweight API, you also need the PKIX API, which provides the openssl package.
Either download bcpkix-jdk15on-150.jar from BC downloads page (direct link) and drop it in the same directory of bcprov or add it to your maven dependencies with its coordinates:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.50</version>
</dependency>
| Bouncy Castle | 24,161,146 | 10 |
I'm working on a Java program to decrypt a TLS 1.2 Session which is using the TLS_RSA_WITH_AES_128_GCM_SHA256 cipher. I recorded a test session using wireshark. The Master Secret is known.
No. Time Protocol Length Info
4 0.000124000 TLSv1.2 166 Client Hello
6 0.000202000 TLSv1.2 1074 Server Hello, Certificate, Server Hello Done
8 0.001071000 TLSv1.2 393 Client Key Exchange, Change Cipher Spec, Finished
9 0.003714000 TLSv1.2 301 New Session Ticket, Change Cipher Spec, Finished
11 6.443056000 TLSv1.2 116 Application Data
12 6.443245000 TLSv1.2 765 Application Data
15 6.443390000 TLSv1.2 103 Alert (Level: Warning, Description: Close Notify)
Packet 11 Contains a HTTP GET Request that I'm trying to decrypt.
Handshake Data:
Cipher: TLS_RSA_WITH_AES_128_GCM_SHA256
Client Random: 375f5632ba9075b88dd83eeeed4adb427d4011298efb79fb2bf78f4a4b7d9d95
Server Random: 5a1b3957e3bd1644e7083e25c64f137ed2803b680e43395a82e5b302b64ba763
Master Secret: 2FB179AB70CD4CA2C1285B4B1E294F8F44B7E8DA26B62D00EE35181575EAB04C
4FA11C0DA3ABABB4AF8D09ACB4CCC3CD
Packet 11 Data:
Direction is Client -> Server.
Secure Sockets Layer
TLSv1.2 Record Layer: Application Data Protocol: Application Data
Content Type: Application Data (23)
Version: TLS 1.2 (0x0303)
Length: 45
Encrypted Application Data: c91de005e2ae50a8a57abee55c183667b136343feef4a387cb7cf83030a47e230af268378c4f33c8b5bab3d26d
What I have done so far:
Key Derivation:
I only need Client keys here, as I want to decrypt a Client->Server package. I expanded server and client keys and IVs as per RFC.
Client Write Key: 4B119DFBFC930ABE130030BD53C3BF78
Client Write IV: 2029CAE2
Nonce:
I create AES-GCM nonce from salt (=Client Write IV) and explicit nonce (=first 8 Byte of encrypted data).
Salt: 2029CAE2
explicitNonce: C91DE005E2AE50A8
Nonce: 2029CAE2C91DE005E2AE50A8
Additional Authentication Data (AAD):
This is where I apparently got stuck. The RFC5246 says:
additional_data = seq_num + TLSCompressed.type +
TLSCompressed.version + TLSCompressed.length;
where "+" denotes concatenation.
So I made this:
byte[] aad = {0, 0, 0, 0, 0, 0, 0, 1, // seq_no uint64
0x17, // type 0x17 = Application Data
0x03, 0x03, // TLS Version 1.2
0, 45}; // 45 Bytes of encrypted data
I think seq_no is 1. It gets reset to zero, when Change Cipher Spec record is sent. (Packet #8) Then the encrypted Finished record has seq_no = 0. And the next client packet is our Packet #11 with seq_no = 1.
Code:
Now I'm feeding everything into BouncyCastle:
AEADParameters parameters = new AEADParameters(new KeyParameter(clientWriteKey), 128, nonce, aad);
GCMBlockCipher gcmBlockCipher = new GCMBlockCipher(new AESFastEngine());
gcmBlockCipher.init(false, parameters);
byte[] plainText = new byte[gcmBlockCipher.getOutputSize(cipherText.length)];
try {
int decLen = gcmBlockCipher.processBytes(cipherText, 0, cipherText.length, plainText, 0);
decLen += gcmBlockCipher.doFinal(plainText, decLen);
} catch (InvalidCipherTextException e) {
System.out.println("MAC failed: " + e.getMessage());
}
This always throws MAC failed: mac check in GCM failed. BUT the decrypted output is correct:
byte[] decomp = decompress(plainText);
System.out.println(new String(decomp, "UTF-8"));
This prints GET / HTTP/1.0\n.
Decompress helper:
public static byte[] decompress(byte[] data) throws IOException, DataFormatException {
Inflater inflater = new Inflater(true);
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
while (inflater.getRemaining() > 0) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
byte[] output = outputStream.toByteArray();
inflater.end();
return output;
}
Conclusion:
As the decrypted output is correct, i can safely assume that key derivation and decryption are working fine. Only authentication fails. So I think maybe I'm doing something wrong with the Additional Authentication Data (AAD).
So this question boils down to:
How are the Additional Authentication Data (AAD) correctly assembled?
Thank you!
| GCM mode computes MAC from message, associated data and public nonce, you covered it very well.
I think you are using wrong length, it should be plaintext length before encrypting and appending MAC. Try 45 - 8 (explicit nonce) - 16 (MAC) = 21.
| Bouncy Castle | 28,198,379 | 10 |
I created public and private PGP keys using org.bouncycastle.openpgp.PGPKeyRingGenerator. After making a change suggested by GregS, the public key is a .asc file, and the private key is a .skr file. I need to distribute the public key at first to Thunderbird users, and then later to users of Outlook and other email clients. I read these instructions for receiving a public key in thunderbird, but the instructions merely specify a .asc extension without specifying the contents/structure of the .asc file.
How do set things up so that my (modified?) code below creates a public key that can be used by remote users of Thunderbird to send encrypted emails which can then be decrypted by my private key, also created by the (modified?) code below? The accepted answer will include step by step instructions, not only for making any necessary changes to the code below, but also for setting up each remote Thunderbird user to utilize the below-generated-public-key to send emails which can be decrypted by the private key in my app, created by the (modified?) code below.
Here is my first draft of the key-generating code:
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Date;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.bcpg.HashAlgorithmTags;
import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags;
import org.bouncycastle.bcpg.sig.Features;
import org.bouncycastle.bcpg.sig.KeyFlags;
import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.openpgp.PGPEncryptedData;
import org.bouncycastle.openpgp.PGPKeyPair;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPKeyRingGenerator;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator;
import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor;
import org.bouncycastle.openpgp.operator.PGPDigestCalculator;
import org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyEncryptorBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider;
import org.bouncycastle.openpgp.operator.bc.BcPGPKeyPair;
public class RSAGen {
public static void main(String args[]) throws Exception {
char pass[] = {'h', 'e', 'l', 'l', 'o'};
PGPKeyRingGenerator krgen = generateKeyRingGenerator("alice@example.com", pass);
// Generate public key ring, dump to file.
PGPPublicKeyRing pkr = krgen.generatePublicKeyRing();
ArmoredOutputStream pubout = new ArmoredOutputStream(new BufferedOutputStream(new FileOutputStream("/home/user/dummy.asc")));
pkr.encode(pubout);
pubout.close();
// Generate private key, dump to file.
PGPSecretKeyRing skr = krgen.generateSecretKeyRing();
BufferedOutputStream secout = new BufferedOutputStream(new FileOutputStream("/home/user/dummy.skr"));
skr.encode(secout);
secout.close();
}
public final static PGPKeyRingGenerator generateKeyRingGenerator(String id, char[] pass) throws Exception{
return generateKeyRingGenerator(id, pass, 0xc0);
}
// Note: s2kcount is a number between 0 and 0xff that controls the number of times to iterate the password hash before use. More
// iterations are useful against offline attacks, as it takes more time to check each password. The actual number of iterations is
// rather complex, and also depends on the hash function in use. Refer to Section 3.7.1.3 in rfc4880.txt. Bigger numbers give
// you more iterations. As a rough rule of thumb, when using SHA256 as the hashing function, 0x10 gives you about 64
// iterations, 0x20 about 128, 0x30 about 256 and so on till 0xf0, or about 1 million iterations. The maximum you can go to is
// 0xff, or about 2 million iterations. I'll use 0xc0 as a default -- about 130,000 iterations.
public final static PGPKeyRingGenerator generateKeyRingGenerator(String id, char[] pass, int s2kcount) throws Exception {
// This object generates individual key-pairs.
RSAKeyPairGenerator kpg = new RSAKeyPairGenerator();
// Boilerplate RSA parameters, no need to change anything
// except for the RSA key-size (2048). You can use whatever key-size makes sense for you -- 4096, etc.
kpg.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), new SecureRandom(), 2048, 12));
// First create the master (signing) key with the generator.
PGPKeyPair rsakp_sign = new BcPGPKeyPair(PGPPublicKey.RSA_SIGN, kpg.generateKeyPair(), new Date());
// Then an encryption subkey.
PGPKeyPair rsakp_enc = new BcPGPKeyPair(PGPPublicKey.RSA_ENCRYPT, kpg.generateKeyPair(), new Date());
// Add a self-signature on the id
PGPSignatureSubpacketGenerator signhashgen = new PGPSignatureSubpacketGenerator();
// Add signed metadata on the signature.
// 1) Declare its purpose
signhashgen.setKeyFlags(false, KeyFlags.SIGN_DATA|KeyFlags.CERTIFY_OTHER);
// 2) Set preferences for secondary crypto algorithms to use when sending messages to this key.
signhashgen.setPreferredSymmetricAlgorithms
(false, new int[] {
SymmetricKeyAlgorithmTags.AES_256,
SymmetricKeyAlgorithmTags.AES_192,
SymmetricKeyAlgorithmTags.AES_128
});
signhashgen.setPreferredHashAlgorithms
(false, new int[] {
HashAlgorithmTags.SHA256,
HashAlgorithmTags.SHA1,
HashAlgorithmTags.SHA384,
HashAlgorithmTags.SHA512,
HashAlgorithmTags.SHA224,
});
// 3) Request senders add additional checksums to the message (useful when verifying unsigned messages.)
signhashgen.setFeature(false, Features.FEATURE_MODIFICATION_DETECTION);
// Create a signature on the encryption subkey.
PGPSignatureSubpacketGenerator enchashgen = new PGPSignatureSubpacketGenerator();
// Add metadata to declare its purpose
enchashgen.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS|KeyFlags.ENCRYPT_STORAGE);
// Objects used to encrypt the secret key.
PGPDigestCalculator sha1Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1);
PGPDigestCalculator sha256Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA256);
// bcpg 1.48 exposes this API that includes s2kcount. Earlier versions use a default of 0x60.
PBESecretKeyEncryptor pske = (new BcPBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha256Calc, s2kcount)).build(pass);
// Finally, create the keyring itself. The constructor takes parameters that allow it to generate the self signature.
PGPKeyRingGenerator keyRingGen =
new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, rsakp_sign,
id, sha1Calc, signhashgen.generate(), null,
new BcPGPContentSignerBuilder(rsakp_sign.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1), pske);
// Add our encryption subkey, together with its signature.
keyRingGen.addSubKey(rsakp_enc, enchashgen.generate(), null);
return keyRingGen;
}
}
When I run the code above to generate the .asc file, and then try to import the .asc file into Thunderbird, I get the following error screen:
Note that I did not install GnuPG on my CentOS 7 machine.
Also, you can recreate this problem on your own machine easily because Thunderbird is free. You can download thunderbird for free using this link. Alternatively, on my CentOS 7 machine, I downloaded Thunderbird with yum install thunderbird. You can download bouncy castle by adding the following to your pom.xml:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpg-jdk15on</artifactId>
<version>1.51</version>
</dependency>
EDIT#1:
To address JRichardSnape's questions, I found that maven must also be automatically downloading the org.bouncycastle.crypto library because it is a dependency of bcpg-jdk15on. JRichardSnape is correct that RSAKeyGenerationParameters and RSAKeyPairGenerator are not in the bcpg-jdk15on.jar manual download. (Note: the versions in the links may not be current.) However, both classes are in the automated maven download that results from the single dependency snippet from pom.xml shown above. I say this because there are no other bouncycastle dependencies in my pom.xml. I am using Java 7.
Eclipse describes the two classes imported as:
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
I added all of the import statements from RSAGen.java to the code segment in my OP above. I think the problem might to do with the need for a name/signature for the key.
Googling this error results in the following links, among others:
Convert userId to UTF8 before generating signature #96
non-ascii characters in Name field #92
Unable to import PGP certificate into Keychain
EDIT#2
As per @JRichardSnape's advice, I tried Enigmail->Key management ->File ->Import keys from file. This resulted in the following dialog box, which seems to indicate that, while the key was imported, the key was not signed. Thus, it seems that there is no name or no email address associated with the .asc file that was imported. The key also does not show up in EnigMail's list of keys afterwards.
EDIT#3
Using gpg --gen-key, I was able to get the CentOS 7 terminal to create a keypair, including a public key, which I was able to successfully import into Thunderbird, so that Thunderbird can now associate the terminal-gpg-generated public key with the intended email recipient. But when I take all the steps to send an encrypted email from Thunderbird using the public key, the email and its attachments nonetheless arrive unencrypted. The steps I took to send encrypted email with the public key from remote Thunderbird to the server that has the private key are described in this SuperUser posting.
Given that gpg --gen-key seems to work, the major remaining problem at the moment, seems to be the Thunderbird part of this bounty question. I have posted a lot of progress towards solving the Thunderbird part in the SuperUser question in the preceding paragraph. Your help answering it would go a long way towards answering this question as well.
EDIT#4
I am still not able to get the BouncyCastle-created key to import into Thunderbird. However, when I use keys created on the CentOS 7 terminal using gpg --gen-key, I am able to complete the following steps:
1.) I configured my Thunderbird to manage another (second)
email account I have not been using.
2.) I then created a gpg key for that second account and
configured encryption for that second account in Thunderbird.
3.) I sent an encrypted email containing an attachment from the
first Thunderbird account to the second Thunderbird account.
4.) I was able to see that the attachment remained encrypted in
the second account's inbox until I used the recipient key's
passphrase to decrypt it.
My CentOS 7 server is still producing un-encrypted attachments when I send an email to it from the same "first" Thunderbird account as described in this edit. I am trying to determine whether this is due to some "auto-decryption" in dovecot/postfix/mailx/gpg in the CentOS 7 server, or whether it is due to some settings in the Thunderbird sender. I am researching this.
| I'll try to address these points one by one:
Java bouncycastle keyring generation
The Java code does work and produces a usable keyring pair. I have tested it with different emails and different pass codes with no problems. I have had a 3rd party send me an email using the public key and successfully decrypted it with the private key both generated by this Java code. The key has worked with the following combinations
Thunderbird (31.4.0) + Enigmail (1.7.2) + gpg (Gpg4win) on Windows 8
Thunderbird + Enigmail on ubuntu 14.10 (with the xfer desktop manager)
however
The OP finds a problem importing the keys with a failure implying there is no user ID in a CentOS / Thunderbird / pgp combination. Similarly, it has failed to be imported with an error saying no User ID on Windows / Outlook / Kleopatra plugin (tested although the question specifically cites Thunderbird).
I am unable to reproduce the error - strongly suspect it is due to either configuration differences or version differences in GNU PG. My setup shows the following for gpg --version
gpg (GnuPG) 2.0.26 (Gpg4win 2.2.3)
libgcrypt 1.6.2
Testing Java generated key with gpg directly
You can generate the keys with your java code, go to command line and execute
gpg --import dummy.asc
Then test is by executing
gpg --edit-key alice@example.com
check it has a user id by typing check at the gpg> prompt. Sample output:
uid alice@example.com
sig!3 14AEE94A 2015-02-05 [self-signature]
If this works - you have eliminated a gpg problem with your key import - check the Thunderbird / Enigmail versions.
Using Thunderbird
It seems that the majority of issues have been solved by my comment recommending key import via Enigmail->Key management ->File ->Import keys from file in combination with this related question from the OP on superuser.
Note also - there is a "generate" option in Key Management dialogue for Enigmail. If the Java generation is not required, this can be used to generate key pairs - it is basically the same as generating directly via gpg to the best of my knowledge.
The remaining issue with use of Thunderbird appears to be a lack of confidence in the encryption as the message appears in plain text on the OP's server (it appears that the key is to be used in a server/client combination where clients send encrypted emails to a server).
To gain confidence that the message is indeed being encrypted - I suggest altering an Enigmail setting:
Enigmail -> Preference -> Sending tab
select "Manual encryption settings"
select "Always" in the "confirm before sending" box
You will then see the encrypted mail along with a confimation box before it is sent.
I can't speak as to how to stop your server automatically decrypting incoming mail, as it depends on your server configuration and would be better asked as a separate question, quite possibly on either superuser or serverfault StackExchange sites.
Testing PGP email
You might also consider following the advice from the Enigmail tutorial and sending an encrypted mail to
Adele, the "Friendly OpenPGP Email Robot". Adele accepts OpenPGP
messages and replies in an explanatory way to any kind of OpenPGP
messages.
The address is adele <at> gnupp <dot> de
| Bouncy Castle | 28,245,669 | 10 |
How can one decompile Android DEX (VM bytecode) files into corresponding Java source code?
| It's easy
Get these tools:
dex2jar to translate dex files to jar files
jd-gui to view the java files in the jar
The source code is quite readable as dex2jar makes some optimizations.
Procedure:
And here's the procedure on how to decompile:
Step 1:
Convert classes.dex in test_apk-debug.apk to test_apk-debug_dex2jar.jar
d2j-dex2jar.sh -f -o output_jar.jar apk_to_decompile.apk
d2j-dex2jar.sh -f -o output_jar.jar dex_to_decompile.dex
Note 1: In the Windows machines all the .sh scripts are replaced by .bat scripts
Note 2: On linux/mac don't forget about sh or bash. The full command should be:
sh d2j-dex2jar.sh -f -o output_jar.jar apk_to_decompile.apk
Note 3: Also, remember to add execute permission to dex2jar-X.X directory e.g. sudo chmod -R +x dex2jar-2.0
dex2jar documentation
Step 2:
Open the jar in JD-GUI
| Dex | 1,249,973 | 782 |
Since updating to ADT 14 I can no longer build my project. It was building fine prior to updating.
The error:
[2011-10-23 16:23:29 - Dex Loader] Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;
[2011-10-23 16:23:29 - myProj] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;
Similar issues have been reported and I have tried the suggestions there including
Restarting Eclipse.
Cleaning the project and rebuild - Disable "Project->Build Automatically" option, then "Clean" and "Build" project, then try to run. reset "Build Automatically" option to On
Re-installing the Android Developer Tools
Re-installing Eclipse (updated to the latest version 3.7.1)
Created a new project importing from the file system
Created a new project from subversion.
| I had the same problem, quite weird because it was happening only when using Eclipse (but it was OK with Ant).
This is how I fixed it:
Right click on the Project Name
Select Build Path -> Configure Build Path
In Java Build Path, go to the tab Order and Export
Uncheck your .jar library
Only sometimes:
In Order and Export tab I did not have any jar library there, so I have unchecked Android Private Libraries item. Now my project is running.
| Dex | 7,870,265 | 398 |
I have seen various versions of the dex erros before, but this one is new. clean/restart etc won't help. Library projects seems intact and dependency seems to be linked correctly.
Unable to execute dex: method ID not in [0, 0xffff]: 65536
Conversion to Dalvik format failed: Unable to execute dex: method ID not in [0, 0xffff]: 65536
or
Cannot merge new index 65950 into a non-jumbo instruction
or
java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
tl;dr: Official solution from Google is finally here!
http://developer.android.com/tools/building/multidex.html
Only one small tip, you will likely need to do this to prevent out of memory when doing dex-ing.
dexOptions {
javaMaxHeapSize "4g"
}
There's also a jumbo mode that can fix this in a less reliable way:
dexOptions {
jumboMode true
}
Update: If your app is fat and you have too many methods inside your main app, you may need to re-org your app as per
http://blog.osom.info/2014/12/too-many-methods-in-main-dex.html
| Update 3 (11/3/2014)
Google finally released official description.
Update 2 (10/31/2014)
Gradle plugin v0.14.0 for Android adds support for multi-dex. To enable, you just have to declare it in build.gradle:
android {
defaultConfig {
...
multiDexEnabled true
}
}
If your application supports Android prior to 5.0 (that is, if your minSdkVersion is 20 or below) you also have to dynamically patch the application ClassLoader, so it will be able to load classes from secondary dexes. Fortunately, there's a library that does that for you. Add it to your app's dependencies:
dependencies {
...
compile 'com.android.support:multidex:1.0.0'
}
You need to call the ClassLoader patch code as soon as possible. MultiDexApplication class's documentation suggests three ways to do that (pick one of them, one that's most convenient for you):
1 - Declare MultiDexApplication class as the application in your AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.multidex.myapplication">
<application
...
android:name="android.support.multidex.MultiDexApplication">
...
</application>
</manifest>
2 - Have your Application class extend MultiDexApplication class:
public class MyApplication extends MultiDexApplication { .. }
3 - Call MultiDex#install from your Application#attachBaseContext method:
public class MyApplication {
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
....
}
....
}
Update 1 (10/17/2014):
As anticipated, multidex support is shipped in revision 21 of Android Support Library. You can find the android-support-multidex.jar in /sdk/extras/android/support/multidex/library/libs folder.
Multi-dex support solves this problem. dx 1.8 already allows generating several dex files.
Android L will support multi-dex natively, and next revision of support library is going to cover older releases back to API 4.
It was stated in this Android Developers Backstage podcast episode by Anwar Ghuloum. I've posted a transcript (and general multi-dex explanation) of the relevant part.
| Dex | 15,209,831 | 346 |
I have Android Studio Beta. I created a new project with compile my old modules but when I tried launching the app it did not launch with the message:
Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
But I don't know how to solve this error. I googled this for hours but with no success.
My project gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-beta6'
classpath "io.realm:realm-gradle-plugin:3.7.1"
classpath 'com.google.gms:google-services:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
My app gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "parad0x.sk.onlyforyou"
minSdkVersion 21
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
}
}
compileOptions {
targetCompatibility 1.7
sourceCompatibility 1.7
}
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/NOTICE'
}
lintOptions {
checkReleaseBuilds false
}
productFlavors {
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
//noinspection GradleCompatible
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
compile project(path: ':loginregisterview')
}
And my module gradle:
apply plugin: 'com.android.library'
apply plugin: 'realm-android'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.0.2'
compile 'com.android.support:support-v4:26.1.0'
compile 'com.github.bumptech.glide:glide:4.0.0'
testCompile 'junit:junit:4.12'
compile project(path: ':parser')
}
My second module:
apply plugin: 'com.android.library'
apply plugin: 'realm-android'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
realm {
syncEnabled = true
}
useLibrary 'org.apache.http.legacy'
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile 'junit:junit:4.12'
// compile 'com.android.support:appcompat-v7:23.1.0'
// compile 'com.fasterxml.jackson.core:jackson-core:2.9.0'
// compile 'com.fasterxml.jackson.core:jackson-annotations:2.9.0'
// compile 'com.fasterxml.jackson.core:jackson-databind:2.9.0'
compile 'com.google.code.gson:gson:2.6.2'
}
____________finding_________
When I did not import the second module (parser) the app did not crash on dex but when the module was not imported app did not work. :D :D
| I tried all the above and none of them helps. finally, I find this work for me:
app/build.gradle:
android {
defaultConfig {
multiDexEnabled true
}
}
| Dex | 46,267,621 | 325 |
I have some questions regarding dex files
What is a dex file in Android?
How does dex work for Android?
How are they used in debugging an Android app?
Are they similar to java class files?
I need specific information please help on this and any real examples are welcome!
| About the .dex File:
One of the most remarkable features of the Dalvik Virtual Machine (the workhorse under the Android system) is that it does not use Java bytecode. Instead, a homegrown format called DEX was introduced and not even the bytecode instructions are the same as Java bytecode instructions.
Compiled Android application code file
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created by automatically translating compiled applications written in the Java programming language.
Dex file format:
File Header
String Table
Class List
Field Table
Method Table
Class Definition Table
Field List
Method List
Code Header
Local Variable List
Android has documentation on the Dalvik Executable Format (.dex files). You can find out more over at the official docs: Dex File Format
.dex files are similar to java class files, but they were run under the Dalvik Virtual Machine (DVM) on older Android versions, and compiled at install time on the device to native code with ART on newer Android versions.
You can decompile .dex using the dexdump tool which is provided in android-sdk.
There are also some Reverse Engineering Techniques to make a jar file or java class file from a .dex file.
| Dex | 7,750,448 | 235 |
When compiling a specific Android project, and only on my Windows machine, I get a java.nio.BufferOverflowException during from dex. The problem occurs both when using Eclipse and when using Ant.
The output when using Ant is:
...
[dex] Pre-Dexing C:\MyProject\libs\android-support-v4.jar -> android-support-v4-5f5341d3c1b10a79d7d93f9c1e64421e.jar
[dex] Converting compiled files and external libraries into C:\MyProject\bin\classes.dex...
[dx]
[dx] UNEXPECTED TOP-LEVEL EXCEPTION:
[dx] java.nio.BufferOverflowException
[dx] at java.nio.Buffer.nextPutIndex(Buffer.java:499)
[dx] at java.nio.HeapByteBuffer.putShort(HeapByteBuffer.java:296)
[dx] at com.android.dex.Dex$Section.writeShort(Dex.java:818)
[dx] at com.android.dex.Dex$Section.writeTypeList(Dex.java:870)
[dx] at com.android.dx.merge.DexMerger$3.write(DexMerger.java:437)
[dx] at com.android.dx.merge.DexMerger$3.write(DexMerger.java:423)
[dx] at com.android.dx.merge.DexMerger$IdMerger.mergeUnsorted(DexMerger.java:317)
[dx] at com.android.dx.merge.DexMerger.mergeTypeLists(DexMerger.java:423)
[dx] at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:163)
[dx] at com.android.dx.merge.DexMerger.merge(DexMerger.java:187)
[dx] at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439)
[dx] at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287)
[dx] at com.android.dx.command.dexer.Main.run(Main.java:230)
[dx] at com.android.dx.command.dexer.Main.main(Main.java:199)
[dx] at com.android.dx.command.Main.main(Main.java:103)
BUILD FAILED
C:\Users\Jaap\android-sdks\tools\ant\build.xml:892: The following error occurred while executing this line:
C:\Users\Jaap\android-sdks\tools\ant\build.xml:894: The following error occurred while executing this line:
C:\Users\Jaap\android-sdks\tools\ant\build.xml:906: The following error occurred while executing this line:
C:\Users\Jaap\android-sdks\tools\ant\build.xml:284: null returned: 2
When using Eclipse the message is shorter but similar:
[2013-11-01 14:29:44] APK file is not created for Project:
[2013-11-01 14:29:46 - Dex Loader] Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.
[2013-11-01 14:29:46 - MyProject] Conversion to Dalvik format failed: Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.
Like I said, I don't have this problem on my MacBook, even though they are both upgraded to the latest versions of the Android Build tools: 19.0.0.
| No need to downgrade the build tools back to 18.1.11, this issue is fixed with build tools 19.0.1.
If you can't use 19.0.1 for some reason then:
Make sure that the value of android:targetSdkVersion in AndroidManifest.xml matches target=android-<value> in project.properties. If these two values are not the same, building with build tools version 19.0.0 will end in the BufferOverflowException. Source
There is also some indication from comments on this post that you need to target at least 19 (android-19). Please leave a comment if this solution also works if your target is < 19.
This is how the fix looks for my project. The related AOSP issue is #61710.
1 If you really need to downgrade, you don't need to uninstall build tools 19.0.0, simply install 18.1.1 and add sdk.buildtools=18.1.1 to the local.properties file.
| Dex | 19,727,915 | 174 |
Are the users able to convert the apk file of my application back to the actual code?
If they do - is there any way to prevent this?
| First, an apk file is just a modified jar file. So the real question is can they decompile the dex files inside. The answer is sort of. There are already disassemblers, such as dedexer and smali. You can expect these to only get better, and theoretically it should eventually be possible to decompile to actual Java source (at least sometimes). See the previous question decompiling DEX into Java sourcecode.
What you should remember is obfuscation never works. Choose a good license and do your best to enforce it through the law. Don't waste time with unreliable technical measures.
| Dex | 3,122,635 | 95 |
I don't know why but it's impossible to launch my app on my mobile this morning. I get this error message:
Cannot fit requested classes in a single dex file. Try supplying a
main-dex list.
# methods: 68061 > 65536 Message{kind=ERROR, text=Cannot fit requested classes in a single dex file. Try supplying a main-dex list.
# methods: 68061 > 65536, sources=[Unknown source file], tool
I'm really new to Android and I don't understand the problem and what I need to do? And why I get this problem now and not before?
| In root build.gradle file do something like:
dependencies {
// ...
implementation 'androidx.multidex:multidex:2.0.1'
}
android {
defaultConfig {
// ...
multiDexEnabled true
}
}
More details here: Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536
| Dex | 51,341,627 | 95 |
I have a rather large Android app that relies on many library projects. The Android compiler has a limitation of 65536 methods per .dex file and I am surpassing that number.
There are basically two paths you can choose (at least that I know of) when you hit the method limit.
1) Shrink your code
2) Build multiple dex files (see this blog post)
I looked into both and tried to find out what was causing my method count to go so high. The Google Drive API takes the biggest chunk with the Guava dependency at over 12,000. Total libs for Drive API v2 reach over 23,000!
My question I guess is, what do you think I should do? Should I remove Google Drive integration as a feature of my app? Is there a way to shrink the API down (yes, I use proguard)? Should I go the multiple dex route (which looks rather painful, especially dealing with third party APIs)?
| It looks like Google has finally implementing a workaround/fix for surpassing the 65K method limit of dex files.
About the 65K Reference Limit
Android application (APK) files contain
executable bytecode files in the form of Dalvik Executable (DEX)
files, which contain the compiled code used to run your app. The
Dalvik Executable specification limits the total number of methods
that can be referenced within a single DEX file to 65,536, including
Android framework methods, library methods, and methods in your own
code. Getting past this limit requires that you configure your app
build process to generate more than one DEX file, known as a multidex
configuration.
Multidex support prior to Android 5.0
Versions of the platform prior to Android 5.0 use the Dalvik runtime
for executing app code. By default, Dalvik limits apps to a single
classes.dex bytecode file per APK. In order to get around this
limitation, you can use the multidex support library, which becomes
part of the primary DEX file of your app and then manages access to
the additional DEX files and the code they contain.
Multidex support for Android 5.0 and higher
Android 5.0 and higher uses a runtime called ART which natively
supports loading multiple dex files from application APK files. ART
performs pre-compilation at application install time which scans for
classes(..N).dex files and compiles them into a single .oat file for
execution by the Android device. For more information on the Android
5.0 runtime, see Introducing ART.
See: Building Apps with Over 65K Methods
Multidex Support Library
This library provides support for building
apps with multiple Dalvik Executable (DEX) files. Apps that reference
more than 65536 methods are required to use multidex configurations.
For more information about using multidex, see Building Apps with Over
65K Methods.
This library is located in the /extras/android/support/multidex/
directory after you download the Android Support Libraries. The
library does not contain user interface resources. To include it in
your application project, follow the instructions for Adding libraries
without resources.
The Gradle build script dependency identifier for this library is as
follows:
com.android.support:multidex:1.0.+ This dependency notation specifies
the release version 1.0.0 or higher.
You should still avoid hitting the 65K method limit by actively using proguard and reviewing your dependencies.
| Dex | 15,471,772 | 90 |
Actually I was trying to extract code of a .apk file called cloudfilz.apk and wanted to manipulate in its source code so I followed the steps given below:-
make a new folder and put .apk file (which you want to decode) now rename this .apk file with extension .zip (eg: rename from filename.apk to filename.apk.zip) and save it..now you get classes.dex files etc...at this stage you are able to see drawable but not XML and java file...so continue...
Step 2:
now extract this zip apk file in the same folder(in this eg or case NEW FOLDER). now download dex2jar from this link http://code.google.com/p/dex2jar/ and extract it to the same folder (in this case NEW FOLDER).....now open command prompt and reach to that folder (in this case NEW FOLDER)....after reaching write "dex2jar classes.dex" and press enter.....now you get classes.dex.dex2jar file in the same folder......
=>Question:-I was successful to achieve step 1 but in step2 when I am executing dex2jar classes.dex I am getting an error on command prompt java.lang.UnsupportedClassVersionError ,I know this is due to incompatibility between my installed JDK version and classes.dex JDK version number so stuck here and don't have way out...
| Note: All of the following instructions apply universally (aka to all OSes) unless otherwise specified.
Prerequsites
You will need:
A working Java installation
A working terminal/command prompt
A computer
An APK file
Steps
Step 1: Changing the file extension of the APK file
Change the file extension of the .apk file by either adding a .zip extension to the filename, or to change .apk to .zip.
For example, com.example.apk becomes com.example.zip, or com.example.apk.zip. Note that on Windows and macOS, it may prompt you whether you are sure you want to change the file extension. Click OK or Add if you're using macOS:
Step 2: Extracting Java files from APK
Extract the renamed APK file in a specific folder. For example, let that folder be demofolder.
If it didn't work, try opening the file in another application such as WinZip or 7-Zip.
For macOS, you can try running unzip in Terminal (available at /Applications/Terminal.app), where it takes one or more arguments: the file to unzip + optional arguments. See man unzip for documentation and arguments.
Download dex2jar (see all releases on GitHub) and extract that zip file in the same folder as stated in the previous point.
Open command prompt (or a terminal) and change your current directory to the folder created in the previous point and type the command d2j-dex2jar.bat classes.dex and press enter. This will generate classes-dex2jar.jar file in the same folder.
macOS/Linux users: Replace d2j-dex2jar.bat with d2j-dex2jar.sh. In other words, run d2j-jar2dex.sh classes.dex in the terminal and press enter.
Download Java Decompiler (see all releases on Github) and extract it and start (aka double click) the executable/application.
From the JD-GUI window, either drag and drop the generated classes-dex2jar.jar file into it, or go to File > Open File... and browse for the jar.
Next, in the menu, go to File > Save All Sources (Windows: Ctrl+Alt+S, macOS: ⌘+⌥+S). This should open a dialog asking you where to save a zip file named `classes-dex2jar.jar.src.zip" consisting of all packages and java files. (You can rename the zip file to be saved)
Extract that zip file (classes-dex2jar.jar.src.zip) and you should get all java files of the application.
Step 3: Getting xml files from APK
For more info, see the apktool website for installation instructions and more
Windows:
Download the wrapper script (optional) and the apktool jar (required) and place it in the same folder (for example, myxmlfolder).
Change your current directory to the myxmlfolder folder and rename the apktool jar file to apktool.jar.
Place the .apk file in the same folder (i.e myxmlfolder).
Open the command prompt (or terminal) and change your current directory to the folder where apktool is stored (in this case, myxmlfolder). Next, type the command apktool if framework-res.apk.
What we're doing here is that we are installing a framework. For more info, see the docs.
The above command should result in "Framework installed ..."
In the command prompt, type the command apktool d filename.apk (where filename is the name of apk file). This should decode the file. For more info, see the docs.
This should result in a folder filename.out being outputted, where filename is the original name of the apk file without the .apk file extension. In this folder are all the XML files such as layout, drawables etc.
Source: How to get source code from APK file - Comptech Blogspot
| Dex | 7,888,102 | 82 |
I'm trying the new MultiDex Support on my app and so far I've managed to compile my app correctly, but when running it, I get the following exception:
java.lang.RuntimeException: Unable to instantiate application android.support.multidex.MultiDexApplication: java.lang.ClassNotFoundException: Didn't find class "android.support.multidex.MultiDexApplication" on path: DexPathList[[zip file "/data/app/me.myapp.main-2.apk"],nativeLibraryDirectories=[/data/app-lib/me..main-2, /vendor/lib, /system/lib]]
at android.app.LoadedApk.makeApplication(LoadedApk.java:507)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4382)
at android.app.ActivityThread.access$1500(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1270)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.multidex.MultiDexApplication" on path: DexPathList[[zip file "/data/app/me.myapp.main-2.apk"],nativeLibraryDirectories=[/data/app-lib/me.myapp.main-2, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
at android.app.Instrumentation.newApplication(Instrumentation.java:998)
at android.app.LoadedApk.makeApplication(LoadedApk.java:502)
This is my gradle file:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.0"
defaultConfig {
minSdkVersion 16
targetSdkVersion 21
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
packagingOptions {
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
}
repositories {
mavenCentral()
mavenLocal()
}
dependencies {
compile 'com.android.support:multidex:1.0.0'
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:support-v4:21.0.0'
compile 'com.android.support:support-v13:21.0.0'
compile 'com.android.support:appcompat-v7:21.0.0'
}
And my AndroidManifest.xml:
<application
android:name="android.support.multidex.MultiDexApplication">
I don't understand what the problem is. I think I'm doing everything according to the documentation. Is there something else i am missing? I made sure I had the latest support library and repo installed from the SDK manager.
| The solution didn't help me because I was using jetpack version ie androidx. libraries.
Followed official doc.
And
I had to change name to androidx....Multidex.
<application
android:name="androidx.multidex.MultiDexApplication" >
...
</application>
Hope It helps other people looking for adding multidex with jetpack.
| Dex | 26,763,702 | 65 |
I am going to learn a little bit about Dalvik VM, dex and Smali.
I have read about smali, but still cannot clearly understand where its place in chain of compilers. And what its purpose.
Here some questions:
As I know, dalvik as other Virtual Machines run bytecode, in case of Android it is dex byte code.
What is smali? Does Android OS or Dalvik Vm work with it directly, or it is just the same dex bytecode but more readable for the human?
Is it something like dissasembler for Windows (like OllyDbg) program executable consist of different machines code (D3 , 5F for example) and there is appropriate assembly command to each machine code, but Dalvik Vm also is software, so smali is readable representation of bytecodes
There is new ART enviroment. Is it still use bytecodes or it executes directly native code?
Thank you in advance.
| When you create an application code, the apk file contains a .dex file, which contains binary Dalvik bytecode. This is the format that the platform actually understands. However, it's not easy to read or modify binary code, so there are tools out there to convert to and from a human readable representation. The most common human readable format is known as Smali. This is essentially the same as the dissembler you mentioned.
For example, say you have Java code that does something like
int x = 42
Assuming this is the first variable, then the dex code for the method will most likely contain the hexadecimal sequence
13 00 2A 00
If you run baksmali on it, you'd get a text file containing the line
const/16 v0, 42
Which is obviously a lot more readable then the binary code. But the platform doesn't know anything about smali, it's just a tool to make it easier to work with the bytecode.
Dalvik and ART both take .dex files containing dalvik bytecode. It's completely transparent to the application developer, the only difference is what happens behind the scenes when the application is installed and run.
| Dex | 30,837,450 | 61 |
I'm having troubles trying to compile an Android application with Gradle 0.5.+ and Android Studio, using SimpleXML.
This is the error:
Gradle: Execution failed for task ':MyApplication:dexDebug'.
> Failed to run command:
/Applications/Android Studio.app/sdk/build-tools/android-4.2.2/dx --dex --output <REALLY_LONG_STRING.....>
Error Code:
1
Output:
trouble processing "javax/xml/stream/events/StartElement.class":
Ill-advised or mistaken usage of a core class (java.* or javax.*)
when not building a core library.
This is often due to inadvertently including a core library file
in your application's project, when using an IDE (such as
Eclipse). If you are sure you're not intentionally defining a
core class, then this is the most likely explanation of what's
going on.
However, you might actually be trying to define a class in a core
namespace, the source of which you may have taken, for example,
from a non-Android virtual machine project. This will most
assuredly not work. At a minimum, it jeopardizes the
compatibility of your app with future versions of the platform.
It is also often of questionable legality.
If you really intend to build a core library -- which is only
appropriate as part of creating a full virtual machine
distribution, as opposed to compiling an application -- then use
the "--core-library" option to suppress this error message.
If you go ahead and use "--core-library" but are in fact
building an application, then be forewarned that your application
will still fail to build or run, at some point. Please be
prepared for angry customers who find, for example, that your
application ceases to function once they upgrade their operating
system. You will be to blame for this problem.
If you are legitimately using some code that happens to be in a
core package, then the easiest safe alternative you have is to
repackage that code. That is, move the classes in question into
your own package namespace. This means that they will never be in
conflict with core system classes. JarJar is a tool that may help
you in this endeavor. If you find that you cannot do this, then
that is an indication that the path you are on will ultimately
lead to pain, suffering, grief, and lamentation.
1 error; aborting
build.gradle is configured like that:
dependencies {
[...]
compile 'org.simpleframework:simple-xml:2.7.+'
}
repositories {
[...]
mavenCentral()
}
How can i solve this problem?
EDIT
The problem is not present if i install Simple-XML directly as a Jar inside libs/ - of course a maven solution would be cleaner.
| You need to also exclude stax-API.
implementation('org.simpleframework:simple-xml:2.7.+'){
exclude module: 'stax'
exclude module: 'stax-api'
exclude module: 'xpp3'
}
| Dex | 18,084,285 | 59 |
I have a .dex file, call it classes.dex.
Is there a way to "read" the contents of that classes.dex and get a list of all classes in there as full class names, including their package, com.mypackage.mysubpackage.MyClass, for exmaple?
I was thinking about com.android.dx.dex.file.DexFile, but I cannot seem to find a method for retrieving an entire set of classes.
| Use the command line tool dexdump from the Android-SDK. It's in $ANDROID_HOME/build-tools/<some_version>/dexdump. It prints a lot more info than you probably want. I didn't find a way to make dexdump less verbose, but
dexdump classes.dex | grep 'Class descriptor'
should work.
| Dex | 11,343,388 | 53 |
In an android project, build.gradle file, I have been through this line
dexOptions{
javaMaxHeapSize "4g"
}
I would like to know the exact purpose of this javaMaxHeapSize and what does that 4g means. What are other values I can give ?
| As it mentioned in the answer above, it is just an option to specify the maximum memory allocation pool for a Java Virtual Machine (JVM) for dex operation. And it's the same, as to provide to java the -xmx argument. Due to it's source codes from here, it's setter look like:
if (theJavaMaxHeapSize.matches("\\d+[kKmMgGtT]?")) {
javaMaxHeapSize = theJavaMaxHeapSize
} else {
throw new IllegalArgumentException(
"Invalid max heap size DexOption. See `man java` for valid -Xmx arguments.")
}
So, you can see, that the accepted value should match the \d+[kKmMgGtT]? pattern, and hence not, it even refers to the man java to get to know, how to set the -xmx. You can read the man page here. And it says, that this flag:
Specify the maximum size, in bytes, of the memory allocation pool. This value must a multiple of 1024 greater than 2MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is chosen at runtime based on system configuration.
In your example, 4g is 4 Gigabytes and this is a maximum heap size for dex operation.
| Dex | 33,750,404 | 51 |
I made:
In "Settings"->"Android SDK"->"SDK Tools" Google Play services is checked and installed v.46
Removed folder /.gradle
"Clean Project"
"Rebuild Project
Error is:
Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
Project build.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
classpath 'com.google.gms:google-services:3.1.0'
}
}
allprojects {
repositories {
jcenter()
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
App build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "com.asanquran.mnaum.quranasaanurdutarjuma"
minSdkVersion 15
targetSdkVersion 26
versionCode 3
versionName "1.3"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.android.gms:play-services-ads:11.4.2'
compile 'com.github.barteksc:android-pdf-viewer:2.3.0'
compile 'org.apache.commons:commons-io:1.3.2'
compile 'com.google.firebase:firebase-ads:11.4.2'
compile 'com.google.firebase:firebase-messaging:11.4.2'
compile 'com.google.firebase:firebase-storage:11.4.2'
apply plugin: 'com.google.gms.google-services'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
|
Go to <project>/app/ and open build.gradle file
Add the following line to the defaultConfig and dependencies sections
android {
...
defaultConfig {
...
multiDexEnabled true // ADD THIS LINE
}
}
...
dependencies {
...
implementation 'com.android.support:multidex:1.0.3' // ADD THIS LINE
}
| Dex | 46,977,267 | 42 |
I am getting the following error when I compile my app:
[2014-05-07 21:48:42 - Dex Loader] Unable to execute dex: Cannot merge new index 65536 into a non-jumbo instruction!
I am at the point that if I declare a new method anywhere in my package, I get this error. If I don't, the app compiles.
I would like to know what exactly (and accurately) does this error mean. My app is big, but I don't think its that big! So:
Does the error mean I have too many methods? public? static? package? members?
Is it related to the methods/members of my root package, or also to the included JAR libraries?
Is there a way to get more debug information about this?
I already know about that "jumbo" enabling flag addressed in the similar questions here in SO, however, I think jumbo mode is not available on the API level I'm targeting (ICS).
| Your error is for the amount of strings (methods, members, etc) in a single dex file.
You need to compile you app using jumbo in dex with:
dex.force.jumbo=true
in project.properties
This increment the limit for strings in a dex files. And your project will probably compile.
Also with jumbo set, the is another limit of 64K only for methods in an single dex. If you get this limit in the future , you will need to remove some dependencies.
UPDATE: for build with Gradle:
In Gradle you can enable jumboMode also in the build.gradle file with:
dexOptions {
jumboMode = true
}
Check:
Android Build: Dex Jumbo Mode in Gradle
Also with Gradle you can avoid the 64K limit for methods using multidex build, tutorial here:
https://developer.android.com/tools/building/multidex.html
| Dex | 23,527,218 | 36 |
I'm working on android app that's running up against the dex method count limit. Is there a simple way to show the method count grouped by package?
I can get the total method count, but my app has multiple components and I'm trying to figure out which component is the biggest contributor to this.
| I've written a dex-method-counts tool that outputs per-package method counts faster and more accurately than the smali-based tools referenced in JesusFreke's answer¹. It can be installed from https://github.com/mihaip/dex-method-counts.
[1] that script disassembles the .dex and re-assembles it by package, but this means that methods that are referenced by multiple packages are counted twice
| Dex | 17,094,094 | 34 |
Can i have the count of all methods used in a jar file .
My APK uses certain external JARS and there are a number of classes around hundred to be precise.
I have used decompilers like dex2jar JAD and others to name a few ,but they all seem to show methods only in particular class file.
Is there a way i can get a total count ?
| You can convert the jar to a dex file, and then pull the number of method references out of the header. It is stored as an unsigned little endian integer, at offset 88 (0x58).
dx --dex --output=temp.dex orig.jar
cat temp.dex | head -c 92 | tail -c 4 | hexdump -e '1/4 "%d\n"'
Keep in mind that this is the number of unique methods referenced, not the number of method references. In other words, if a particular method is referenced twice in the dex file, it will only be counted once in the count in the header. And when you import this jar into your apk, the method references that are common between the two are deduplicated, so the total method reference count of the final merged apk will be <= the sum of the two.
| Dex | 14,023,397 | 33 |
In Android systems or development enviroments, what are the differences between AAR, JAR, DEX, and APK files? What is the purpose of each one?
AFAIK, JAR are just like a collection of .class files (like in Java).
AAR are JAR files + resources. But what's its usage case? To be used to distribute development libraries for Android?
APK seems to be similar to packages like .deb or .rpm. Is it the only way to install applications on Android?
What about DEX files? Compiled applications... but what's the difference with a JAR or AAR file?
Moreveor, when distributing .so (i.e. native code) files for Android, what's the best way to do it?
| JAR (Java Archive)
JAR is a package file format designed for distribution of Java application on its platform. It contains compiled Java class files + some more files like MANIFEST. Basically it is just an ZIP archive with some restrictions.
DEX (Dalvik Executable)
DEX is binary file format, so it is compiled. We could say, that .dex file is for DVM (Dalvik Virtual Machine) something like .class files for JVM.
DEX file format is really generated from java CLASS files by dex compiler from Android SDK. This compiler translates JVM bytecode to DVM bytecode and put all class files to one dex file.
APK (Android Application Package)
APK is file format designed for distributing Android application on its platform. It has some similarities with JAR format. Again it is simply just a ZIP archive, but APK files have pre-defined specific structure. For example, it always must contains file named AndroidManifest.xml and many more. Also this package aggregates compiled classes in dex format.
AAR
AAR is the binary distribution of an Android Library Project. It has similar structure as APK.
| Dex | 33,533,370 | 33 |
Okay, now i'm really stuck here. I don't know what to do, where to go or ANYTHING!
I have been trying to uninstall, reinstall, both SDK and Eclipse-versions, trying to Google this out, but nu-uh... Nothing!!!
I CAN run my app in emulator, but i cant EXPORT it...
[2011-10-07 16:35:30 - Dex Loader] Unable to execute dex: Multiple dex files define Lcom/dreamhawk/kalori/DataBaseHelper;
this is dataBaseHelper
package com.dreamhawk.kalori;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
public class DataBaseHelper extends SQLiteOpenHelper {
// The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.dreamhawk.kalori/databases/";
private static String DB_NAME = "livsmedel_db";
private DataBaseHelper myDBHelper;
private SQLiteDatabase myDb;
private final Context myContext;
private static final String DATABASE_TABLE = "Livsmedel";
public static String DB_FILEPATH = "/data/data/com.dreamhawk.kalori/databases/lifemedel_db";
public static final String KEY_TITLE = "Namn";
public static final String KEY_BODY = "Kcal";
public static final String KEY_ROWID = "_id";
private static final int DATABASE_VERSION = 2;
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* @param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
// checking database and open it if exists
if (checkDataBase()) {
openDataBase();
} else {
try {
this.getReadableDatabase();
createDatabase();
this.close();
openDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
Toast.makeText(context, "Livsmedelsdatabasen importerad",
Toast.LENGTH_LONG).show();
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
boolean exist = false;
try {
String dbPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(dbPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
Log.v("db log", "database does't exist");
}
if (checkDB != null) {
exist = true;
checkDB.close();
}
return exist;
}
@Override
public void onCreate(SQLiteDatabase db) {
// db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Kalori", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS Livsmedel");
onCreate(db);
}
public DataBaseHelper open() throws SQLException {
myDBHelper = new DataBaseHelper(myContext);
myDb = myDBHelper.getWritableDatabase();
return this;
}
public void createDatabase() throws IOException {
InputStream assetsDB = myContext.getAssets().open("livsmedel_db");
// OutputStream dbOut = new FileOutputStream(DB_PATH);
String outFileName = DB_PATH + DB_NAME;
OutputStream dbOut = new FileOutputStream(outFileName);
Log.d("DH", "index=" + assetsDB);
byte[] buffer = new byte[1024];
int length;
while ((length = assetsDB.read(buffer)) > 0) {
dbOut.write(buffer, 0, length);
}
dbOut.flush();
dbOut.close();
assetsDB.close();
}
public Cursor fetchAllNotes() {
return myDb.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_TITLE,
KEY_BODY }, null, null, null, null, null);
}
public void openDataBase() throws SQLException {
String dbPath = DB_PATH + DB_NAME;
myDb = SQLiteDatabase.openDatabase(dbPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
}
I suspect:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
But I don't know what to do... Please help !!! :'(
| There is a file in bin/dexedLibs
The same file exists in libs
Delete it in libs and it should work.
For me it was the android-support-v4.jar.
Hope this helps
| Dex | 7,688,828 | 29 |
I am wondering, if there is any way, how to set skip packaging and dexing in IntelliJ IDEA like in Eclipse and ADT. There is Additional VM Options field in Android DX Compiler section in IntelliJ Preferences, maybe this could be a way, how to set it. I would also appreciate another tips, how to speed up IntelliJ Android project build.
| I'm using IntelliJ 12. I've won time deploying and running Android apps enabling IntelliJ to "Make project automatically". To enable it, just go to Preferences -> Compiler and check "Make project automatically". In the same window check "Compile independent modules in parallel".
Enabling "Make project automatically" allows you skip "Make" task before an Android application launch. You can remove it in "Run/Debug Configurations", selecting your Android Application and removing "Make" task in "Before launch" section.
| Dex | 13,335,674 | 28 |
I'm trying to run instrumentation test cases but getting the below error while dex conversion
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Too many classes in --main-dex-list, main dex capacity exceeded
at com.android.dx.command.dexer.Main.processAllFiles(Main.java:494)
at com.android.dx.command.dexer.Main.runMultiDex(Main.java:334)
at com.android.dx.command.dexer.Main.run(Main.java:244)
at com.android.dx.command.dexer.Main.main(Main.java:215)
at com.android.dx.command.Main.main(Main.java:106)
:App:dexDebug FAILED
How to resolve this issue in gradle?
| Let's first understand the problem:
On pre-Lollipop devices, only main dex is being loaded by the framework. To support multi-dex applications you have to explicitly patch application class loader with all the secondary dex files (this is why your Application class have to extend MultiDexApplication class or call MultiDex#install).
This means that your application's main dex should contain all the classes that are potentially accessible before class loader patching.
You will receive java.lang.ClassNotFoundException if your application code will try to reference a class that was packaged in one of your secondary dex files before successfully patching application class loader.
I've documented here how plugin decides which classes should be packaged in main-dex.
If total amount of methods that those classes are referencing exceeds the 65,536 limit, then build will fail with Too many classes in --main-dex-list, main dex capacity exceeded error.
I can think of three possible solutions for this issue:
(The easiest solution, but not suitable for most of the
applications) Change your minSdkVersion to 21.
Shrink your application code. This was discussed many times previously (see here and here).
If none of the above solutions work for you, you can try to use my workaround for this issue - I'm patching the Android gradle plugin to not include Activity classes in main dex. It's a bit hacky, but works well for me.
There's an issue in Android bug tracker regarding this error. Hopefully the Tools team will provide a better solution soon.
Update (4/27/2016)
Version 2.1.0 of Gradle plugin allows to filter main-dex list classes.
Warning: this is using an unsupported api that will be replaced in the future.
For example, to exclude all activity classes you can do:
afterEvaluate {
project.tasks.each { task ->
if (task.name.startsWith('collect') && task.name.endsWith('MultiDexComponents')) {
println "main-dex-filter: found task $task.name"
task.filter { name, attrs ->
def componentName = attrs.get('android:name')
if ('activity'.equals(name)) {
println "main-dex-filter: skipping, detected activity [$componentName]"
return false
} else {
println "main-dex-filter: keeping, detected $name [$componentName]"
return true
}
}
}
}
}
You can also check my example project that demonstrates this issue (and applies the above filtering).
Update 2 (7/1/2016)
Version 2.2.0-alpha4 of Gradle plugin (with build-tools v24) finally solves this issue by reducing multidex keep list to a minimum.
The unsupported (and undocumented) filter from 2.1.0 should not be used anymore. I've updated my sample project, demonstrating that build succeeds now without any custom build logic.
| Dex | 32,721,083 | 28 |
I'm trying to create a test example where I've the contents of a TextView is set to the contents of a file stored in the IPFS.
I'm using this repository for my functions: https://github.com/ipfs/java-ipfs-api
I keep getting what appears to be a multidex error despit enable multidex in multiple places:
defaultConfig {
applicationId "*****"
minSdkVersion 26
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
**multiDexEnabled true**
}
dependancies{
implementation 'com.android.support:multidex:1.0.0'
}
MainActivity.java:
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
This is the error I'm getting:
FATAL EXCEPTION: main
Process: com.lab1.ac01220.blossom, PID: 20807
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.lab1.ac01220.blossom/com.lab1.ac01220.blossom.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.lab1.ac01220.blossom.MainActivity" on path: DexPathList[[zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/base.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_dependencies_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_0_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_1_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_2_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_3_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_4_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_5_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_6_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_7_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_8_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/lib/x86, /system/lib, /vendor/lib]]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2718)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.lab1.ac01220.blossom.MainActivity" on path: DexPathList[[zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/base.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_dependencies_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_0_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_1_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_2_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_3_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_4_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_5_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_6_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_7_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_8_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/lib/x86, /system/lib, /vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:93)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.Instrumentation.newActivity(Instrumentation.java:1173)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2708)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
05-01 17:51:48.094 20807-20807/com.lab1.ac01220.blossom E/AndroidRuntime: Suppressed: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v7/app/AppCompatActivity;
at java.lang.VMClassLoader.findLoadedClass(Native Method)
at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
... 12 more
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v7.app.AppCompatActivity" on path: DexPathList[[zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/base.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_dependencies_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_0_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_1_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_2_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_3_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_4_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_5_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_6_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_7_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_8_apk.apk", zip file "/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/lib/x86, /system/lib, /vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:93)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
... 15 more
Suppressed: java.io.IOException: Failed to open dex files from /data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_dependencies_apk.apk because: Failure to verify dex file '/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_dependencies_apk.apk': Bad method handle type 7
at dalvik.system.DexFile.openDexFileNative(Native Method)
at dalvik.system.DexFile.openDexFile(DexFile.java:353)
at dalvik.system.DexFile.<init>(DexFile.java:100)
at dalvik.system.DexFile.<init>(DexFile.java:74)
at dalvik.system.DexPathList.loadDexFile(DexPathList.java:374)
at dalvik.system.DexPathList.makeDexElements(DexPathList.java:337)
at dalvik.system.DexPathList.<init>(DexPathList.java:157)
at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:65)
at dalvik.system.PathClassLoader.<init>(PathClassLoader.java:64)
at com.android.internal.os.PathClassLoaderFactory.createClassLoader(PathClassLoaderFactory.java:43)
at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:69)
at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:36)
at android.app.LoadedApk.createOrUpdateClassLoaderLocked(LoadedApk.java:676)
at android.app.LoadedApk.getClassLoader(LoadedApk.java:709)
at android.app.LoadedApk.getResources(LoadedApk.java:936)
at android.app.ContextImpl.createAppContext(ContextImpl.java:2242)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5672)
at android.app.ActivityThread.-wrap1(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1661)
... 6 more
[CIRCULAR REFERENCE:java.io.IOException: Failed to open dex files from /data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_dependencies_apk.apk because: Failure to verify dex file '/data/app/com.lab1.ac01220.blossom-ixLs4xcrmWVVfgtCrH9vpw==/split_lib_dependencies_apk.apk': Bad method handle type 7]
this is my code:
TextView example = view.findViewById(R.id.example);
IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/4001");
try {
ipfs.refs.local();
NamedStreamable.ByteArrayWrapper file = new NamedStreamable.ByteArrayWrapper("hello.txt", "G'day world! IPFS rocks!".getBytes());
MerkleNode addResult = ipfs.add(file).get(0);
Multihash filePointer = Multihash.fromBase58("QmPZ9gcCEpqKTo6aq61g2nXGUhM4iCL3ewB6LDXZCtioEB");
byte[] fileContents = ipfs.cat(filePointer);
this.example.setText(new String(fileContents));
} catch (IOException e) {
e.printStackTrace();
}
Edit:
I was not getting this error before I installed the jitpack and java-ipfs-api
| Just experienced the same problem, it is because some library use Java 8 features, in your case it should be java-ipfs-api. To solve the problem, configure Android Gradle Plugin to support Java 8 by adding the following code to your build.gradle file, be sure to use latest Android gradle plugin:
android {
...
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
solution taken from here.
| Dex | 50,121,367 | 28 |
My team and I have inherited a large Android project from another team. The whole application with all the included libraries is reported to have around 35000 methods. We now have the task to implement a new service in the app where we need to use Protocol Buffers.
The problem is that the generated .jar file with all the required .proto files creates another couple of 35000 methods, that's 70000 methods. And if you are not aware, the Android compiler has a limitation of 65536 methods per .dex file. We are clearly over that limit and we are getting the following error trying to compile the app:
Unable to execute dex: method ID not in [0, 0xffff]: 65536
Conversion to Dalvik format failed: Unable to execute dex: method ID not in [0, 0xffff]: 65536
Yes, the application architecture should probably be restructured but that will take time. And for now we are trying to figure out a solution to work around this problem temporarily.
Any suggestions?
| You can use another DEX file. This is how you do it:
http://android-developers.blogspot.co.il/2011/07/custom-class-loading-in-dalvik.html
| Dex | 15,436,956 | 27 |
I updated Android Studio to the latest version, and let it "fix the project" and the like - but now my project does not compile, gives me
FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:dexDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
D:\VGA\AndroidStudio\sdk\build-tools\21.1.1\dx.bat --dex --no-optimize --output D:\VGA\Projects\Sales-App\Android-Project\svn\android\app\build\intermediates\dex\debug --input-list=D:\VGA\Projects\Sales-App\Android-Project\svn\android\app\build\intermediates\tmp\dex\debug\inputList.txt
Error Code:
2
Output:
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
at com.android.dx.merge.DexMerger$6.updateIndex(DexMerger.java:502)
at com.android.dx.merge.DexMerger$IdMerger.mergeSorted(DexMerger.java:277)
at com.android.dx.merge.DexMerger.mergeMethodIds(DexMerger.java:491)
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:168)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)
at com.android.dx.command.dexer.Main.runMonoDex(Main.java:302)
at com.android.dx.command.dexer.Main.run(Main.java:245)
at com.android.dx.command.dexer.Main.main(Main.java:214)
at com.android.dx.command.Main.main(Main.java:106)
However, this isn't resolved by just multidexing, because when I added this:
defaultConfig {
...
multiDexEnabled = true
}
This happens
D:\VGA\AndroidStudio\sdk\build-tools\21.1.1\dx.bat --dex --no-optimize --multi-dex --main-dex-list D:\VGA\Projects\Sales-App\Android-Project\svn\android\app\build\intermediates\multi-dex\debug\maindexlist.txt --output D:\VGA\Projects\Sales-App\Android-Project\svn\android\app\build\intermediates\dex\debug --input-list=D:\VGA\Projects\Sales-App\Android-Project\svn\android\app\build\intermediates\tmp\dex\debug\inputList.txt
Error Code:
3
Output:
UNEXPECTED TOP-LEVEL ERROR:
java.lang.OutOfMemoryError: GC overhead limit exceeded
at com.android.dx.cf.code.ConcreteMethod.makeSourcePosistion(ConcreteMethod.java:254)
at com.android.dx.cf.code.RopperMachine.run(RopperMachine.java:306)
at com.android.dx.cf.code.Simulator$SimVisitor.visitLocal(Simulator.java:612)
at com.android.dx.cf.code.BytecodeArray.parseInstruction(BytecodeArray.java:367)
at com.android.dx.cf.code.Simulator.simulate(Simulator.java:94)
at com.android.dx.cf.code.Ropper.processBlock(Ropper.java:787)
at com.android.dx.cf.code.Ropper.doit(Ropper.java:742)
at com.android.dx.cf.code.Ropper.convert(Ropper.java:349)
at com.android.dx.dex.cf.CfTranslator.processMethods(CfTranslator.java:280)
at com.android.dx.dex.cf.CfTranslator.translate0(CfTranslator.java:137)
at com.android.dx.dex.cf.CfTranslator.translate(CfTranslator.java:93)
at com.android.dx.command.dexer.Main.processClass(Main.java:729)
at com.android.dx.command.dexer.Main.processFileBytes(Main.java:673)
at com.android.dx.command.dexer.Main.access$300(Main.java:82)
at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:602)
at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:284)
at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166)
at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
at com.android.dx.command.dexer.Main.processOne(Main.java:632)
at com.android.dx.command.dexer.Main.processAllFiles(Main.java:505)
at com.android.dx.command.dexer.Main.runMultiDex(Main.java:332)
at com.android.dx.command.dexer.Main.run(Main.java:243)
at com.android.dx.command.dexer.Main.main(Main.java:214)
at com.android.dx.command.Main.main(Main.java:106)
I tried changing the build tools to latest
android {
compileSdkVersion 21
buildToolsVersion "21.1.1"
Because by default it changed to 20.0.0 which seemed to use the SDK for 4.4W, but this didn't fix my problem.
Does anyone know what could be wrong here?
EDIT:
Changing the build tools or the compile SDK did not fix the problem.
Turning the app into a multi-dex project and also adding the following
android {
compileSdkVersion 21
buildToolsVersion "21.1.1"
defaultConfig {
...
multiDexEnabled true
}
...
dexOptions {
incremental true
javaMaxHeapSize "4g"
}
}
Fixed the build process, however this still seems to be just a "treatment" but not a fix to the problem.
I am not sure if this is related, but this is my dependency list:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:multidex:1.0.0'
compile 'com.android.support:appcompat-v7:21.0.2'
compile 'com.squareup:otto:1.3.5'
compile 'com.squareup.picasso:picasso:2.4.0'
compile 'com.squareup.retrofit:retrofit:1.7.1'
compile 'com.jakewharton:butterknife:6.0.0'
compile 'com.madgag.spongycastle:core:1.51.0.0'
compile 'com.madgag.spongycastle:prov:1.51.0.0'
compile 'com.madgag.spongycastle:pkix:1.51.0.0'
compile 'com.google.code.gson:gson:2.3'
compile 'commons-io:commons-io:2.4'
compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
compile 'com.squareup.dagger:dagger:1.2.2'
compile 'com.squareup.dagger:dagger-compiler:1.2.2'
compile('com.googlecode.json-simple:json-simple:1.1.1') {
exclude module: 'junit'
}
compile 'com.google.android.gms:play-services:6.5.87'
}
The only new dependency since then has been the last line, which I added as per https://developer.android.com/google/gcm/client.html so I don't think that is the source of the problem.
EDIT2:
Yes, it was the source of the problem. As I needed Google Cloud Messaging, I replaced that dependency with the base as per http://developer.android.com/google/play-services/setup.html#split :
compile 'com.google.android.gms:play-services-base:6.5.87'
And it fixed the problem. Thank you for the help.
EDIT3:
As of play services 7.0.0, the GCM is in
compile 'com.google.android.gms:play-services-gcm:7.0.0'
EDIT4:
Play Services updated to 7.3.0.
Please keep check of the latest version here: http://developer.android.com/google/play-services/setup.html#split
| The error means you have reached maximum method count in your app. That does include any libraries that you use for your project.
There are two ways to tackle the issue:
Get rid of any third-party libraries that you don't really need. If you use google play services that might contribute a lot to the method count. Fortunately as of the latest play-services release it is possible to include only parts of the framework.
Use a multi dex setup for your application.
| Dex | 27,377,080 | 27 |
Dalvik has this well-known limitation on the number of methods it can have in a single .dex file (about 65,536 of them). My question is whether inherited (but not overridden) methods count against this limit or not.
To make things concrete, suppose I have:
public class Foo {
public int foo() {
return 0;
}
}
public class A extends Foo { }
public class B extends Foo { }
public class C extends Foo { }
For the purposes of the 65,536 method limit, does this count as adding one method, or adding 4? (Or, I guess, to take things to their logical conclusion, does this count as 1 method or 52 methods, considering that java.lang.Object brings 12 methods along too).
As background, I've got a non-trivial number of generated classes with some commonality, and I'm also bumping up against the method limit, so I'm wondering if it's worthwhile to try to abstract some of those out into a class hierarchy in order to buy some time.
| An inherited but not overridden method only counts against the method limit if it is ever referenced (called).
In your example, let's say you have the following piece of code
public class main {
public static void main(String[] args) {
Foo foo = new A();
foo.foo();
}
}
In this case, you are referring to Foo.foo(), which already has a reference, due to the explicit definition. Assuming these 5 classes are the only classes in the dex file, you will have a total of 2 method references*. One for main.main(String[]), and one for Foo.foo().
Instead, let's say you have the following code
public class main {
public static void main(String[] args) {
A a = new A();
a.foo();
B b = new B();
b.foo();
C c = new C();
c.foo();
}
}
In this case, since the foo method for each subclass is actually referenced, they will count against your method limit. Your dex file will have 5 method references*.
main.main(String[])
Foo.foo()
A.foo()
B.foo()
C.foo()
* This count isn't quite accurate, it doesn't take into account the constructor methods that are added to each class behind the scenes. Each constructor calls its superclass' constructor, so we also have a reference to the Object constructor, for a total of 6 additional method references in each case, giving a method count of 8 and 11 respectively.
If in doubt, you can try out various scenarios and use baksmali's raw dump functionality to see what the method list in the dex file actually contains.
e.g.
javac *.java
dx --dex --output=temp.dex *.class
baksmali -N -D temp.dump temp.dex
And then, in the dump file, look for "method_id_item section". This is the list of method references that the 64k limit applies to.
| Dex | 17,730,815 | 25 |
I'm not totally sure what the difference is between setting dex option "jumbomode" to true vs adding multidex support.
Setting jumbo mode to true or multidex to true seems to fix the problem below
AGPBI: {"kind":"SIMPLE","text":"UNEXPECTED TOP-LEVEL EXCEPTION:","position":{},"original":"UNEXPECTED TOP-LEVEL EXCEPTION:"}
AGPBI: {"kind":"SIMPLE","text":"com.android.dex.DexIndexOverflowException: Cannot merge new index 65772 into a non-jumbo instruction!","position":{},"original":"com.android.dex.DexIndexOverflowException: Cannot merge new index 65772 into a non-jumbo instruction!"}
AGPBI: {"kind":"SIMPLE","text":"\tat com.android.dx.merge.InstructionTransformer.jumboCheck(InstructionTransformer.java:109)","position":{},"original":"\tat com.android.dx.merge.InstructionTransformer.jumboCheck(InstructionTransformer.java:109)"}
AGPBI: {"kind":"SIMPLE","text":"\tat com.android.dx.merge.InstructionTransformer.access$800(InstructionTransformer.java:26)","position":{},"original":"\tat com.android.dx.merge.InstructionTransformer.access$800(InstructionTransformer.java:26)"}
AGPBI: {"kind":"SIMPLE","text":"\tat com.android.dx.merge.InstructionTransformer$StringVisitor.visit(InstructionTransformer.java:72)","position":{},"original":"\tat com.android.dx.merge.InstructionTransformer$StringVisitor.visit(InstructionTransformer.java:72)"}
AGPBI: {"kind":"SIMPLE","text":"\tat com.android.dx.io.CodeReader.callVisit(CodeReader.java:114)","position":{},"original":"\tat com.android.dx.io.CodeReader.callVisit(CodeReader.java:114)"}
AGPBI: {"kind":"SIMPLE","text":"\tat com.android.dx.io.CodeReader.visitAll(CodeReader.java:89)","position":{},"original":"\tat com.android.dx.io.CodeReader.visitAll(CodeReader.java:89)"}
AGPBI: {"kind":"SIMPLE","text":"\tat com.android.dx.merge.InstructionTransformer.transform(InstructionTransformer.java:49)","position":{},"original":"\tat com.android.dx.merge.InstructionTransformer.transform(InstructionTransformer.java:49)"}
...
| Jumbo Mode, when reading
https://source.android.com/devices/tech/dalvik/dalvik-bytecode.html, the const-string/jumbo is the jumbo mode for string. It is about the opcode such that "op vAA, string@BBBBBBBB" versus "op vAA, string@BBBB", 32 bits versus 16 bit.
Multi Dex is to allow to load classes from more than one dex file. The primary classes.dex must contain the classes necessary for calling this class methods. Secondary dex files found in the application apk will be added to the classloader after first call to MultiDex.install(Context)
see https://developer.android.com/reference/android/support/multidex/MultiDex.html
| Dex | 30,495,212 | 25 |
Adding Multi dex support with the support v4-r21 using gradle def (https://plus.google.com/+IanLake/posts/JW9x4pcB1rj)
apply plugin: 'com.android.application'
android {
compileSdkVersion 19
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "info.osom.multidex"
minSdkVersion 19
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dexOptions {
preDexLibraries = false
}
afterEvaluate {
tasks.matching {
it.name.startsWith('dex')
}.each { dx ->
if (dx.additionalParameters == null) {
dx.additionalParameters = []
}
dx.additionalParameters += '--multi-dex'
dx.additionalParameters += "--main-dex-list=$projectDir/multidex.keep".toString()
}
Now this works for the app itself and I'm able to build and deploy but when I run a robolectric test for my Application class, I get a failure from ZipUtils (which is caught in MultiDex.java). The other tests are running fine. Here is the trace -
Caused by: java.lang.RuntimeException: Multi dex installation failed (/Users/Code/android-code/android/. (Is a directory)).
at android.support.multidex.MultiDex.install(MultiDex.java:178)
at android.support.multidex.MultiDexApplication.attachBaseContext(MultiDexApplication.java:39)
at android.app.Application.attach(Application.java:181)
at org.fest.reflect.method.Invoker.invoke(Invoker.java:112)
at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:155)
at org.robolectric.RobolectricTestRunner.setUpApplicationState(RobolectricTestRunner.java:430)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:236)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:177)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:86)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:49)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:48)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:105)
| Add multi-dex shadow as your dependency:
testCompile "org.robolectric:shadows-multidex:3.0"
This will mock MultiDex.install call and do nothing, since there are no dex in Robolectric
| Dex | 26,512,170 | 21 |
I have been getting this strange error the whole of today - anyone know what is going wrong here?
As far as I know, I have been using the multidex library correctly (the below is from the app.gradle file):
defaultConfig {
applicationId "com.example.simon"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
/*Enabling multidex*/
multiDexEnabled true
}
dependencies {
/* Enabling multidex*/
compile 'com.android.support:multidex:1.0.1'
}
My top level gradle file is very basic:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.0'
classpath 'com.google.gms:google-services:1.3.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
Error:
Executing tasks: [:app:generateDebugSources,
:app:generateDebugAndroidTestSources]
Parallel execution with configuration on demand is an incubating
feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72301Library UP-TO-DATE
:app:prepareComAndroidSupportCardviewV72301Library UP-TO-DATE
:app:prepareComAndroidSupportDesign2301Library UP-TO-DATE
:app:prepareComAndroidSupportMultidex101Library UP-TO-DATE
:app:prepareComAndroidSupportPaletteV72301Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72301Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42301Library UP-TO-DATE
:app:prepareComDigitsSdkAndroidDigits162Library UP-TO-DATE
:app:prepareComFacebookAndroidFacebookAndroidSdk440Library UP-TO-DATE
:app:prepareComFacebookConcealConceal101Library UP-TO-DATE
:app:prepareComGithubCurioustechizenAndroidAgoLibrary130Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesAppinvite780Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesBase780Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesGcm780Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesLocation780Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesMaps780Library UP-TO-DATE
:app:prepareComTheartofdevEdmodoAndroidImageCropper104Library UP-TO-DATE
:app:prepareComTwitterSdkAndroidTweetComposer080Library UP-TO-DATE
:app:prepareComTwitterSdkAndroidTweetUi131Library UP-TO-DATE
:app:prepareComTwitterSdkAndroidTwitter161Library UP-TO-DATE
:app:prepareComTwitterSdkAndroidTwitterCore141Library UP-TO-DATE
:app:prepareIoFabricSdkAndroidFabric134Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:processDebugGoogleServices
:app:generateDebugResources
:app:mergeDebugResources UP-TO-DATE
:app:processDebugManifest UP-TO-DATE
:app:fabricGenerateResourcesDebug
:app:processDebugResources
:app:generateDebugSources
:app:preDebugAndroidTestBuild UP-TO-DATE
:app:prepareDebugAndroidTestDependencies
:app:compileDebugAndroidTestAidl UP-TO-DATE
:app:processDebugAndroidTestManifest UP-TO-DATE
:app:compileDebugAndroidTestRenderscript UP-TO-DATE
:app:generateDebugAndroidTestBuildConfig UP-TO-DATE
:app:generateDebugAndroidTestAssets UP-TO-DATE
:app:mergeDebugAndroidTestAssets UP-TO-DATE
:app:generateDebugAndroidTestResValues UP-TO-DATE
:app:generateDebugAndroidTestResources UP-TO-DATE
:app:mergeDebugAndroidTestResources UP-TO-DATE
:app:processDebugAndroidTestResources UP-TO-DATE
:app:generateDebugAndroidTestSources UP-TO-DATE
BUILD SUCCESSFUL
Total time: 3.913 secs Executing tasks: [:app:assembleDebug]
Parallel execution with configuration on demand is an incubating
feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72301Library UP-TO-DATE
:app:prepareComAndroidSupportCardviewV72301Library UP-TO-DATE
:app:prepareComAndroidSupportDesign2301Library UP-TO-DATE
:app:prepareComAndroidSupportMultidex101Library UP-TO-DATE
:app:prepareComAndroidSupportPaletteV72301Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72301Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42301Library UP-TO-DATE
:app:prepareComDigitsSdkAndroidDigits162Library UP-TO-DATE
:app:prepareComFacebookAndroidFacebookAndroidSdk440Library UP-TO-DATE
:app:prepareComGithubCurioustechizenAndroidAgoLibrary130Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesAppinvite780Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesBase780Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesGcm780Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesLocation780Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesMaps780Library UP-TO-DATE
:app:prepareComTheartofdevEdmodoAndroidImageCropper104Library
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:processDebugGoogleServices
:app:generateDebugResources
:app:mergeDebugResources UP-TO-DATE
:app:processDebugManifest UP-TO-DATE
:app:fabricGenerateResourcesDebug
:app:processDebugResources
:app:generateDebugSources
:app:processDebugJavaRes UP-TO-DATE
:app:compileDebugJavaWithJavac UP-TO-DATE
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources UP-TO-DATE
:app:collectDebugMultiDexComponents UP-TO-DATE
:app:packageAllDebugClassesForMultiDex UP-TO-DATE
:app:shrinkDebugMultiDexComponents UP-TO-DATE
:app:createDebugMainDexClassList UP-TO-DATE
:app:dexDebugExecuting
tasks: [:app:assembleDebug]
Parallel execution with configuration on demand is an incubating
feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72301Library UP-TO-DATE
:app:prepareComAndroidSupportCardviewV72301Library UP-TO-DATE
:app:prepareComAndroidSupportDesign2301Library UP-TO-DATE
:app:prepareComAndroidSupportMultidex101Library UP-TO-DATE
:app:prepareComAndroidSupportPaletteV72301Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72301Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42301Library UP-TO-DATE
:app:prepareComDigitsSdkAndroidDigits162Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:processDebugGoogleServices
:app:generateDebugResources
:app:mergeDebugResources UP-TO-DATE
:app:processDebugManifest UP-TO-DATE
:app:fabricGenerateResourcesDebug
:app:processDebugResources
:app:generateDebugSources
:app:processDebugJavaRes UP-TO-DATE
:app:compileDebugJavaWithJavac UP-TO-DATE
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources UP-TO-DATE
:app:collectDebugMultiDexComponents UP-TO-DATE
:app:packageAllDebugClassesForMultiDex UP-TO-DATE
:app:shrinkDebugMultiDexComponents UP-TO-DATE
:app:createDebugMainDexClassList UP-TO-DATE
:app:dexDebug AGPBI:
{"kind":"simple","text":"UNEXPECTED TOP-LEVEL
EXCEPTION:","sources":[{}]} AGPBI:
{"kind":"simple","text":"java.lang.RuntimeException: Unexpected
exception in dex writer thread","sources":[{}]} AGPBI:
{"kind":"simple","text":"\tat
com.android.dx.command.dexer.Main.runMultiDex(Main.java:397)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat
com.android.dx.command.dexer.Main.run(Main.java:275)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat
com.android.dx.command.dexer.Main.main(Main.java:245)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat
com.android.dx.command.Main.main(Main.java:106)","sources":[{}]}
FAILED
FAILURE: Build failed with an exception.
* What went wrong: Execution failed for task ':app:dexDebug'.
com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command
'C:\Program Files\Java\jdk1.7.0_76\bin\java.exe'' finished with
non-zero exit value 2
* Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 1 mins 5.426 secs
| After googling for a while, I found the problem was that not enough heap was allocated to the dex writer.
I fixed it by putting in the following in my app gradle.build:
android {
dexOptions {
incremental true
javaMaxHeapSize "4g"
}
}
This option also managed to speed up my gradle build significantly.
Extremely long build with Gradle (Android Studio)
| Dex | 32,553,245 | 21 |
Can any body please share the method to execute the dex file in android with command?
This is just to understand.
| Let's say you have a the following code in file HelloWorld.java:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
To run it on an android device:
javac HelloWorld.java
dx --dex --output=classes.dex HelloWorld.class
zip HelloWorld.zip classes.dex
adb push HelloWorld.zip /sdcard/
For GB or earlier, you should be able to simply do:
adb shell dalvikvm -cp /sdcard/HelloWorld.zip HelloWorld
For ICS+:
adb shell mkdir /sdcard/dalvik-cache
adb shell ANDROID_DATA=/sdcard dalvikvm -cp /sdcard/HelloWorld.zip HelloWorld
| Dex | 10,199,863 | 20 |
Subsets and Splits