So I'm trying to get a secretKey for Blowfish using bouncycastle as this:
SecretKeyFactory factory =SecretKeyFactory.getInstance("Blowfish", "BC");
but it throws the following exception:
Exception in thread "main" java.security.NoSuchAlgorithmException: no such algorithm: Blowfish for provider BC
at sun.security.jca.GetInstance.getService(GetInstance.java:87)
at javax.crypto.JceSecurity.getInstance(JceSecurity.java:96)
at javax.crypto.SecretKeyFactory.getInstance(SecretKeyFactory.java:204)
at Main.main(Main.java:112)
How do I solve this? (it also happens when I use "RC4" instead of "Blowfish", but it works with "DES" and "AES")
Unlike asymmetric keys which have internal structure, you don't really need a factory for 'raw' secret (symmetric) keys, only those that use a derivation algorithm (PBE*, PBKDF2, etc). The standard (SunJCE) factories for DES and DESEDE do check/fix length and parity FWLIW, but the BC ones (plus AES beginning with 1.56) don't even do that. RC4 and Blowfish (among others) accept variable-length keys with no constraints on the bits, so there's not really anything the factory could do even if it were provided.
Just put your key material in a SecretKeySpec and use that. Unlike the other *KeySpec types, SecretKeySpec 'is-a' SecretKey (to be exact implements that interface) and can be used where a SecretKey or appropriate Key is needed, particularly in Cipher.init(mode, key ...)
If you really want to generate a key, not use/convert an existing one, you don't want a factory anyway. In spite of the name, factories only convert, they don't create. To generate a key you either need a KeyGenerator (or for asymmetric KeyPairGenerator) and those DO exist for RC4 (aka ARC4) and BLOWFISH in BC, and also in standard SunJCE but using the names ARCFOUR and BLOWFISH; or (for raw symmetric) just use SecureRandom to generate the correct number of bytes, and use that.
(this is purely for academic purposes)
I have got RSA and ElGamal implemented using bouncy castle, But I am not sure how to impliment EC ElGamal. section 4.4 in the bouncy castle spec says: "The org.bouncycastle.crypto.ec package contains implementations for a variety of EC cryptographic transforms such as EC ElGamal" However it doesn't go about explaining how to use it.
I have got as far as using the named curves in the key pair generation
ECNamedCurveTable.getParameterSpec("prime192v1")
But I don't know the algorithm reference e.g. "AES", "RSA" to put the initialisation calls
KeyPairGenerator kpg = KeyPairGenerator.getInstance(algorithm, provider);
Or if anything else needs to be changed when using ECC? I take it the message size limit in ECC is based on the curve size? the above example being 192-bits.
With ECElGamalEncryptor you can only encrypt a point on the curve. This is actually the same with textbook RSA (i.e. modular exponentiation) where you can only encrypt a big integer (less than the modulus).
You should be using a scheme such as ECIES to encrypt with Elliptic Curve cryptography. ECIES basically uses static Diffie-Hellman to encrypt messages.
In signature method in xml signature you have specify in this format : SignatureMethod.RSA_SHA1 but when using normal signature you just do
Cipher c1=Cipher.getInstance("RSA");
So what is the difference between these two?
The difference is simple:
RSA is a (public-key) cryptography algorithm, where the public key is used to encrypt important message. The encrypted data must be decrypted with the private key.
RSA-SHA1, on the other hand, is a combination of RSA cryptography + SHA1 Message Digest. A message digest is a one-way hashing function, which has four main or significant properties:
it is easy to compute the hash value for any given message
it is infeasible to generate a message that has a given hash
it is infeasible to modify a message without changing the hash
it is infeasible to find two different messages with the same hash
In Digital Signature, one would want a guarantee that the signature is valid from sender to receiver. A signature is created through a cryptographic algorithm (e.g. RSA) and then a verification process is done to public key, message, and signature through a hashing function (e.g. SHA-1) for authenticity.
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.
Talking about javax.crypto.Cipher
I was trying to encrypt data using Cipher.getInstance("RSA/None/NoPadding", "BC") but I got the exception:
ArrayIndexOutOfBoundsException: too much data for RSA block
Looks like is something related to the "NoPadding", so, reading about padding, looks like CBC is the best approach to use here.
I found at google something about "RSA/CBC/PKCS#7", what is this "PKCS#7"? And why its not listed on sun's standard algorithm names?
Update:
I'm wondering, if is a padding problem, why this example run just fine?
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
/**
* Basic RSA example.
*/
public class BaseRSAExample
{
public static void main(
String[] args)
throws Exception
{
byte[] input = new byte[] { (byte)0xbe, (byte)0xef };
Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC");
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
// create the keys
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
new BigInteger("d46f473a2d746537de2056ae3092c451", 16),
new BigInteger("11", 16));
RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(
new BigInteger("d46f473a2d746537de2056ae3092c451", 16),
new BigInteger("57791d5430d593164082036ad8b29fb1", 16));
RSAPublicKey pubKey = (RSAPublicKey)keyFactory.generatePublic(pubKeySpec);
RSAPrivateKey privKey = (RSAPrivateKey)keyFactory.generatePrivate(privKeySpec);
// encryption step
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherText = cipher.doFinal(input);
// decryption step
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] plainText = cipher.doFinal(cipherText);
}
}
Update 2:
I realized that even if I use just Cipher.getInstance("RSA", "BC") it throws the same exception.
If you use a block cipher, you input must be an exact multiple of the block bit length.
In order to encipher arbitrary length data, you need first to pad you data to a multiple of the block length. This can be done with any method, but there are a number of standards. PKCS7 is one which is quite common, you can see an overview on the wikipedia article on padding.
Since block cipers operate on blocks, you also need to come up with a way of concatenating the encrypted blocks. This is very important, since naive techniques greatly reduce the strength of the encryption. There is also a wikipedia article on this.
What you did was to try to encrypt (or decrypt) data of a length which didn't match the block length of the cipher, and you also explicitly asked for no padding and also no chaining mode of operation.
Consequently the block cipher could not be applied to your data, and you got the reported exception.
UPDATE:
As a response to your update and GregS's remark, I would like to acknowledge that GregS was right (I did not know this about RSA), and elaborate a bit:
RSA does not operate on bits, it operates on integer numbers. In order to use RSA you therefore need to convert your string message into an integer m: 0 < m < n, where n is the modulus of the two distinct primes chosen in the generation process. The size of a key in the RSA algorithm typically refers to n. More details on this can be found on the wikipedia article on RSA.
The process of converting a string message to an integer, without loss (for instance truncating initial zeroes), the PKCS#1 standard is usually followed. This process also adds some other information for message integrity (a hash digest), semantical security (an IV) ed cetera. With this extra data, the maximum number of bytes which can be supplied to the RSA/None/PKCS1Padding is (keylength - 11). I do not know how PKCS#1 maps the input data to the output integer range, but
my impression is that it can take any length input less than or equal to keylength - 11 and produce a valid integer for the RSA encryption.
If you use no padding, your input will simply be interpreted as a number. Your example input, {0xbe, 0xef} will most probably be interpreted as {10111110 +o 11101111} = 1011111011101111_2 = 48879_10 = beef_16 (sic!). Since 0 < beef_16 < d46f473a2d746537de2056ae3092c451_16, your encryption will succeed. It should succeed with any number less than d46f473a2d746537de2056ae3092c451_16.
This is mentioned in the bouncycastle FAQ. They also state the following:
The RSA implementation that ships with
Bouncy Castle only allows the
encrypting of a single block of data.
The RSA algorithm is not suited to
streaming data and should not be used
that way. In a situation like this you
should encrypt the data using a
randomly generated key and a symmetric
cipher, after that you should encrypt
the randomly generated key using RSA,
and then send the encrypted data and
the encrypted random key to the other
end where they can reverse the process
(ie. decrypt the random key using
their RSA private key and then decrypt
the data).
RSA is a one-shot asymmetric encryption with constraints. It encrypts a single "message" in one go, but the message has to fit within rather tight limits based on the public key size. For a typical 1024 bit RSA key, the maximum input message length (with RSA as described in the PKCS#1 standard) is 117 bytes, no more. Also, with such a key, the encrypted message has length 128 bytes, regardless of the input message length. As a generic encryption mechanism, RSA is very inefficient, and wasteful of network bandwidth.
Symmetric encryption systems (e.g. AES or 3DES) are much more efficient, and they come with "chaining modes" which allow them to process input messages of arbitrary length. But they do not have the "asymmetric" property of RSA: with RSA, you can make the encryption key public without revealing the decryption key. That's the whole point of RSA. With symmetric encryption, whoever has the power to encrypt a message also has all the needed information to decrypt messages, hence you cannot make the encryption key public because it would make the decryption key public as well.
Thus it is customary to use an hybrid system, in which a (big) message is symmetrically encrypted (with, e.g., AES), using a symmetric key (which is an arbitrary short sequence of random bytes), and have that key encrypted with RSA. The receiving party then uses RSA decryption to recover that symmetric key, and then uses it to decrypt the message itself.
Beyond the rather simplistic description above, cryptographic systems, in particular hybrid systems, are clock full of little details which, if not taken care of, may make your application extremely weak against attackers. So it is best to use a protocol with an implementation which already handles all that hard work. PKCS#7 is such a protocol. Nowadays, it is standardized under the name of CMS. It is used in several places, e.g. at the heart of S/MIME (a standard for encrypting and signing emails). Another well-known protocol, meant for encrypting network traffic, is SSL (now standardized under the name of TLS, and often used in combination with HTTP as the famous "HTTPS" protocol).
Java contains an implementation of SSL (see javax.net.ssl). Java does not contain a CMS implementation (at least not in its API) but Bouncy Castle has some code for CMS.
This error indicates that the input data size is greater than the key modulus size. You will need a bigger key size to encrypt the data. If changing the key length is not an option, alternatively you may need to investigate if you are really expecting that big input data.
RSA can only be used to encrypt, when the number of bits being used to encrypt is greater then the size of the thing you are tying to encrypt + 11 bytes
Public-Key Cryptography Standards - PKCS
Scroll down a bit and you'll see it. It's not an cypher algortihm (like RSA) or a cypher mode like CBC, but a description of the way the certificate is encoded as bytes (i.e., a data structure syntax). You can find the spec for it here.
PKCS#7 is listed (referring to your link). It's encoding is PKCS7
Description
A PKCS#7 SignedData object, with the
only significant field being
certificates.
Use java.security.cert.CertificateFactory or CertPath when using PKCS7.
RSA is a block cipher. It encrypts block of the same key size.
Therefore, BouncyCastle RSA gives an exception if you try to encrypt a block
which is longer than the key size.
That's all I can tell you so far.
You should not encrypt your data using RSA directly. Encrypt your data with a random symmetric key (i.e. AES/CBC/PKCS5Padding) and encrypt the symmetric key using RSA/None/PKCS1Padding.