Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7642673
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T09:14:59+00:00 2026-05-31T09:14:59+00:00

I am first going to describe the problem which I have, and then give

  • 0

I am first going to describe the problem which I have, and then give some background to what I am trying to do. Finally I shall paste some relevant code snippets.

I am trying to implement secret key encryption/decryption using the method specified in https://stackoverflow.com/a/992413/171993. If I use that example as-is, it works (although I did notice that I need to re-instantiate the Cipher class, otherwise the decryption produces garbage). However, in my implementation I get the following exception:

java.security.InvalidKeyException: Wrong algorithm: AES or Rijndael required
    at com.sun.crypto.provider.AESCrypt.init(AESCrypt.java:77)
    at com.sun.crypto.provider.CipherBlockChaining.init(CipherBlockChaining.java:91)
    at com.sun.crypto.provider.CipherCore.init(CipherCore.java:469)
    at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:217)
    at javax.crypto.Cipher.implInit(Cipher.java:790)
    at javax.crypto.Cipher.chooseProvider(Cipher.java:848)
    at javax.crypto.Cipher.init(Cipher.java:1347)
    at javax.crypto.Cipher.init(Cipher.java:1281)
    at securitytest.SecurityManager.getCipher(SecurityManager.java:175)
    at securitytest.SecurityManager.decryptSecretKey(SecurityManager.java:379)
    at securitytest.SecurityManager.<init>(SecurityManager.java:82)
    at securitytest.Test.main(Test.java:44)

To beat off the obvious question, yes, I do use the same algorithm: in fact, I assigned AES/CBC/PKCS5Padding to a constant and use that for instantiating both the Cipher class for encryption and decryption. I have also tried using only AES instantiate Cipher for the decryption, but that did not work either.

What I am trying to do is to password-protect a secret key by using AES/CBC/PKCS5Padding. I generate a random salt and initialisation vector. After encrypting the secret key, I append the initialisation vector (an array of bytes) to the encrypted value (also an array of bytes, creating a new array). I then encode this value in Base64 and store it in a Sqlite database, along with the salt (which, for the sake of simplicity, I store as a comma-separated string of values). However when I try to decrypt, I get the above exception. I can verify that directly after my call to the encryption method and directly before the decryption method, the following values are exactly the same (when converted to Base64 so that I can print it out):

  1. The salt
  2. The initialisation vector
  3. The encrypted secret key (i.e. the cipher text)

I have tried both Java 6 and 7: both give the same results. I have also ruled out the unlimited strength jurisdiction policy files as an issue. In fact, I get a similar error if I substitute “AES” with another algorithm and adjust the length of the salt accordingly (for example “Blowfish” with IV length 8, which produces java.security.InvalidKeyException: Wrong algorithm: Blowfish required).

Google has not been able to help me with this problem. If anyone can shed some light on this, I would be very appreciative.

Here are some code snippets (my apologies, it is a little rough):

private static final int INIT_VECTOR_LENGTH = 16;
private static final int PRIVATE_KEY_LENGTH = 128;
private static final int SALT_LENGTH = 16;
private static final int PBE_KEYSPEC_ITERATIONS = 65536;

private static final String CIPHER_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM_MODE = "CBC";
private static final String CIPHER_ALGORITHM_PADDING = "PKCS5Padding";
private static final String DIGEST = "SHA1";
private static final String PLAINTEXT_ENCODING = "UTF8";
private static final String PRNG = DIGEST + "PRNG";
private static final String SECRET_KEY_FACTORY = "PBKDF2WithHmac" + DIGEST;

private static final String CIPHER = CIPHER_ALGORITHM + "/" + CIPHER_ALGORITHM_MODE + "/" + CIPHER_ALGORITHM_PADDING;

private IvParameterSpec ivSpec;
private final BASE64Encoder encoder = new BASE64Encoder();
private final BASE64Decoder decoder = new BASE64Decoder();

