logo
down
shadow

Unable to replicate an encryption method from Java to PHP using AES/ECB/PKCS5Padding


Unable to replicate an encryption method from Java to PHP using AES/ECB/PKCS5Padding

By : user2186736
Date : November 25 2020, 04:01 AM
With these it helps Since you are interested in the decryption of an encrypted string in which the encryption was done with the Java encryptEK-method and the decryption should be done with the PHP decrypt-method (or vice versa) I ignore the code of the main-method (which isn't very clear to me) and I focus on the porting of the both Java-methods, encryptEK and decrypt, to PHP-methods.
The Java encryptEK-method takes a plain text and a key as byte array, encrypts the plain text using AES (256-ECB) and encodes the encrypted text using Base64 encoding. A possible PHP-counterpart is:
code :
public function encrypt($data = '', $key = NULL) {
    if($key != NULL && $data != ""){
        $method = "AES-256-ECB";
        $encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA);
        $result = base64_encode($encrypted);
        return $result;
    }else{
        return "String to encrypt, Key is required.";
    }
}
public function decrypt($data="", $key = NULL) {
    if($key != NULL && $data != ""){
        $method = "AES-256-ECB";
        $dataDecoded = base64_decode($data);
        $decrypted = openssl_decrypt($dataDecoded, $method, $key, OPENSSL_RAW_DATA);
        return $decrypted;
    }else{
        return "Encrypted String to decrypt, Key is required.";
    }
}
KEYGEN.init(256);
SecretKey secretKey = KEYGEN.generateKey();
byte[] key = secretKey.getEncoded();
$key = random_bytes(32);
byte[] key = "This is a 256 bits = 32 byte key".getBytes(Charsets.UTF_8);
$key = mb_convert_encoding("This is a 256 bits = 32 byte key", "UTF-8");
Plain text: The quick brown fox jumps over the lazy dog
Randomly generated key (hex): 20e9c191374b688e74e68ab6c969109e84c5c8e059d84f16f2beb07a7545cbc8
Encrypted text (base64 encoded): ZWOnSYErRxRRtqoVFTLVQMT329pOFHzN1gPDMuiZt0zFpt4n2TF/L54RB21zhVUa
Decrypted text: The quick brown fox jumps over the lazy dog
Plain text: The quick brown fox jumps over the lazy dog
Randomly generated key (hex): eecd40c21e2a395f3aa3baeac19bfc8dcee04ea6e07f02dca7069397a487824f
Encrypted text (base64 encoded): 8wjusOED9TTXHjyEqvmGExLATVlvhg3hXEBHQ6Ku3Fos2OrYKbF+4XdO6cD9JJA5
Decrypted text: The quick brown fox jumps over the lazy dog
$key = random_bytes(32);
echo bin2hex($key);
$atomAES = new AtomAES();
$encrypt = $atomAES->encrypt("The quick brown fox jumps over the lazy dog", $key);
echo $encrypt; 
$decrypt = $atomAES->decrypt($encrypt, $key);
echo $decrypt;
Plain text: The quick brown fox jumps over the lazy dog
Encrypted text (base64 encoded) with Java: /XjXJc5dNk6p/h2HL8MVmmWG8Vd0Ud2x1QQWwmIQr9OG/PXZ0AzsIIMV1YmvMJho
Decrypted text with PHP: The quick brown fox jumps over the lazy dog
$key = mb_convert_encoding("This is a 256 bits = 32 byte key", "UTF-8");
$atomAES = new AtomAES();
$decrypt = $atomAES->decrypt("/XjXJc5dNk6p/h2HL8MVmmWG8Vd0Ud2x1QQWwmIQr9OG/PXZ0AzsIIMV1YmvMJho", $key);
echo $decrypt;
Plain text: The quick brown fox jumps over the lazy dog
Encrypted text (base64 encoded) with PHP:  /XjXJc5dNk6p/h2HL8MVmmWG8Vd0Ud2x1QQWwmIQr9OG/PXZ0AzsIIMV1YmvMJho
Decrypted text with Java: The quick brown fox jumps over the lazy dog
$key = mb_convert_encoding("This is a 256 bits = 32 byte key", "UTF-8");
$atomAES = new AtomAES();
$encrypt = $atomAES->encrypt("The quick brown fox jumps over the lazy dog", $key);
echo $encrypt; 
$encKey = mb_convert_encoding("VEMwcCYfFpsrXQVIFTDrA/2zP/5PYOY6JC1XEkEcLGSk/klt+HqHzGSr781Yznku", "UTF-8");
$asp_secret = mb_convert_encoding("DTosv9G179D0cY1985Uh2eF6ND80C95L", "UTF-8");

