简体   繁体   中英

RSA encryption from java and decryption using php

I am trying do RSA encrypt of user email id using java and trying to decrypt using php. But i was not successful below are the details

Source in java:

package ia;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64; 


public class EncryptionUntil {
/**
* String to hold name of the encryption algorithm.
*/
public static final String ALGORITHM = "RSA";

/**
* String to hold the name of the private key file.
*/
 public static final String PRIVATE_KEY_FILE = "C:/keys/private/private.key";

 /**
 * String to hold name of the public key file.
 */
 public static final String PUBLIC_KEY_FILE = "C:/keys/public/public.key";

 /** 
 * Generate key which contains a pair of private and public key using 1024
  * bytes. Store the set of keys in Prvate.key and Public.key files.
 * 
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws FileNotFoundException
 */
 public static void generateKey() {
try {
    final KeyPairGenerator keyGen = KeyPairGenerator
            .getInstance(ALGORITHM);
    keyGen.initialize(512);
    final KeyPair key = keyGen.generateKeyPair();

    File privateKeyFile = new File(PRIVATE_KEY_FILE);
    File publicKeyFile = new File(PUBLIC_KEY_FILE);

    // Create files to store public and private key
    if (privateKeyFile.getParentFile() != null) {
        privateKeyFile.getParentFile().mkdirs();
    }
    privateKeyFile.createNewFile();

    if (publicKeyFile.getParentFile() != null) {
        publicKeyFile.getParentFile().mkdirs();
    }
    publicKeyFile.createNewFile();

    // Saving the Public key in a file
    ObjectOutputStream publicKeyOS = new ObjectOutputStream(
            new FileOutputStream(publicKeyFile));
    publicKeyOS.writeObject(key.getPublic());
    publicKeyOS.close();

    // Saving the Private key in a file
    ObjectOutputStream privateKeyOS = new ObjectOutputStream(
            new FileOutputStream(privateKeyFile));
    privateKeyOS.writeObject(key.getPrivate());
    privateKeyOS.close();
} catch (Exception e) {
    e.printStackTrace();
}

}

/**
 * The method checks if the pair of public and private key has been
 * generated.
 * 
 * @return flag indicating if the pair of keys were generated.
 */
public static boolean areKeysPresent() {

File privateKey = new File(PRIVATE_KEY_FILE);
File publicKey = new File(PUBLIC_KEY_FILE);

if (privateKey.exists() && publicKey.exists()) {
    return true;
}
return false;
}

/**
* Encrypt the plain text using public key.
* 
* @param text
*            : original plain text
* @param key
*            :The public key
* @return Encrypted text
* @throws java.lang.Exception
*/
public static byte[] encrypt(String text, PublicKey key) {
byte[] cipherText = null;
try {
    // get an RSA cipher object and print the provider
    final Cipher cipher = Cipher.getInstance(ALGORITHM);
    // encrypt the plain text using the public key
    cipher.init(Cipher.ENCRYPT_MODE, key);
    cipherText = cipher.doFinal(text.getBytes());

} catch (Exception e) {
    e.printStackTrace();
}
return cipherText;
}

/**
* Decrypt text using private key.
* 
* @param text
*            :encrypted text
* @param key
*            :The private key
* @return plain text
* @throws java.lang.Exception
*/
public static String decrypt(byte[] text, PrivateKey key) {
byte[] dectyptedText = null;
try {
    // get an RSA cipher object and print the provider
    final Cipher cipher = Cipher.getInstance(ALGORITHM);

    // decrypt the text using the private key
    cipher.init(Cipher.DECRYPT_MODE, key);
    dectyptedText = cipher.doFinal(text);

} catch (Exception ex) {
    ex.printStackTrace();
}

return new String(dectyptedText);
}

public static void encDecrypt (String originalText) throws FileNotFoundException,     IOException, ClassNotFoundException{
    ObjectInputStream inputStream = null;

    // Encrypt the string using the public key
    inputStream = new ObjectInputStream(new FileInputStream(
            PUBLIC_KEY_FILE));
    final PublicKey publicKey = (PublicKey) inputStream.readObject();
    final byte[] cipherText = encrypt(originalText, publicKey);
    final String cipherText64 = Base64.encodeBase64URLSafeString(cipherText);


    // Decrypt the cipher text using the private key.
    inputStream = new ObjectInputStream(new FileInputStream(
            PRIVATE_KEY_FILE));
    final PrivateKey privateKey = (PrivateKey) inputStream.readObject();
    final String plainText = decrypt(Base64.decodeBase64(cipherText64), privateKey);

    // Printing the Original, Encrypted and Decrypted Text
    System.out.println("Original Text: " + originalText);
    //System.out.println("Encrypted Text: " + new String(cipherText));
    System.out.println("Base 64 Text: " +cipherText64);
    System.out.println("Decrypted Text: " + plainText);


}
 /**
  * Test the EncryptionUntil
 */
 public static void main(String[] args) {

try {

    // Check if the pair of keys are present else generate those.
    if (!areKeysPresent()) {
        // Method generates a pair of keys using the RSA algorithm and
        // stores it
        // in their respective files
        generateKey();
    }

    final String originalText = "rohit.gupta@infoaxon.com";
    Date dd = new Date();
    System.out.println(dd);
    final String currentTime = String.valueOf(dd.getTime());

    encDecrypt(originalText);
    encDecrypt(currentTime);

} catch (Exception e) {
    e.printStackTrace();
}
}
}