private Cipher getCipher(SecretKey key, int mode) {

    Cipher cipher = null;

    try {
        cipher = Cipher.getInstance(CIPHER);
    }
    catch (NoSuchAlgorithmException e) {System.err.println(System.err.println(e.getMessage());}
    catch (NoSuchPaddingException e) {System.err.println(e.getMessage());}

    try {
        if (mode == Cipher.ENCRYPT_MODE) {
            cipher.init(mode, key);
            AlgorithmParameters params = cipher.getParameters();
            ivSpec = params.getParameterSpec(IvParameterSpec.class);
        }
        else {
            /* This is my point-of-failure. */
            cipher.init(mode, key, ivSpec);
        }
    }
    catch (InvalidKeyException e) {System.err.println(e.getMessage());}
    catch (InvalidAlgorithmParameterException e) {System.err.println(e.getMessage());}
    catch (InvalidParameterSpecException e) {System.err.println(e.getMessage());}

    return cipher;

}

private SecurityData.Secrets generateSecrets(SecretKey decryptedKey, byte[] salt, String passphrase) {

    /* Generate a new key for encrypting the secret key. */
    byte[] raw = null;
    PBEKey key = null;
    PBEKeySpec password = new PBEKeySpec(passphrase.toCharArray(), salt, PBE_KEYSPEC_ITERATIONS, PRIVATE_KEY_LENGTH);
    SecretKeyFactory factory = null;
    byte[] initVector = null;
    byte[] secretKeyBytes = decryptedKey.getEncoded();

    try {
        factory = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY);
        key = (PBEKey) factory.generateSecret(password);
    }
    catch (NoSuchAlgorithmException e) {System.err.println(e.getMessage());}
    catch (InvalidKeySpecException e) {System.err.println(e.getMessage());}

    SecretKeySpec newKey = new SecretKeySpec(key.getEncoded(), CIPHER_ALGORITHM);

    /* Encrypt the secret key. */
    IvParameterSpec ivSpec = new IvParameterSpec(initVector);
    Cipher cipher = getCipher(newKey, ivSpec, Cipher.ENCRYPT_MODE);

    try {
        raw = cipher.doFinal(secretKeyBytes);
    }
    catch (IllegalBlockSizeException e) {System.err.println(e.getMessage());}
    catch (BadPaddingException e) {System.err.println(e.getMessage());}

    return new SecurityData.Secrets(encoder.encode(concatByteArrays(initVector, raw)), joinByteArray(salt));

}

private SecretKey decryptSecretKey(String encryptedKey, String salt, String passphrase) {

    /* Get initialisation vector. */
    byte[] raw = null, decoded = null, initVector = new byte[INIT_VECTOR_LENGTH];
    try {
        decoded = decoder.decodeBuffer(encryptedKey);
    } catch (IOException e) {System.err.println(e.getMessage());}
    System.arraycopy(decoded, 0, initVector, 0, INIT_VECTOR_LENGTH);
    raw = new byte[decoded.length-INIT_VECTOR_LENGTH];
    System.arraycopy(decoded, INIT_VECTOR_LENGTH, raw, 0, decoded.length-INIT_VECTOR_LENGTH);
    IvParameterSpec ivSpec = new IvParameterSpec(initVector);

    /* Generate the key. */
    byte[] rawSalt = splitByteArrayString(salt);
    PBEKeySpec password = new PBEKeySpec(passphrase.toCharArray(), rawSalt, PBE_KEYSPEC_ITERATIONS, PRIVATE_KEY_LENGTH);
    SecretKeyFactory factory = null;
    PBEKey key = null;
    try {
        factory = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY);
        key = (PBEKey) factory.generateSecret(password);
    }
    catch (NoSuchAlgorithmException e) {System.err.println(e.getMessage());}
    catch (InvalidKeySpecException e) {System.err.println(e.getMessage());}

    Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE);

    /* Decrypt the message. */
    byte[] stringBytes = null;
    try {
        stringBytes = cipher.doFinal(raw);
    }
    catch (IllegalBlockSizeException e) {System.err.println(e.getMessage());}
    catch (BadPaddingException e) {System.err.println(e.getMessage());}

    /* Converts the decoded message to a String. */
    String clear = null;
    try {
        clear = new String(stringBytes, PLAINTEXT_ENCODING);
    }
    catch (UnsupportedEncodingException e) {System.err.println(e.getMessage());}

    return new SecretKeySpec(clear.getBytes(), CIPHER_ALGORITHM);

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T09:15:01+00:00Added an answer on May 31, 2026 at 9:15 am

    The SecretKey object needs to return “AES” from its getAlgorithm() method. That’s why the example has these steps:

    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Before going to describe my problem first,I would like to define definitions of Decorator
First I'm going to show you an image of what I'm trying to recreate
First of all, I have to say that I'm going to talk about System.ComponentModel.Component
First, a little background, because there is a lot of interaction going on: I'm
I'm writing my first Android app, which is more or less going to be
Please bear with me on this one. I am first going to describe an
First I've read loads of posts and sites that recommend going to http://silverlight.net/GetStarted/ to
I am going to develop my first application (4 members team).I am not aware
I'm going a little mad I think. This is the VERY first thing I
Yesterday I used jQuery UI for the first time and I think I'm going

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.