Sorry for this question. I've read all the previous questions, but my code still not work.
Thanks in advance to anyone that will help me in understanding where is the problem.
In android I use this code for reading the public key and produce the encrypted text:
public static PublicKey getPublicKeyFromString(String stringKey) throws Exception {
byte[] keyBytes = stringKey.getBytes();
byte[] decode = Base64.decode(keyBytes, Base64.DEFAULT);
KeyFactory fact = KeyFactory.getInstance("RSA");
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(decode);
return (PublicKey) fact.generatePublic(x509KeySpec);
}
public static String RSAEncrypt(final String plain, final PublicKey publicKey)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
byte[] encryptedBytes;
Cipher cipher;
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plain.getBytes());
return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
}
//I call these functions in this manner.
private final String pubKeyString =
//"-----BEGIN PUBLIC KEY-----" +
"MIG..." +
"...";
//"-----END PUBLIC KEY-----"
PublicKey pubKey = RSAFunctions.getPublicKeyFromString(pubKeyString);
String encData = RSAFunctions.RSAEncrypt("prova", pubKey);
The publickey.php and privatekey.php file are generated in php with this code:
<?php
include('./Crypt/RSA.php');
$rsa = new Crypt_RSA();
extract($rsa->createKey()); // == $rsa->createKey(1024) where 1024 is the key size
$File1 = "./privatekey.php";
$Handle = fopen($File1, 'w');
fwrite($Handle, "<?php \$privatekey=\"" . $privatekey . "\"?>");
fclose($Handle);
$File2 = "./publickey.php";
$Handle = fopen($File2, 'w');
fwrite($Handle, "<?php \$publickey=\"" . $publickey . "\"?>");
fclose($Handle);
?>
In php I use this code for decrypt data:
<?php
include('Crypt/RSA.php');
require('privatekey.php');
$rsa = new Crypt_RSA();
$rsa->loadKey($privatekey); // private key
$base64_string = $_GET["data"];
$base64_string = str_replace(' ', '+', $base64_string);
$ciphertext = base64_decode( $base64_string );
//$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$plaintext = $rsa->decrypt($ciphertext);
echo $plaintext;
?>
I've also made a php crypt script for testing my decrypt php function. This is the code of my encrypt.php:
<?php
include('Crypt/RSA.php');
require('publickey.php');
$rsa = new Crypt_RSA();
$rsa->loadKey($publickey); // public key
$plaintext = $_GET["data"];
//$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$ciphertext = $rsa->encrypt($plaintext);
echo base64_encode( $ciphertext );
?>
I've no problem when encrypt and decrypt text using only php, but if I use the encrypted data made with android app, php give me an error in decrypting.
Thanks for the attention.
In your php there is :
CRYPT_RSA_ENCRYPTION_PKCS1
but when you create your Cipher object on Android you omit the mode and padding
cipher = Cipher.getInstance("RSA");
you should try something like
Cipher c = Cipher.getInstance("AES/CBC/PKCS1Padding");
ref :
http://developer.android.com/reference/javax/crypto/Cipher.html
Related
I'm trying to encrypt a message using phpseclib. Below is the method that encrypts it:
function RSAEncrypt($data, $publicKey)
{
$rsa = new \Crypt_RSA();
$rsa->loadKey($publicKey);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$encryptedData = $rsa->encrypt($data);
$encodedData = base64_encode($encryptedData);
return $encodedData;
}
the code that encrypt message
$client_key = 123456789;
$random_str = rand();
$aes_password = $client_key.'-'.$random_str;
$public_key = file_get_contents('keys/public.xml');
$ecrypted_password = RSAEncrypt($aes_password, $public_key);
but no matter the message the $aes_password that i passed , the $ecrypted_password output is always
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE= ◀"
I tried to decrypt it using the private key to see if its valid anyways but i always gets Decryption Error so i figured maybe the error is with the encryption
We migrated to PHPSecLib a while ago, but did not migrate our legacy data that was encrypted by the old PEAR\Crypt_RSA library. We've reached a point where we need to migrate that data into PHPSecLib's RSA format. While investigating this, I came across this old forum thread. I attempted to apply the suggestion in the response, but could not get it to successfully decrypt our data. It's not erroring out or anything, it just appears to still be encrypted or encoded. We're running PHPSecLib 2.0.6 currently, and I suspect the instructions were for 1.x.
Here's a roughed out version of my adapted decryption flow (based off the forum thread):
$rsaDecryptor = new RSA();
// The Private Key is encrypted based off a password
$mc = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($mc), MCRYPT_DEV_URANDOM);
$keySize = mcrypt_enc_get_key_size($mc);
$key = substr($rsaDecryptor->password, 0, $keySize);
mcrypt_generic_init($mc, $key, $iv);
$privateKey = mdecrypt_generic($mc, base64_decode($privateKey));
mcrypt_generic_deinit($mc);
mcrypt_module_close($mc);
list($privateKeyModulus, $privateKeyExponent) = unserialize(base64_decode($privateKey));
$privateKeyExponent = new BigInteger(strrev($privateKeyExponent), 256);
$privateKeyModulus = new BigInteger(strrev($privateKeyModulus), 256);
$rsaDecryptor->modulus = $privateKeyModulus;
$rsaDecryptor->exponent = $privateKeyExponent;
$rsaDecryptor->publicExponent = $privateKeyExponent;
$rsaDecryptor->k = strlen($this->decRSA->modulus->toBytes());
// ciphertext is the raw encrypted string created by PEAR\Crypt_RSA
$value = base64_decode($ciphertext);
$value = new BigInteger($value, 256);
$value = $rsaDecryptor->_exponentiate($value)->toBytes();
$value = substr($value, 1);
Bugs In PEAR's Crypt_RSA
So I was playing around with this. There's a bug in PEAR's Crypt_RSA (latest version) that might prevent this from working at all. The following code demonstrates:
$key_pair = new Crypt_RSA_KeyPair(1024);
$privkey = $key_pair->getPrivateKey();
$pubkey = $key_pair->getPublicKey();
$a = $privkey->toString();
$b = $pubkey->toString();
echo $a == $b ? 'same' : 'different';
You'd expect $a and $b to be different, wouldn't you? Well they're not. This is because RSA/KeyPair.php does this:
$this->_public_key = &$obj;
...
$this->_private_key = &$obj;
If you remove the ampersands it works correctly but they're in the code by default.
It looks like this is an unresolved issue as of https://pear.php.net/bugs/bug.php?id=15900
Maybe it behaves differently on PHP4 but I have no idea.
Decrypting Data
Assuming the above bug isn't an issue for you then the following worked for me (using phpseclib 2.0):
function loadKey($key) // for keys genereated with $key->toString() vs $key->toPEMString()
{
if (!($key = base64_decode($key))) {
return false;
}
if (!($key = unserialize($key))) {
return false;
}
list($modulus, $exponent) = $key;
$modulus = new BigInteger(strrev($modulus), 256);
$exponent = new BigInteger(strrev($exponent), 256);
$rsa = new RSA();
$rsa->loadKey(compact('modulus', 'exponent'));
return $rsa;
}
function decrypt($key, $ciphertext)
{
if (!($ciphertext = base64_decode($ciphertext))) {
return false;
}
$key->setEncryptionMode(RSA::ENCRYPTION_NONE);
$ciphertext = strrev($ciphertext);
$plaintext = $key->decrypt($ciphertext);
$plaintext = strrev($plaintext);
$plaintext = substr($plaintext, 0, strpos($plaintext, "\0"));
return $plaintext[strlen($plaintext) - 1] == "\1" ?
substr($plaintext, 0, -1) : false;
}
$key = loadKey($private_key);
$plaintext = decrypt($key, $ciphertext);
echo $plaintext;
Private Keys Generated with toPEMString()
With PEAR's Crypt_RSA you can generate private keys an alternative way:
$key_pair->toPEMString();
This method works without code changes. If you used this approach to generate your private keys the private key starts off with -----BEGIN RSA PRIVATE KEY-----. If this is the case then you don't need to use the loadKey function I wrote. You can do this instead:
$key = new RSA();
$key->loadKey('...');
$plaintext = decrypt($key, $ciphertext);
echo $plaintext;
I send an encrypted base64 encoded JSON object
N4m4EBDjdCfq5V1JqjMXdO6PEjNEh1fAMaHPn....
to an API which reads and returns a response , I am facing trouble trying to decrypt the response. The response I get from the API is
� �Gֲ:й�#���BJ)3ࣗ�%���wW��u~��J�1��(�/�ik�A���Ԥ& ��g��yi�ُ�3��qxQ������4iM���k�o��k����k\�6�x9
My code for Decryption
$private_key = file_get_contents('privateKey.key');
$res = openssl_pkey_get_private($private_key);
$a_key = openssl_pkey_get_details($res);
// Decrypt the data in the small chunks
$chunkSize = ceil($a_key['bits'] / 8);
$output = '';
while ($response)
{
$chunk = substr($response, 0, $chunkSize);
$response = substr($response, $chunkSize);
$decrypted = '';
if (!openssl_private_decrypt($chunk, $decrypted, $res, OPENSSL_NO_PADDING))
{
while ($msg = openssl_error_string())
echo $msg . "<br />\n";
}
$output .= $decrypted;
}
openssl_free_key($res);
echo '<br /><br /> Unencrypted Data: ' .$output;
The output after decryption is
�E�X,�/�၏�����2#>�o����� 1f�=�*�O���г���18}Yi�,�_�ڪ�|
but I am expecting a readable plain text response.
EDIT : I now understand that the encryption is happening at one end in Java, the sample code for encryption is
The code for using .pem file below:
public static String encrypt(String rawText, PublicKey publicKey) throws
IOException, GeneralSecurityException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.encodeBase64String(cipher.doFinal(rawText.getBytes("UTF-
8")));
}
public static RSAPublicKey getPublicKey(String filename) throws IOException,
GeneralSecurityException {
String publicKeyPEM = getKey(filename);
return getPublicKeyFromString(publicKeyPEM);
}
public static RSAPublicKey getPublicKeyFromString(String key) throws
IOException, GeneralSecurityException {
String publicKeyPEM = key;
publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
byte[] encoded = Base64.decodeBase64(publicKeyPEM);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(new
X509EncodedKeySpec(encoded));
return pubKey;
}
private static String getKey(String filename) throws IOException {
// Read key from file
String strKeyPEM = "";
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
while ((line = br.readLine()) != null) {
strKeyPEM += line + "\n";
}
br.close();
return strKeyPEM;
}
public static void main(String[] args) {
RSA necryptionService = new RSA();
try
{
String file = "D:/public.pem";
String data = "Hello Test"
PublicKey publicKey = necryptionService.getPublicKey(file);
String encryptedData = necryptionService.encrypt(data,publicKey);
System.out.println(encryptedData);
}
catch (Exception e)
{
e.printStackTrace();
}
}
Where the string gets converted in the 3rd method, try this additional piece
of code
CertificateFactory fact = CertificateFactory.getInstance("X.509");
FileInputStream is = new FileInputStream(path);
Certificate cer = fact.generateCertificate(is);
logger.info("Public Key:::::::::::loaded"+cer.getPublicKey());
I send my request to the API using cURL and get back the java encrypted response.
The encrypted request is
Zxh5xmxS6pteaq+aWWorF7WRGPn6MB5SlcUR16ncYbUPaNfhOiHskYPuxY+6I3KoHLGWpZ3IndTkaS0CxOSNwFFIsLcAWj9Jv9B6rnk8Y0Tt54d4fygfpY0FGUJdxlgY7DN0ll00OBMqlcReWlBoVxWP06nHLuUmNke9SH0ToJo+V/S7ntQYTBYV+DVbFLJF+/U7woM6xHY8pSoBfKFC1r443ftOP05adkUcrPVIrvswIfk+4TmRvF5Th1tKaHQyGCQ6MJnOZt37RIiMFnfyqgC7RUQHnz6CfnfXKqe3RCUiuZ0wuRaPPLLzmbBhh0Qi7egJqmvFWl6Mx177a3cseVSikhI50QxRnl2zQjcUcUBWXvLf2av+ggBrSb2rLr4+3B2MGUV/5831LH4jDYuLhhYteeq36vODiEE6io/WxOr/V8LCDe44kOoJiKIe0agghGWBVmsEaMAKHLnDKrA885RAEf1ogtXwPlKaMWHD3QCOAWttH2TlRCwzdNLdMr4lrsHUR5CLceQt8zPSSfo9eP6EvvO6HbEfvd2ynbqxEaOlkCrGcQKvMXcSQ0/pefq6LExEJXA8CmukVh4+26vNAh5EpAnS/s7oJCcMHsSxkjvRG9Chn+DoboUCGR/TCum8NDS9f/JjkyElfK+C8vqumEc2RgaeAAHsV2+CXq5Njr0=
The Private Key is
-----BEGIN RSA PRIVATE KEY-----
MIIJKgIBAAKCAgEA2YOAhMmwLjfBddPtLf/Da+Lm1BeUwkg41q/fa5H/NgI8yU0a
GnvydVgP51qCYWlKVRHBf76j56Jbu1NclBd3RFzcBC6SFsyRNPdo3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P2RU301
AtLI9mq6tOm+bEyoVJurSsXCG3EGE1v6cQXDV3OJdJuVtEGCNgNdV1TLulXGfB2A
VduOMMNl4v5v9cSILonMqvOzqL2dPEVyndL8q+z1lOCM40+aKJmw/mHuSE4l/oE5
gf2uYBECK1PI8sH6MAKZFHYyL/tLuYzjyaDIQOFRjZ1YczDGKr6Amt7GqOlDO+oE
rLbJ1wKCAQEAyWX8LmkqzMLgKohmQvWYnwHzUwe7GCNZeCDhl85bEi134dHo7NFr
V2ZHu17EvGwAC52jpdXHZPW6NuXQR5sSYv3rED8zsihsIAB0Gy4x4t1MGWcRWu4a
Ig26x4uVPoekFmtu/+WKu8LMWGsyhCk5mojR7xlnilRDIEqMWWi4GcuCgJqMhLcj
xfYu1qwSZ05ybFOPGsEmNZu+Oyzpp3AHM7o0nhngFLuqTaklaADsahElgDXGv5w7
jC8HVj34WY+o4mEJVfxHVIXvANH1c9Qoafd5guAxjiuJ1s9mITgLNM+VOJT/Kbcp
onGh82MXuB2EBTjeNY8jU+3fLGOsfh3wAwKCAQEAgaEa/6stH6KxGsX36A1mdHUN
4EnOHiMLd8Fv0/Y0dyazlmHr/2/Y6MVTunD1A0jjursrkiH+tcmEYr9crpjp4jBE
5SVh8/iXqeKnS60sUfwKGONUHvfO9hWTGMShqIiD+9TKQ1UUoUuAHfZcBXzDA6EH
RULhpfBlWf3cAxJamHo8JlnPw94Dok7licwUxgCUQRPe7gUrS/5SyFuuRUuSf8SS
AuZxP0QB5DGTtVN7aGw4wsdSPLUve+q03hcFVu/375HE2S5lYbgAQZ2NzXVua6WF
t2rnTjk2EmPjV8Byg7o4Xt7Op5c21reIOuAfh8OQc1m6zqJ8LDiMJ5Cd7eiW2w==
-----END RSA PRIVATE KEY-----
I have a program that encrypts passwords using a c# rsa public key which outputs a byte array.
In order for me to transport it easily and maintain data I am converting the bytes directly to a Hex string. Now this is where I am having issue. I send the post data to my script and am now unsure what to convert it to and how to decrypt it.
I am attempting to use http://phpseclib.sourceforge.net/ which I was pointed to by this post RSA decryption using private key The documentation on this is very vague and I don't know what data/type decrypt() should take.
<?php
include('Crypt/RSA.php');
if (isset($_POST['Password']))
{
$Password = $_POST['Password'];
$crypttext = pack("H*",$Password);
echo $cryptext;
$rsa = new Crypt_RSA();
$rsa->loadKey('key.priv');
$decryptedText =$rsa->decrypt($cryptext);
echo "Pass = >" . $decryptedText;
}
?>
Note that this gives no errors but $decryptedText is empty.
EDIT: Adding more info.
This is my c# encrypt method.
public static string Encrypt(string data, string keyLocation, string keyName)
{
Console.WriteLine("-------------------------BEGIN Encrypt--------------------");
// Variables
CspParameters cspParams = null;
RSACryptoServiceProvider rsaProvider = null;
string publicKeyText = "";
string result = "";
byte[] plainBytes = null;
byte[] encryptedBytes = null;
try
{
// Select target CSP
cspParams = new CspParameters();
cspParams.ProviderType = 1; // PROV_RSA_FULL
rsaProvider = new RSACryptoServiceProvider(2048, cspParams);
// Read public key from Server
WebClient client = new WebClient();
Stream stream = client.OpenRead(keyLocation + "/" + keyName);
StreamReader reader = new StreamReader(stream);
publicKeyText = reader.ReadToEnd();
//
//Console.WriteLine("Key Text : {0}",publicKeyText);
// Import public key
rsaProvider.FromXmlString(publicKeyText);
// Encrypt plain text
plainBytes = Convert.FromBase64String(data);
Console.WriteLine("inputlength : {0}",plainBytes.Length);
encryptedBytes = rsaProvider.Encrypt(plainBytes, false);
result = ByteArrayToString(encryptedBytes);
Console.WriteLine("Encrypted Hex string : {0}", result);
}
catch (Exception ex)
{
// Any errors? Show them
Console.WriteLine("Exception encrypting file! More info:");
Console.WriteLine(ex.Message);
}
rsaProvider.Dispose();
Console.WriteLine("-------------------------END Encrypt--------------------");
return result;
} // Encrypt
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length / 2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hex))
{
for (int i = 0; i < NumberChars; i++)
bytes[i] =
Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
}
return bytes;
}
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
I modified the php to this
<?php
include('Crypt/RSA.php');
if (isset($_POST['Password']))
{
$Password = $_POST['Password'];
$crypttext = pack("H*",$Password);
echo $cryptext;
$rsa = new Crypt_RSA();
$rsa->loadKey(file_get_contents('key.priv')); // Added file_get_contents() which fixed the key loading
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); // Added this which is essential thank you guys/gals
$decryptedText =$rsa->decrypt($cryptext);
echo "Pass = >" . $decryptedText; // gives unsual data. This needs to be converted from binary data to base64string I think
echo "Pass = >" . base64_encode($decryptedText); // gives no data.
echo "Pass = >" . base64_decode($decryptedText); // gives no data.
}
?>
I searched around and tried several things to convert back to text and I have tried base64_encode() and base64_decode() but I get nothing and otherwise I get gobbledey gook.
The final solution was to use imap_binary($decryptedText) to convert back.
Edit :
It has since been brought to my attention that a better way of doing this would be to replace 2 things
C#
plainBytes = Convert.FromBase64String(data);
Changed to
plainBytes = Encoding.UTF8.GetBytes(data);
and PHP
imap_binary($decryptedText)
Changed to
utf8_decode($decryptedText)
I have a problem, I want to encrypt word docs(which have only 10 Kb) using public key, and it must decrypt with private key.
I already created key pair using phpseclib library.
http://phpseclib.sourceforge.net/crypt/examples.html
and I can encrypt and decrypt string using that library. but I don't know how to encrypt file using key pair.
is there any method for this.(or using file_get_contents)
thanks for all
<?php
//create word docx using phpdocx
require("phpDocx.php");
$phpdocx = new phpdocx("word_temp\loan_app_temp.docx");
//assign
$upfno='999';
$loanid_db='1234';
$phpdocx->assign("#upfno#","$upfno");
$phpdocx->assign("#loanid#","$loanid_db");
$phpdocx->assign("#fullname#","$name");
$phpdocx->assign("#initials#","$initials");
$phpdocx->save("word_gen\loan_docs\la_".$upfno."_".$loanid_db.".docx"); // sucessfully created.
// create key pair using phpseclib
set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');
include('phpseclib/Crypt/RSA.php');
$rsa = new Crypt_RSA();
//$rsa->setPassword('layanthi#123');
extract($rsa->createKey());
//echo "$privatekey<br />$publickey";
echo $privatekeydata=$privatekey;
echo '<br />';
echo $pubkey=$publickey; //key pair genarated - ok
//encryption using pubkey - commented snippet from phpseclib
$file="word_gen\loan_docs\la_".$upfno."_".$loanid_db.".docx";
$message=file_get_contents($file);
function rsa_encrypt($key, $message) {
$rsa = new Crypt_RSA();
$rsa->loadKey($key);
$encrypted = base64_encode($rsa->encrypt($message));
return $encrypted;
}
echo $encrypt_file=rsa_encrypt($pubkey, $message);
//from here i want to save encryptted file to encrypt folder like
//$savepath="encrypt\la_".$upfno."_".$loanid_db.".docx"; but i dont know how to do that
//Deryption using phpseclib function is here - but how to use it for above encryption
function rsa_decrypt($key, $package) {
$rsa = new Crypt_RSA();
$rsa->loadKey($key);
$decrypted = $rsa->decrypt(base64_decode($package));
return $decrypted;
}
echo $encrypt_file=rsa_encrypt($pubkey, $message);
$savepath="word_gen\encrypt\la_".$upfno."_".$loanid_db.".docx";
file_put_contents($savepath, $encrypt_file);
//Deryption using phpseclib function is here - but how to use it for above encryption
function rsa_decrypt($key, $package) {
$rsa = new Crypt_RSA();
$rsa->loadKey($key);
$decrypted = $rsa->decrypt(base64_decode($package));
return $decrypted;
}
//get encrypt file
$encfile="word_gen\encrypt\la_".$upfno."_".$loanid_db.".docx";
$epackage=file_get_contents($encfile);
echo $decryptfile= rsa_decrypt($privatekeydata, $epackage);
$savepath_de="word_gen\decrypt\la_".$upfno."_".$loanid_db.".docx";
file_put_contents($savepath_de, $encrypt_file);
?>