So, I have some encryption/decryption issues …
I encrypt data in javascript thanks to node-forge and I try to decrypt it into PHP thanks to openssl_private_decrypt.
On the PHP side, I use the «OPENSSL_PKCS1_OAEP_PADDING» padding. So, on the javascript side I tried to configure forge to encrypt data with RSA-OAEP.
And when I try to decsypt the message on the PHP side, I have these errors :
error:04099079:rsa routines:RSA_padding_check_PKCS1_OAEP_mgf1:oaep decoding error
error:04065072:rsa routines:rsa_ossl_private_decrypt:padding check failed
I've tried to configure the encryption with sha1 message digest and sha1 for mgf1 option. I've also tried without any option (if I remember, forge use SHA256 by default). But there is nothing to do, I always have the same error …
javascript
const pubkey = `-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----
`;
const privkey = `-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----
`;
let publicKey = forge.pki.publicKeyFromPem(pubkey);
let key = forge.random.getBytesSync(32);
let encKey = publicKey.encrypt(key, 'RSA-OAEP', {
md: forge.md.sha1.create(),
mgf1: {
md: forge.md.sha1.create()
}
});
let b64Key = encodeURIComponent(btoa(enckey));
Next, I send the key in url with the "xcem" param, thanks to HttpClient. And I receive it in PHP.
php
$privKey = "";
$b64Key = urldecode($_GET['xcem']);
$encKey = base64_decode($b64Key);
$key = null;
if (!openssl_private_decrypt($encKey, $key, file_get_contents('/keys/openssl_private.key'), OPENSSL_PKCS1_OAEP_PADDING))
{
$errorssl = [];
while ($error = openssl_error_string()) {
$errorssl[] = $error;
}
throw new Exception("Erreur lors du décryptage du message ! " . json_encode($errorssl));
}
When I send Data between 2 PHP servers, there is no problem …
But I can't make it work between JS and PHP … I need some help ^^
Sooo …
After some tests, and headaches I found the problem … In my original code (not the one here) I sent the key, the init vector, the signature and the encrypted data …
But in my PHP, I tried to decode the signature … I didn't send data in the right order …
My bad …
Related
I have a code for encrypting and decrypting in Java as such
public static String decrypt(String strToDecrypt, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(base64Decode(strToDecrypt)));
}
public static String encrypt(String strToEncrypt, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return base64Encode(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
I tried to encrypt the data in forge js, and decrypt it using Java. All I get is
Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
function aesEncrypt(data, secretKey) {
var cipher = forge.cipher.createCipher('AES-ECB', secretKey)
cipher.start()
cipher.update(forge.util.createBuffer(data))
cipher.finish()
return forge.util.encode64(cipher.output.data)
}
function aesDecrypt(data, secretKey) {
var decipher = forge.cipher.createDecipher('AES-ECB', secretKey)
decipher.start()
decipher.update(forge.util.createBuffer(forge.util.decode64(data)))
decipher.finish()
return decipher.output.data
}
Is there a way to solve this?
Below is the way I generate my key. It is 32 length alphanumeric string.
The secret key is sent in the request itself (Symmetric enc).
SecretKey secretKey = AESEncryptionUtil.generateSecretKey();
public static SecretKey generateSecretKey() throws Exception {
String secretStr = RandomGenerator.getAlphaNumericString(32);
log.info("Generated secret key : {}", secretStr);
byte[] decodeSecretKey = base64Decode(secretStr);
return new SecretKeySpec(decodeSecretKey, 0, decodeSecretKey.length, "AES");
}
The data is then encrypted. Now in JS, it is done as below
function generateSecret(length) {
var result = ''
var characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
var charactersLength = characters.length
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength))
}
return result
}
let aesEncryptedData = aesEncrypt(data, generateSecret(32))
I tried to debug it. I get the plain secret key as it is. The signature is also verified. But the data is not decrypted. I am confused if the Java's SecretKey Interface behaves differently, as in JS I use the plain secret key itself, while in Java I use the SecretKey.
The main problem will be (without seeing more code with a full running example) that you need to use the same generated secretKey on both side (encryption and decryption). As you simply use the output of generateSecret(32) as input for your aesEncrypt-function you do not have access to the same key on decryption side.
let aesEncryptedData = aesEncrypt(data, generateSecret(32))
This is even more important when changing the platforms (javascript to Java). Below you find an example code in Java that takes the data of your encryption part (Javascript) and uses it for decryption.
Security warning: the code is UNSECURE as it uses AES in unsecure mode ECB. The codes does not have any exception handling and is for
educational purpose only.
output:
Is there a difference in generating Secret Key in Java (SecretKey Interface) and forge?
generatedSecret: Mwhq5YXBY6d7zUUbQbVxsJeXvuOz7Sqp
aesEncryptedData: 2TxS64Eku0yO7Na7WwEWinnVwkzrbv2yTIdRA/cW5VURtuTdCyud0Bo4orxP1+ky
decryptedString: The quick brown fox jumps over the lazy dog
code:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class MainSo {
public static void main(String[] args) throws Exception {
System.out.println("Is there a difference in generating Secret Key in Java (SecretKey Interface) and forge?");
String generatedSecret = "Mwhq5YXBY6d7zUUbQbVxsJeXvuOz7Sqp";
String aesEncryptedData = "2TxS64Eku0yO7Na7WwEWinnVwkzrbv2yTIdRA/cW5VURtuTdCyud0Bo4orxP1+ky";
SecretKey secretKey = new SecretKeySpec(generatedSecret.getBytes(StandardCharsets.UTF_8), "AES");
String decrypt = decrypt(aesEncryptedData, secretKey);
System.out.println("generatedSecret: " + generatedSecret);
System.out.println("aesEncryptedData: " + aesEncryptedData);
System.out.println("decryptedString: " + decrypt);
}
public static String decrypt(String strToDecrypt, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
//return new String(cipher.doFinal(base64Decode(strToDecrypt)));
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
}
I have a PHP application which can communicate with other PHP applications.
Theses apps exchange encrypted data.
A central app knows all public keys of other apps.
And other apps only know the public key of the central app.
The data are encrypted thanks to the openssl_seal PHP method.
And there are decrypted thanks to the openssl_open PHP method.
I use the "AES256" cypher method and generate an "iv" element.
In PHP no problem at all, everything is for the best in the best of all possible worlds …
But, now, I would like to do the same with an Ionic app (based on cordova and Angular 5).
I tried to use JSEncrypt and CryptoJS, but PHP dos not explain how openssl_seal works and I have some trouble to export my PHP code into Javascript one …
function encrypt($message)
{
$envKeys = [];
$encMessage = '';
$pubKey = "-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----
";
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES256'));
if (openssl_seal($message, $encMessage, $envKeys, [$pubKey], 'AES256', $iv) === false) {
throw new Exception("Erreur lors du cryptage du message !");
}
return [base64_encode($encMessage), base64_encode($envKeys[0]), base64_encode($iv)];
}
function decrypt($messageCrypte, $key, $iv)
{
$privateKey = "-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----
";
$message = '';
openssl_open(base64_decode($messageCrypte), $message, base64_decode($key), $privateKey, 'AES256', base64_decode($iv));
return $message;
}
$crypted = encrypt('Test');
$embed = "<script>var encrypted = '$crypted[0]'; var envelope = '$crypted[1]'; var iv = '$crypted[2]'; </script>";
<html>
<head>
<script type="text/javascript" src="crypto-js.js"></script>
<script type="text/javascript" src="jsencrypt.js"></script>
<?php echo $embed; ?>
<script>
var private_key = `-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----
`;
var crypt = new JSEncrypt();
crypt.setPrivateKey(private_key);
var theKey = CryptoJS.enc.Utf8.parse(crypt.decrypt(envelope));
console.log('The key', theKey);
console.log('ciphertext', CryptoJS.enc.Base64.parse(encrypted));
var decrypted = CryptoJS.AES.decrypt(
{ciphertext: CryptoJS.enc.Base64.parse(encrypted)},
theKey,
{iv: CryptoJS.enc.Base64.parse(iv)}
);
console.log('Decrypted', decrypted.toString());
</script>
</head>
<body>
</body>
</html>
I don't have the original message "Test" … Only empty string …
I would like to be able to make an openssl_seal (like the PHP one) method in JS and an openssl_open (like the PHP one) using CryptoJS and JSEncrypt.
I think it's possible, maybe someone already did that …
Edit
If someone is interested by this problem, I maybe found a lead : http://geekswithblogs.net/Strenium/archive/2013/01/27/converting-phprsquos-ldquoopenssl_sealrdquo-and-ldquoopenssl_openrdquo-into-.net.aspx
It is for .NET but it's a start …
I'm trying to
generate sign/verification keys (RSA)
sign a value (using those keys) on a Java web application (lets call server-side)
in order to a web client to verify - public-key imported as RSASSA-PKCS1-v1_5 + SHA-256, (in a browser, using WebCrypto API / client-side)
I'm having problems verifying the signed value (signed in the Java server-side) even though the public sign/verify key is successfully imported as a JWK in the client side.
I was wondering if there is any algorithm compatibility issue in any of the steps (OpenSSL, Java or Javascript) that I may be encountering.
The OpenSSL commands used to generate the keys
openssl genrsa -out privatekey.pem 2048
openssl rsa -in privatekey.pem -pubout > publickey.pub
openssl pkcs8 -topk8 -inform PEM -outform DER -in privatekey.pem -out privatekey-pkcs8.pem
Importing keys with Java (server-side)
public static KeyPair generateSignKeyPair() throws ... {
byte[] privBytes = b64ToByteArray(PRIVATE_KEY_PEM_VALUE);
byte[] pubBytes = b64ToByteArray(PUBLIC_KEY_PEM_VALUE);
// private key
KeySpec keySpec = new PKCS8EncodedKeySpec(privBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
// public key (javaPubSignKey)
X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(pubBytes);
PublicKey publicKey = keyFactory.generatePublic(X509publicKey);
return new KeyPair(publicKey, privateKey);
}
Signing a value with Java (server-side)
public static byte[] generateSignature(PrivateKey signPrivateKey, byte[] data) throws ... {
Signature dsa = Signature.getInstance("SHA256withRSA");
dsa.initSign(signPrivateKey);
dsa.update(data);
return dsa.sign();
}
Send them to a web-app for the WebCrypto API to verify as a client/browser (the client is aware of the publicKey generated in the first step).
// Import public sign/verify key (javaPubSignVerifyKey)
var signatureAlgorithm = {
name: 'RSASSA-PKCS1-v1_5',
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: {
name: 'SHA-256'
}
};
// JWK format (1)
crypto.subtle.importKey(
'jwk', javaPubSignVerifyKey, signatureAlgorithm, false, ['verify']
).then(success, error);
function success(key) {
signatureVerifyPublicKey = key;
}
Note (1): on the Java side, I'm using com.nimbusds.jose.jwk.JWK to export the publicKey to JWK format.
The sign key is successfully imported by WebCrypto. But when it comes to the verification, it fails (the verification boolean is false).
crypto.subtle.verify(
signatureAlgorithm,
signatureVerifyPublicKey,
signature, // bytes in Int8Array format (2)
data // bytes in Int8Array format
).then(
function (valid) {
// valid === false
}
)
Note (2): also note that every example I found on WebCrypto used Uint8Array to represent byte arrays, but since Java generates signed byte-arrays I need to use Int8Array so that the signature values are not contaminated (maybe this is an issue aswell).
EDIT: for reference, it turned out to be another unrelated issue - I was converting the expected data from base64 twice in Javascript without noticing it; naturally the verification failed.
Please, check this simple code based on yours to import a RSA public key (spki) and verify a signature. I have generated the keys and signature using similar Java code
var publicKeyB64 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDVdZDEs6htb3oxWstz7q+e5IwIRcptMNJiyemuoNyyjtiOy+0tEodjgo7RVoyUcGU3MysEivqvKdswQZ4KfwQCBLAR8DRzp3biAge5utZcKsQoQaC1rCEplfmzEo5ovIlBcMq5x1BxnrnlwEPRmM7MefRa+OeAOQJcstHcrJFO7QIDAQAB";
var dataB64 = "aGVsbG8=";
var signatureB64 = "aEOmUA7YC5gvF6QgH+TMg0erY5pzr83nykZGFtyGOOe+6ld+MC4/Qdb608XiNud+pBpzh0wqd6aajOtJim5XEfCH8vUPsv45aSPtukUIQTX00Oc1frIFDQI6jGJ4Q8dQYIwpqsyE2rkGwTDzt1fTTGiw54pLsJXjtL/D5hUEKL8=";
var signatureAlgorithm = {name: 'RSASSA-PKCS1-v1_5',modulusLength: 2048, publicExponent: new Uint8Array([0x01, 0x00, 0x01]),hash: { name: 'SHA-256' }};
//convert public key, data and signature to ArrayBuffer.
var publicKey = str2ab(atob(publicKeyB64));
var data = str2ab(atob(dataB64));
var signature = str2ab(atob(signatureB64));
crypto.subtle.importKey("spki", publicKey, signatureAlgorithm, false,["verify"]).
then(function(key){
console.log(key);
return crypto.subtle.verify( signatureAlgorithm, key, signature, data);
}).then( function (valid) {
console.log("Signature valid: "+valid);
}).catch(function(err) {
alert("Verification failed " + err );
});
I could not reproduce exactly the issue. Using the str2ab utility function you have linked, the code works perfectly.
//Utility function
function str2ab(str) {
var arrBuff = new ArrayBuffer(str.length);
var bytes = new Uint8Array(arrBuff);
for (var iii = 0; iii < str.length; iii++) {
bytes[iii] = str.charCodeAt(iii);
}
return bytes;
}
I suggest to compare both codes to find the differences
So I've been trying to use node with node-rsa and javascript with jsencrypt to create a website (for an assignment) where the javascript client gets the public key generated by the server (node-rsa), encrypts the message (jsencrypt) that the user has entered, sends it to the server and gets the server to decrypt it (node-rsa). The generation of the keys works, the encryption works however the decryption doesn't. When I start the node script I do the following for the encryption...
var NodeRSA = require('node-rsa');
var myDecrypter = new NodeRSA({b: 512});
When the client requests the key (I am using express) the following is ran.
app.get('/getPublicKey', function(req, res){
var publicKeyJson = {"Key": ""};
console.log(myDecrypter.exportKey('public'));
publicKeyJson.Key = myDecrypter.exportKey('public');
res.json(JSON.stringify(publicKeyJson));
});
The client then saves that key like this...
var myEncrypter = new JSEncrypt();
var myJson = "";
$.getJSON( "getPublicKey", function( data ) {
myJson = JSON.parse(data).Key;
setKey();
});
function setKey() {
myEncrypter.setPublicKey(myJson);
}
When I got to encrypt and send the message on the client I do this...
function messageEncrypt() {
message = document.getElementById("message").value;
var encrypted = myEncrypter.encrypt(message);
myMessage = {"username": "", "userId": 0.0, "message": ""};
myMessage.username = me.username;
myMessage.userId = me.userId;
myMessage.message = encrypted;
console.log(encrypted);
$.post("sendMessage", myMessage);
}
When the server receives a message this is what happens, this is where I get the errors.
app.post('/sendMessage', function(req, res){
var message = req.body;
var user = message.username;
var id = message.userId;
console.log("What a mess, " + user + " said " + message.message + " what on earth does that mean");
//This line below errors
var clearMessage = myDecrypter.decrypt(message.message, 'utf8');
console.log(user + " said " + clearMessage);
});
The error I get is ...
Error: Error during decryption (probably incorrect key). Original error: Error: error:040A1079:rsa routines:RSA_padding_check_PKCS1_OAEP_mgf1:oaep decoding error
at Error (native)
at NodeRSA.module.exports.NodeRSA.$$decryptKey (/home/node_modules/node-rsa/src/NodeRSA.js:295:19)
at NodeRSA.module.exports.NodeRSA.decrypt (/home/node_modules/node-rsa/src/NodeRSA.js:243:21)
at /home/securechat/securechat.js:36:36
at Layer.handle [as handle_request] (/home/node_modules/express/lib/router/layer.js:95:5)
at next (/home/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/home/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/node_modules/express/lib/router/layer.js:95:5)
at /home/node_modules/express/lib/router/index.js:277:22
at Function.process_params (/home/node_modules/express/lib/router/index.js:330:12)
Here however is where it gets interesting, to get that error message above I had a private key of...
-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBAIhdx31QICGN1LKRW4WngeL3RtzPh7cEHmhFJB8m4bQUSTcSi4eg
sUvMeZkWyaF9gOxtZKzk5TI6q+8hg8TY6S8CAwEAAQJASds423cVH/c4NsqhXh8e
KvYwjBFeeNIjQegIq1KctbHmKNM5MMb4jnDqdY/S5XHHS22EGvLNheLgV8tlRjwG
UQIhANpNmbl215eOsGPJ0jqz1XPMBrO35V6I3P04kvr66R1JAiEAn+oL0jtAFETR
4PRfenye5MAu9US3V5MoDN8xUoEvKrcCIQDQT2ZWNNIrHAyzXB2QyJPxqInoqp1j
5QPDWl3ewtj5iQIgY3E1nKw/stsA8LTGUvMAFBv2l4r9wDXAaBC7KSUwYY0CIAj4
0gA9etDbPm3H/XDwK4WXs9mXkKroyxewkWoOoAw/
-----END RSA PRIVATE KEY-----
and the public key sent to the client was...
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIhdx31QICGN1LKRW4WngeL3RtzPh7cE
HmhFJB8m4bQUSTcSi4egsUvMeZkWyaF9gOxtZKzk5TI6q+8hg8TY6S8CAwEAAQ==
-----END PUBLIC KEY-----
The encrypted messages (stackoverflow) was ...
XDViV0InCSnpyBxbNu5Herut0JYSsp87buvhzM4g2f9z3khIx2zA8Ou0Uq0TtmqtvBBVtZi5wZbcS6em/vB78g==
The interesting thing is that when I used the demo on jsencrypt website and enter my private key as well as the encrypted message I get the correct decrypted message.
So my question is...
What am I doing wrong with my node-rsa decryption???
If you need anymore information/code please put it in the comments below.
To answer your question #Curious_Programmer be default node-rsa uses pkcs1_oaep for encryption and decryption while jsencrypt uses pkcs1. Thankfully node lets you change the encryptionScheme, what you need to do is add ...
myDecrypter.setOptions({encryptionScheme: 'pkcs1'});
under
var myDecrypter = new NodeRSA({b: 512});
and all will work like a charm, I hoped I helped you ;)
It seems that the ciphertext is a buffer, i.e. binary data. Then it is transported using JSON, which consists of text. You need to use a text encoding over the binary data to transport it over a text based interface.
Check the following definition of the encrypt method:
key.encrypt(buffer, [encoding], [source_encoding]);
with the reminder that the default is 'buffer' for [encoding].
So you should be using:
var encrypted = myEncrypter.encrypt(message, 'base64', 'utf-8');
where 'base64' is for the ciphertext encoding and 'utf-8' is for the plaintext encoding.
The decryption routine should automatically use base64 decoding of the ciphertext:
var clearMessage = myDecrypter.decrypt(message.message, 'utf8');
should be just fine.
I had the same issue.
encrypt.setOptions({encryptingScheme:'pkcs1'}); //Can be 'pkcs1_oaep' or 'pkcs1'. Default 'pkcs1_oaep'.
But, it still failed.
I have changed the lib from node-rsa to ursa, like this:
privateKey.decrypt(thirdEncrypted, 'base64', 'utf8',ursa.RSA_PKCS1_PADDING);
The problem has been resolved in ursa.
I'm using the following Encrypt / Decrypt in my C# WCF:
public static string EncryptString(string InputText, string Password)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Padding = PaddingMode.ISO10126;
if (string.IsNullOrEmpty(Password) == true)
{
Password = "Test";
}
byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(InputText);
byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
//This class uses an extension of the PBKDF1 algorithm defined in the PKCS#5 v2.0
//standard to derive bytes suitable for use as key material from a password.
//The standard is documented in IETF RRC 2898.
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
//Creates a symmetric encryptor object.
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
MemoryStream memoryStream = new MemoryStream();
//Defines a stream that links data streams to cryptographic transformations
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
cryptoStream.Write(PlainText, 0, PlainText.Length);
//Writes the final state and clears the buffer
cryptoStream.FlushFinalBlock();
byte[] CipherBytes = memoryStream.ToArray();
memoryStream.Close();
memoryStream = null;
cryptoStream.Close();
cryptoStream = null;
PlainText = null;
Salt = null;
try
{
GC.Collect();
}
catch { }
return Convert.ToBase64String(CipherBytes);
}
public static string DecryptString(string InputText, string Password)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Padding = PaddingMode.ISO10126;
if (string.IsNullOrEmpty(Password) == true)
{
Password = "Test";
}
byte[] EncryptedData = Convert.FromBase64String(InputText);
byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
//Making of the key for decryption
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
//Creates a symmetric Rijndael decryptor object.
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
MemoryStream memoryStream = new MemoryStream(EncryptedData);
//Defines the cryptographics stream for decryption.THe stream contains decrpted data
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
byte[] PlainText = new byte[EncryptedData.Length];
int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
memoryStream.Close();
memoryStream = null;
cryptoStream.Close();
cryptoStream = null;
Salt = null;
try
{
GC.Collect();
}
catch { }
//Converting to string
return Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
}
Now, I'm trying to use Java script to fit, want Encrypt data in my web and be able to Decrypt the data in my WCF, I tried to use this script but not work, where I can find Javascript or both JS & .Net sample ?
get the following error:{"Length of the data to decrypt is invalid."}
Thanks.
Ok, if I understand correctly, you want to encrypt a username/password in javascript in a browser in order to safely transport the data to a WCF service. And to accomplish this, you are using AES (symmetric) encryption on both sides.
If that is correct, then you should really be using SSL. Why? Because SSL does this, but much better. In simple terms, SSL will negotiate an AES key after authenticating the public key of an RSA key. So you get the added benefit of the client javascript knowing for sure that it is speaking to the correct server.
What I think is wrong with the roll-your-own AES approach is that at the very least, you have to expose your key (without the public key authentication step) to the client javascript. This means that you are instantly subverting the security, because anyone with that key can now send data to the server.
If I have misunderstood, then perhaps there is an appropriate time to do this, however, at the moment, I don't see one.
Hope this helps.