RAS签名报错 java.security.InvalidKeyException:throws ioexceptionn : Detect premature EOF,是什么原因

I was working on webservice call where my code was breaking in RAD during decrypting the password of keystore. I encountered below error:
Caused by: java.security.InvalidKeyException: Illegal key size or default parameters
at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
at javax.crypto.Cipher.init(DashoA13*..) ~[na:1.6]
at javax.crypto.Cipher.init(DashoA13*..) ~[na:1.6]
There are key size restrictions with the default crypto files local_policy.jar and US_export_policy.jar comes with JDK – which limits it to 128. If your security policy using a key size larger than this – then the above exception is thrown.
For example – if your security policy specifies the algorithmic suite as Basic256 – then the key size to be used is 256.
For the solution of above issue, you need to patch your JDK with Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files.
For JDK1.5 , download the crypto files and copy the two jar files from the extracted jce directory (local_policy.jar and US_export_policy.jar) to $JAVA_HOME/jre/lib/security.
For JDK1.6
If your IDE using it’s own specific JDK then patch that as well with these files to resolve the issue.
About nitingautam
I am Tech Lead (Java/J2EE/ExtJs)
with a MNC located @ Gurgaon.
This entry was posted in , ,
and tagged , , , . Bookmark the .
Categories
Recent Postsencryption - Getting Exception java.security.InvalidKeyException: Invalid AES key length: 29 bytes? - Stack Overflow
Join the Stack Overflow Community
Stack Overflow is a community of 7.1 million programmers, just like you, helping each other.
J it only takes a minute:
When running below programme i am getting this
exception. Not able to figure out what the issue as AES allows the 128 -256 bit key?
Exception in thread "main" java.security.InvalidKeyException: Invalid AES key length: 29 bytes
at com.sun.crypto.provider.AESCipher.engineGetKeySize(DashoA13*..)
at javax.crypto.Cipher.b(DashoA13*..)
Getting exception at line 20
Here is the programme
import java.security.K
import javax.crypto.C
import javax.crypto.spec.SecretKeyS
import sun.misc.BASE64D
import sun.misc.BASE64E
public class AESEncryptionDecryptionTest {
private static final String ALGORITHM
private static final String myEncryptionKey = "ThisIsSecurityKey";
private static final String UNICODE_FORMAT
public static String encrypt(String valueToEnc) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
//////////LINE 20
byte[] encValue = c.doFinal(valueToEnc.getBytes());
String encryptedValue = new BASE64Encoder().encode(encValue);
return encryptedV
public static String decrypt(String encryptedValue) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedV
private static Key generateKey() throws Exception {
byte[] keyAsB
keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
Key key = new SecretKeySpec(keyAsBytes, ALGORITHM);
public static void main(String[] args) throws Exception {
String value = "password1";
String valueEnc = AESEncryptionDecryptionTest.encrypt(value);
String valueDec = AESEncryptionDecryptionTest.decrypt(valueEnc);
System.out.println("Plain Text : " + value);
System.out.println("Encrypted : " + valueEnc);
System.out.println("Decrypted : " + valueDec);
13.1k47148241
AES allows 128, 192 or 256 bit key length. That is 16, 24 or 32 byte. Try taking just the first 16 bytes of your mEncryptionKey as the keyAsBytes.
An after though occurred to me. A habit I have formed, and one which I recommend, is to take a SHA hash of a password/passphrase, and use that as the source bytes of your key. Taking a hash guarantees the key data will be the correct size, irrespective of the length of the password/passphrase. Your current implementation of using the String by
It will break your key generation if someone uses a short password.
Two different passwords for which the first 16 bytes are the same will create the same key.
Both of these problems are eliminated by using a hash.
Take a look at the buildKey()
13.9k42562
The key uses randomness as input, but there are stiill requirements for how it is composed. The SecretKeySpec constructor you used is for loading an already generated key into memory. Instead, use .
KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
kg.init(128);
SecretKey k = kg.generateKey();
Also note that AES-128 is now actually thought to be weaker than AES-256. It probably isn't drastically different but the benefit from the longer key size may be outweighed by simplifications elsewhere (fewer rounds).
6,78311728
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
rev .25906
Stack Overflow works best with JavaScript enabled写个RAS加密解密例子加深一下印象
package cheng.test.
import java.io.FileInputS
import java.io.FileNotFoundE
import java.io.FileOutputS
import java.io.IOE
import java.io.ObjectInputS
import java.io.ObjectOutputS
import java.security.InvalidKeyE
import java.security.KeyP
import java.security.KeyPairG
import java.security.NoSuchAlgorithmE
import java.security.interfaces.RSAPrivateK
import java.security.interfaces.RSAPublicK
import javax.crypto.BadPaddingE
import javax.crypto.C
import javax.crypto.IllegalBlockSizeE
import javax.crypto.NoSuchPaddingE
public class RSADemo {
private RSAPublicKey publicK
private RSAPrivateKey privateK
* 密文的长度
private int encrytLength = 256;
* 持久化的公钥文件
private static final String publicKeyFile = "./public.key";
* 持久化的私钥文件
private static final String privateKeyFile = "./private.key";
* generate public key and private key
* @throws NoSuchAlgorithmException
public void genKey() throws NoSuchAlgorithmException {
KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA");
kg.initialize(encrytLength * 8);
KeyPair kp = kg.generateKeyPair();
publicKey = (RSAPublicKey) kp.getPublic();
privateKey = (RSAPrivateKey) kp.getPrivate();
//serialize the public key and the private key
serailizeKey();
private void serailizeKey() {
ObjectOutputStream pulicKeyOop = null;
ObjectOutputStream privateKeyOop = null;
pulicKeyOop = new ObjectOutputStream(new FileOutputStream(publicKeyFile));
pulicKeyOop.writeObject(publicKey);
privateKeyOop = new ObjectOutputStream(new FileOutputStream(privateKeyFile));
privateKeyOop.writeObject(privateKey);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(null != pulicKeyOop) {
pulicKeyOop.close();
if(null != privateKeyOop) {
privateKeyOop.close();
} catch (IOException e) {
e.printStackTrace();
private RSAPublicKey getPublicKey() {
ObjectInputStream ois = null;
RSAPublicKey key = null;
ois = new ObjectInputStream(new FileInputStream(publicKeyFile));
key = (RSAPublicKey)ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(null != ois) {
ois.close();
} catch (IOException e) {
e.printStackTrace();
private RSAPrivateKey getPrivateKey() {
RSAPrivateKey key = null;
ObjectInputStream ois = null;
ois = new ObjectInputStream(new FileInputStream(privateKeyFile));
key = (RSAPrivateKey)ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(null != ois) {
ois.close();
} catch (IOException e) {
e.printStackTrace();
public byte[] encrypt(byte [] origin) {
Cipher cipher = null;
byte[] cn = null;
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, getPrivateKey());
cn = cipher.doFinal(origin);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
public byte[] decrypt(byte[] enc) {
Cipher cipher = null;
byte[] cn = null;
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, getPublicKey());
cn = cipher.doFinal(enc);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
public static void main(String[] args) {
RSADemo rs = new RSADemo();
rs.genKey();
String content = "hello world...";
byte[] encryptedContent = rs.encrypt(content.getBytes());
System.out.println(new String(encryptedContent));
byte[] decryptedContent = rs.decrypt(encryptedContent);
System.out.println("\n" + new String(decryptedContent));
阅读(...) 评论()java - Algid parse error, not a sequence - Stack Overflow
Join the Stack Overflow Community
Stack Overflow is a community of 7.1 million programmers, just like you, helping each other.
J it only takes a minute:
When trying to read a RSA private key from a file using the method
public PrivateKey getPrivateKey()
throws NoSuchAlgorithmException,
InvalidKeySpecException, IOException {
final InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream("privatekey");
byte[] privKeyBytes =
privKeyBytes = IOUtils.toByteArray(inputStream);
} catch (final IOException exception) {
LOGGER.error("", exception);
IOUtils.closeQuietly(inputStream);
LOGGER.debug("privKeyBytes: {}", privKeyBytes);
String BEGIN = "-----BEGIN RSA PRIVATE KEY-----";
String END = "-----END RSA PRIVATE KEY-----";
String str = new String(privKeyBytes);
if (str.contains(BEGIN) && str.contains(END)) {
str = str.substring(BEGIN.length(), str.lastIndexOf(END));
KeyFactory fac = KeyFactory.getInstance("RSA");
EncodedKeySpec privKeySpec =
new PKCS8EncodedKeySpec(Base64.decode(str.getBytes()));
return fac.generatePrivate(privKeySpec);
I get the exception
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:200) ~[na:1.6.0_23]
at java.security.KeyFactory.generatePrivate(KeyFactory.java:342) ~[na:1.6.0_23]
at the fac.generatePrivate(privKeySpec) call.
What does this error mean?
1,6362587186
It means your key is not in PKCS#8 format. The easiest thing to do is to use the openssl pkcs8 -topk8 &...other options...& command to convert the key once. Alternatively you can use the
class of the .
44.2k68317452
22.9k74980
I was having this same issue, and the format of the key was NOT the actual problem.
All I had to do to get rid of that exception was to call
java.security.Security.addProvider(
new org.bouncycastle.jce.provider.BouncyCastleProvider()
and everything worked
For me, I was missing the OID in the public key. I had to correct that on the iOS side using help from here:
Also, my public key didn't have to be casted to an RSAPublicKey, the standard worked just fine:
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
rev .25906
Stack Overflow works best with JavaScript enabled

我要回帖

更多关于 ioexception拒绝访问 的文章

 

随机推荐