atomAES = new AtomAES();
$enc_key = $atomAES->decrypt($encKey, $asp_secret);
$enc_asp_secret = $atomAES->encrypt($asp_secret, base64_decode(base64_encode($enc_key)));
//$enc_asp_secret = $atomAES->encrypt($asp_secret, $enc_key);

echo "asp secret encrypted:\n".mb_convert_encoding($enc_asp_secret, "UTF-8")."\n"; 
asp secret encrypted:
zAnTcjmAezfdzrWGixyfwmb8cM0otrsmwJ8+cNDs48Axh9hYgBtCJyeSE9tCvEBz
public function main(){
    $encKey = mb_convert_encoding("VEMwcCYfFpsrXQVIFTDrA/2zP/5PYOY6JC1XEkEcLGSk/klt+HqHzGSr781Yznku", "UTF-8");
    $asp_secret = mb_convert_encoding("DTosv9G179D0cY1985Uh2eF6ND80C95L", "UTF-8");

    $enc_key = $this->decrypt($encKey, $asp_secret);
    $enc_asp_secret = $this->encrypt($asp_secret, base64_decode(base64_encode($enc_key)));
    //$enc_asp_secret = $this->encrypt($asp_secret, $enc_key);

    echo "asp secret encrypted:\n".mb_convert_encoding($enc_asp_secret, "UTF-8")."\n"; 
}
$atomAES = new AtomAES();
$atomAES->main();


Share : facebook icon twitter icon
Java AES/CBC/PKCS5Padding stream encryption performance compared to no encryption

Java AES/CBC/PKCS5Padding stream encryption performance compared to no encryption


By : A.v. Prajith
Date : March 29 2020, 07:55 AM
help you fix your problem The idea of using Bouncy Castle for everything that is already in the Oracle Java API escapes me. AES-NI won't be enabled for Bouncy as Bouncy is a software only library. Java won't magically replace the AESFastEngine with hardware instructions. Just use the Oracle implementation if you want to have speed.
As for the overhead: yes, overhead should be expected. How large the percentage is compare to other calculations depends of course on the machine and the performance of the other calculations. 40% could be a reasonable expectation though.
Java to ruby AES/ECB/PKCS5Padding encryption

Java to ruby AES/ECB/PKCS5Padding encryption


By : Nabil Nawaz
Date : March 29 2020, 07:55 AM
it helps some times Using ECB mode for tamper-proofing input is very stupid.
Having said that, and knowing it's not your fault, because it was not your idea in the first place, and that you just want the code to work, let's ask an independent party to give us a reference point:
code :
echo -n "amount=10&expiryDate=20150101151515&orderRefNum=11001&postBackURL=http://localhost:9081/local/status.php&storeId=28" | openssl enc -K 38394f5549545550524c334938483347 -aes-128-ecb -base64
r7N11xE4HdbJyTByiTDifI1vifvZyNcNfKF+Jo7jEq4rN7c3EiOJxdWOUlCtVXeH
FBTdPSROSmTkUTWfAuOQnHWqe/q/Msd1ykUDIz9eP5L6X6RI0R5UtUXmaakr4klz
1kxEJOjR/WJ5xgd2clBh4iLcYi3caDrCkbD0kRDLQE4=
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class encryptData {
  public static void main(String[] args) throws Exception {

    String data="amount=10&expiryDate=20150101151515&orderRefNum=11001&postBackURL=http://localhost:9081/local/status.php&storeId=28";
    String key="89OUITUPRL3I8H3G";

    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

    byte[] plaintext = data.getBytes();
    byte[] ciphertext = cipher.doFinal(plaintext);
    String encryptedValue = Base64.getEncoder().encodeToString(ciphertext);

    System.out.println(encryptedValue);
  }
}
r7N11xE4HdbJyTByiTDifI1vifvZyNcNfKF+Jo7jEq4rN7c3EiOJxdWOUlCtVXeH
FBTdPSROSmTkUTWfAuOQnHWqe/q/Msd1ykUDIz9eP5L6X6RI0R5UtUXmaakr4klz
1kxEJOjR/WJ5xgd2clBh4iLcYi3caDrCkbD0kRDLQE4=
#!/usr/bin/ruby

require 'openssl'
require 'base64'

data = "amount=10&expiryDate=20150101151515&orderRefNum=11001&postBackURL=http://localhost:9081/local/status.php&storeId=28"

key = "89OUITUPRL4I9H3G"
cipher = OpenSSL::Cipher.new("AES-128-ECB")
cipher.encrypt()
cipher.key = key
crypt = cipher.update(data) + cipher.final