private Key:

aced 0005 7372 0014 6a61 7661 2e73 6563
7572 6974 792e 4b65 7952 6570 bdf9 4fb3
889a a543 0200 044c 0009 616c 676f 7269
7468 6d74 0012 4c6a 6176 612f 6c61 6e67
2f53 7472 696e 673b 5b00 0765 6e63 6f64
6564 7400 025b 424c 0006 666f 726d 6174
7100 7e00 014c 0004 7479 7065 7400 1b4c
6a61 7661 2f73 6563 7572 6974 792f 4b65
7952 6570 2454 7970 653b 7870 7400 0352
5341 7572 0002 5b42 acf3 17f8 0608 54e0
0200 0078 7000 0001 5830 8201 5402 0100
300d 0609 2a86 4886 f70d 0101 0105 0004
8201 3e30 8201 3a02 0100 0241 008d 442f
2df6 7e5d 6e48 16a9 70a1 9006 c932 1c47
71de 6cb7 81eb 8483 e5e4 73ee b06f 5e73
ed1e 851d 54f1 2d86 6491 479a d314 8897
f7e6 85dc 65ca f1f9 318e cc41 4702 0301
0001 0240 2306 f713 d47c bcb9 ed92 00ed
7681 f9cc c56a 11a5 005b c09c ac43 2d59
416e 258e a6a3 c4bb cc6d bcf1 7b5b 24d6
ff95 a146 2040 4d27 a92d cb9e ccaa 3519
fc85 50d1 0221 00db b9b2 a4c4 3ef6 4780
303c 6798 819f 1a9a 04ca dced 0f9e 0cfd
b4a5 75f5 bdf0 f502 2100 a496 8e0e d531
5e0b b427 6966 2b55 546b 2a8a a5d0 dcf4
bbfd 7ce9 1c56 d79c 13cb 0220 2736 8cdb
3aea c1a9 2107 7ac0 4247 5fcd af8f 0b65
4229 775b 7a2b b31b ca2f 8bc1 0220 28e3
e6a3 34c0 3117 4348 cf5c bcc3 5457 d397
e29e 4366 e215 9624 ec0f 7f3d 9d85 0221
00b4 fdab 7ff3 9804 f6f5 00bf 32a1 3c5c
7517 b0ab 90e1 f20a c9df 8d30 f778 c729
e074 0006 504b 4353 2338 7e72 0019 6a61
7661 2e73 6563 7572 6974 792e 4b65 7952
6570 2454 7970 6500 0000 0000 0000 0012
0000 7872 000e 6a61 7661 2e6c 616e 672e
456e 756d 0000 0000 0000 0000 1200 0078
7074 0007 5052 4956 4154 45

RSA Encrypt Output:

    [B@1dd8823

and base64 encode output:

    CslqF1Wj2mOXRzDtfJuA7Idy6Cty_3O2wHUHFWW8ZWsQaPOT-vsCV_KqW_gM2cdw5W1SSA3iZbDrpNiJ1-wMuQ

php Code for decryption

 <?php
 function der2pem($der_data, $kind) {
 $pem = chunk_split(base64_encode($der_data), 64, "\n");
 $pem = "-----BEGIN ".$kind."-----\n".$pem."-----END ".$kind."-----\n";
 return $pem;
 }

 function to_pem($filename, $kind) {
 // TODO: handle errors
 $f = fopen($filename, "r");
 $der = fread($f, filesize($filename));
 $pem = der2pem($der, $kind);
 fclose($f);

 return $pem;
 }

 function load_private_key($filename) {
 $pem = to_pem($filename, "PRIVATE KEY");
 return openssl_pkey_get_private($pem);
 }

 function load_public_key($filename){
 $pem = to_pem($filename, "PUBLIC KEY");
 return openssl_pkey_get_public($pem);
 }

  $private_key = load_private_key("private.key"); 

  $public_key = load_public_key("public.key");
  $ciphertext = base64_decode("[B@1dd8823");
  #$ciphertext = "CslqF1Wj2mOXRzDtfJuA7Idy6Cty_3O2wHUHFWW8ZWsQaPOT-  vsCV_KqW_gM2cdw5W1SSA3iZbDrpNiJ1-wMuQ";
 echo "cipher = "; echo $ciphertext; echo '</br>';echo '</br>';
 if (openssl_private_decrypt($ciphertext, $recovered_plaintext, $private_key))
{
 echo  "recover text = "; echo $recovered_plaintext; echo '</br>';
}
#}
?>

The php output returns none...

Try key.getPublic().getEncoded() instead of key.getPublic() . Same thing for key.getPrivate() . As is the key isn't in a format OpenSSL supports.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM