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

  • Home
  • SEARCH
  • 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 8033465
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T01:42:24+00:00 2026-06-05T01:42:24+00:00

PHP Function: $privateKey = 1234567812345678; $iv = 1234567812345678; $data = Test string; $encrypted =

  • 0

PHP Function:

$privateKey = "1234567812345678";
$iv = "1234567812345678";
$data = "Test string";

$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateKey, $data, MCRYPT_MODE_CBC, $iv);

echo(base64_encode($encrypted));

Result: iz1qFlQJfs6Ycp+gcc2z4w==

Java Function

public static String encrypt() throws Exception{
try{
    String data = "Test string";
    String key = "1234567812345678";
    String iv = "1234567812345678";

    javax.crypto.spec.SecretKeySpec keyspec = new javax.crypto.spec.SecretKeySpec(key.getBytes(), "AES");
    javax.crypto.spec.IvParameterSpec ivspec = new javax.crypto.spec.IvParameterSpec(iv.getBytes());

    javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("AES/CBC/NoPadding");
    cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, keyspec, ivspec);
    byte[] encrypted = cipher.doFinal(data.getBytes());

    return new sun.misc.BASE64Encoder().encode(encrypted);

}catch(Exception e){
    return null;
}

}

returns null.

Please note that we are not allowed to change the PHP code. Could somebody please help us get the same results in Java? Many thanks.

  • 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-06-05T01:42:25+00:00Added an answer on June 5, 2026 at 1:42 am

    You’d have had a better idea of what was going on if you didn’t simply swallow up possible Exceptions inside your encrypt() routine. If your function is returning null then clearly an exception happened and you need to know what it was.

    In fact, the exception is:

    javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
        at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:854)
        at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:828)
        at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
        at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:313)
        at javax.crypto.Cipher.doFinal(Cipher.java:2087)
        at Encryption.encrypt(Encryption.java:20)
        at Encryption.main(Encryption.java:6)
    

    And sure enough, your plaintext is only 11 Java characters long which, in your default encoding, will be 11 bytes.

    You need to check what the PHP mcrypt_encrypt function actually does. Since it works, it is clearly using some padding scheme. You need to find out which one it is and use it in your Java code.

    Ok — I looked up the man page for mcrypt_encrypt. It says:

    The data that will be encrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with \0.

    So you need to replicate that in Java. Here’s one way:

    import javax.crypto.Cipher;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    
    public class Encryption
    {
        public static void main(String args[]) throws Exception {
            System.out.println(encrypt());
        }
    
        public static String encrypt() throws Exception {
            try {
                String data = "Test string";
                String key = "1234567812345678";
                String iv = "1234567812345678";
    
                Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
                int blockSize = cipher.getBlockSize();
    
                // We need to pad with zeros to a multiple of the cipher block size,
                // so first figure out what the size of the plaintext needs to be.
                byte[] dataBytes = data.getBytes();
                int plaintextLength = dataBytes.length;
                int remainder = plaintextLength % blockSize;
                if (remainder != 0) {
                    plaintextLength += (blockSize - remainder);
                }
    
                // In java, primitive arrays of integer types have all elements
                // initialized to zero, so no need to explicitly zero any part of
                // the array.
                byte[] plaintext = new byte[plaintextLength];
    
                // Copy our actual data into the beginning of the array.  The
                // rest of the array is implicitly zero-filled, as desired.
                System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
    
                SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
                IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
    
                cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
                byte[] encrypted = cipher.doFinal(plaintext);
    
                return new sun.misc.BASE64Encoder().encode(encrypted);
    
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    

    And when I run that I get:

    iz1qFlQJfs6Ycp+gcc2z4w==
    

    which is what your PHP program got.


    Update (12 June 2016):
    As of Java 8, JavaSE finally ships with a documented base64 codec. So instead of

    return new sun.misc.BASE64Encoder().encode(encrypted);
    

    you should do something like

    return Base64.Encoder.encodeToString(encrypted);
    

    Alternatively, use a 3rd-party library (such as commons-codec) for base64 encoding/decoding rather than using an undocumented internal method.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

PHP Encrypt Function $privateKey = 1234567812345678; $iv = 1234567812345678; $data = Test string; $encrypted
in function need key to encrypt string without mcrypt libraly in php function encrypt($str,
Which php array function should be used to match a string to the first
This php function retrieves a list of common words used in a string and
i want a php function probably regular expression to find and replace a string
is there any PHP function available that replaces spaces and underscores from a string
A PHP function I am writing pulls a small bit of HTML data from
This PHP function working just fine: if (preg_match (/<(\S+@\S+\w)>.*\n?.*55[0-9]/i,$body,$match)) { echo found!; } in
Is there a Php function to determine if a string consist of only ASCII
Basic PHP function: //SOAP CALL function sayHello(){ $client = new SoapClient('http://Server:8080/MyClassService/MyClass?WSDL'); $response = $client->glassfishHello();

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.