crypt_string = (Base64.encode64(crypt))
puts crypt_string
mp8WVhyUHFDqvJKaRXbYKbZT1920TNboRpFLUdPaYsWTkiQ2fhN/tCL6wvtI
B9/Mu08McaKTVIWYeQAfVR5XcUKdeQ+CBcJJRs5krLBjtjiMNlBUq9JpCUaC
0eclfDMaGTE+Z4XSafjPictWzTG/Ye+vkJWC23yxW1zSjBnYBfg=
key = "38394f5549545550524c334938483347"
key = [key].pack('H*')
r7N11xE4HdbJyTByiTDifI1vifvZyNcNfKF+Jo7jEq4rN7c3EiOJxdWOUlCt
VXeHFBTdPSROSmTkUTWfAuOQnHWqe/q/Msd1ykUDIz9eP5L6X6RI0R5UtUXm
aakr4klz1kxEJOjR/WJ5xgd2clBh4iLcYi3caDrCkbD0kRDLQE4=
Replicating Java's AES/CBC/PKCS5Padding encryption in PHP

Replicating Java's AES/CBC/PKCS5Padding encryption in PHP


By : user1922359
Date : March 29 2020, 07:55 AM
Does that help Finally figured out the solution as per following link :
https://gist.github.com/odan/c1dc2798ef9cedb9fedd09cdfe6e8e76#gistcomment-2743227
Unable to replicate an encryption format from Java to PHP

Unable to replicate an encryption format from Java to PHP


By : Alessandro Devinus
Date : March 29 2020, 07:55 AM
will be helpful for those in need In the Java encrypt-method the (randomly generated) salt- and IV-bytes are copied together with the encryption-bytes in a single byte-array which becomes base64-encoded and which is returned then. In contrast, the PHP encrypt-method returns a hex-representation of the encryption bytes only. Thus, the information concerning the salt and IV get lost and decryption is no longer possible (unless salt and IV are reconstructed in other ways). In order to prevent this, you have to change the PHP encrypt-method as follows:
code :
public function encrypt($data = '', $key = NULL) {
    if($key != NULL && $data != ""){
        $method = "AES-256-CBC";
        $key1 = mb_convert_encoding($key, "UTF-8"); //Encoding to UTF-8
        //Randomly generate IV and salt
        $salt1 = random_bytes (20); 
        $IVbytes = random_bytes (16); 
        //SecretKeyFactory Instance of PBKDF2WithHmacSHA1 Java Equivalent
        $hash = openssl_pbkdf2($key1,$salt1,'256','65556', 'sha1'); 
        // Encrypt
        $encrypted = openssl_encrypt($data, $method, $hash, OPENSSL_RAW_DATA, $IVbytes);
        // Concatenate salt, IV and encrypted text and base64-encode the result
        $result = base64_encode($salt1.$IVbytes.$encrypted);            
        return $result;
    }else{
        return "String to encrypt, Key is required.";
    }
}
public function decrypt($data="", $key = NULL) {
    if($key != NULL && $data != ""){
        $method = "AES-256-CBC";
        $key1 = mb_convert_encoding($key, "UTF-8");//Encoding to UTF-8
        // Base64-decode data
        $dataDecoded = base64_decode($data);
        // Derive salt, IV and encrypted text from decoded data
        $salt1 = substr($dataDecoded,0,20); 
        $IVbytes = substr($dataDecoded,20,16); 
        $dataEncrypted = substr($dataDecoded,36); 
        // SecretKeyFactory Instance of PBKDF2WithHmacSHA1 Java Equivalent
        $hash = openssl_pbkdf2($key1,$salt1,'256','65556', 'sha1'); 
        // Decrypt
        $decrypted = openssl_decrypt($dataEncrypted, $method, $hash, OPENSSL_RAW_DATA, $IVbytes);
        return $decrypted;
    }else{
        return "Encrypted String to decrypt, Key is required.";
    }
}
$atomAES = new AtomAES();
$encrypt = $atomAES->encrypt("This is a text...This is a text...This is a text...", "This is the password");
echo $encrypt; 
$decrypt = $atomAES->decrypt($encrypt, "This is the password");
echo $decrypt; 
6n4V9wqgsQq87HOYNRZmddnncSNyjFZZb8nSSAi681+hs+jwzDVQCugcg108iTMZLlmBB2KQ4iist+SuboFH0bnJxW6+rmZK07CiZ1Ip+8XOv6UuJPjVPxXTIny5p3QptpBGpw==
This is a text...This is a text...This is a text...
encryptedText = AES256.encrypt("This is a text...This is a text...This is a text...","This is the password");
System.out.println(encryptedText);
qfR76lc04eYAPjjqYiE1wXoraD9bI7ql41gSV/hsT/BLoJe0i0GgJnud7IXOHdcCljgtyFkXB95XibSyr/CazoMhwPeK6xsgPbQkr7ljSg8H1i17c8iWpEXBQPm0nij9qQNJ8A==
$decrypt = $atomAES->decrypt("qfR76lc04eYAPjjqYiE1wXoraD9bI7ql41gSV/hsT/BLoJe0i0GgJnud7IXOHdcCljgtyFkXB95XibSyr/CazoMhwPeK6xsgPbQkr7ljSg8H1i17c8iWpEXBQPm0nij9qQNJ8A==", "This is the password");
echo $decrypt; 
This is a text...This is a text...This is a text...
encryptedText = AES256.encrypt("This is a sample text","NEWENCTEST");
System.out.println(encryptedText);

1HO8iuSZf41RzP/gUleEJY3zhtLJVwFMnhZiphnoG0m9ss+g93Sj5SqQg0D7OsgSvUZCeX2Ck5QPpFrPxM0FE/yFE5s=
$decrypt = $atomAES->decrypt("1HO8iuSZf41RzP/gUleEJY3zhtLJVwFMnhZiphnoG0m9ss+g93Sj5SqQg0D7OsgSvUZCeX2Ck5QPpFrPxM0FE/yFE5s=", "NEWENCTEST");
echo $decrypt; 
 This is a sample text
Java to Node.js AES/ECB/PKCS5Padding Encryption

Java to Node.js AES/ECB/PKCS5Padding Encryption


By : kriskangdev
Date : August 28 2020, 04:00 PM
I wish did fix the issue. So that the NodeJS code is functionally identical to the Java code, in the NodeJS code:
code :
const algorithm = 'aes-128-ecb';
...
//const iv = Buffer.alloc(16, 0); // remove
const cipher = crypto.createCipheriv(algorithm, key, null);
key = crypto.scryptSync(key, 'salt', 16); 
Related Posts Related Posts :
  • How do I make this image larger?
  • Run icCube with JDK 10
  • Expression with Math.random() always returns the same value
  • Getting the Set with the most elements nested in a HashMap using Java Streams
  • XmlSlurper to parse XML and get value of inside elements using Groovy
  • Extracting data from HTML and formatting the output
  • SOLR documentCache JMX metrics clarification
  • Limiting Wildfly 14 Two-Way SSL to specific clients
  • How do I get Min and max values to only print when "year" is entered?
  • Hashmap can't loop - getKey() method not found - Using Java 8
  • Android Studio - Create an EditText with a click of a button
  • Mockito Test not invoking verify() method
  • Wrap method implementations of Java interfaces
  • Remediating dynamic SQL into prepared statements
  • Where do X and Y start at in swing windows
  • java code with files work from eclipse but dont work from cmd
  • Return page object from JPA query
  • I can't figure out why this code in my APCS multiple choice book returns 19
  • How to save data between methods
  • I'm trying to install Apache Gobblin. How can I install it using Gradle?
  • Spring Data Sorting Array or Set into Pageable
  • Question about the Java documentation and its implementation
  • How to make a JButton that when pressed it does a new action
  • Java hibernate No validator could be found for boolean
  • Making a POJO Thread Safe
  • Save the data of a text file in a arraylist
  • Sort a List<String[]> by indices using Comparator
  • Overloading in Java for user input?
  • Unable to format timestamp as YYYY-MM-DD HH:mm:ss in java
  • Access SQLite Helper From Adapter
  • How to stream a csv file with header to a HashMap<String, Double> in Java?
  • can't get go daddy ssl certificate to work with spring boot
  • ResourceBundle can't find BaseName gradle project java
  • Java; Jackson; Parsing the array of array json string
  • Java - map key lookup ignoring case
  • Jackson deserialize map null values to empty string
  • Anyone knows why setCount() is not working in twitter4j?
  • Object Visibility in a Multi-threaded Program in Java
  • Can't store and load an arraylist in an object file
  • convert a string number starts with `00` to `+` in java
  • Java - avoiding NonSuchElementException using ConcurrentLinkedDeque
  • Converting Immutable to mutable list Java
  • Getting nosuchmethod exception
  • How to get MQTT subscriptions
  • Android Google Sign in Exceptions
  • JavaFX - method that waits for user input
  • Replacing values for a particular key in treemap changes values for every key
  • This method call passes a null value for a nonnull method parameter. Either the parameter is annotated as a parameter th
  • Kafka: consume all messages on demand
  • Notify what text was changed in textview
  • Tinkerpop/Gremlin: select vertices together with outgoing edge count
  • transform a list of objects into a list of integers that pass a check
  • Why this java code is showing strange behavior?
  • Maven Project classes not compiling
  • Edit image to make text more clear opencv
  • Android Spinner nullpointer
  • Add result to int array every time you finish counting the occurrence
  • Android import java library
  • How to use LDAP Authentication in a corporate environment
  • adding item during iteration in java special usecase
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org