I have encrypted a string using EasyCrypto in C# using the following code
Encryption C#:
/*
EasyCrypto encrypted key format from CryptoContainer.cs file from the EasyCrypto source on GitHub.
* Format:
* 04 bytes 00 - MagicNumber
* 02 bytes 04 - DataVersionNumber
* 02 bytes 06 - MinCompatibleDataVersionNumber
* 16 bytes 08 - IV
* 32 bytes 24 - Salt
* 19 bytes 56 - Key check value
* 48 bytes 75 - MAC
* 04 bytes 123 - Additional header data length
* xx bytes 127 - Additional data
* ----- end of header ----- (sum: 127)
* xx bytes - additional header data (0 for version 1)
* xx bytes - data
*/
AesEncryption.EncryptWithPassword("data to encrypt", "password string");
/*
Method Description:
Encrypts string and returns string. Salt and IV will be embedded to encrypted string. Can later be decrypted with
EasyCrypto.AesEncryption.DecryptWithPassword(System.String,System.String,EasyCrypto.ReportAndCancellationToken)
IV and salt are generated by EasyCrypto.CryptoRandom which is using System.Security.Cryptography.Rfc2898DeriveBytes.
IV size is 16 bytes (128 bits) and key size will be 32 bytes (256 bits).
/*
I am trying to decrypt in C++ using Crypto++, using the following code. I am just getting the error "ciphertext length is not a multiple of block size", what is the missing part in the code? any help would be highly appreciable.
Decryption C++:
string Decrypt() {
// getting CryptoPP::byte array from passowrd
string destination;
CryptoPP::StringSource ss(<hex of password string>, true, new CryptoPP::HexDecoder(new CryptoPP::StringSink(destination)));
CryptoPP::byte* keyByteArray = (CryptoPP::byte*)destination.data();
// getting CryptoPP::byte array from encoded data
string pkDst;
CryptoPP::StringSource ss2(<hex of encoded data>, true, new CryptoPP::HexDecoder(new CryptoPP::StringSink(pkDst)));
CryptoPP::byte* pkByteArray = (CryptoPP::byte*)pkDst.data();
// getting initialization vector from encoded data
CryptoPP::byte iv[16];
for (int i = 8; i < 24; i++) {
iv[i] = pkByteArray[i];
}
string result = CBCMode_Decrypt(keyByteArray, 32, iv);
return result;
}
string CBCMode_Decrypt(CryptoPP::byte key[], int keySize, CryptoPP::byte iv[]) {
string recovered = "";
//Decryption
try
{
CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption d;
d.SetKeyWithIV(key, keySize, iv);
// The StreamTransformationFilter removes
// padding as required.
CryptoPP::StringSource s("encoded string", true, new CryptoPP::StreamTransformationFilter(d, new CryptoPP::StringSink(recovered))); // StringSource
}
catch (const CryptoPP::Exception& e)
{
cerr << e.what() << endl;
exit(1);
}
return recovered;
}
In the Crypto++ code, the following steps must be performed for decryption:
Base64 decoding of the EasyCrypto data
Separating IV, salt and ciphertext (using the information from the CryptoContainer.cs file)
Deriving the 32 bytes key via PBKDF2 using salt and password (digest: SHA-1, iteration count: 25000)
Decryption with AES-256 in CBC mode and PKCS#7 padding (using key and IV)
A possible Crypto++ implementation is:
#include "aes.h"
#include "modes.h"
#include "pwdbased.h"
#include "sha.h"
#include "base64.h"
using namespace CryptoPP;
using namespace std;
...
// Base64 decode data from EasyCrypto
string encoded = "bqCrDAQABABtXsh2DxqYdpZc6M6+kGALOsKUHzxoMR6WAVg5Qtj3zWbr4MiEBdqt9nPIiIZAynFAZmweHQPa/PhEItR6M8Jg1bHAYeQ8Cm5eUlKNzPXFNfuUw0+qtds29S0L4wAWY0xfuiBJTUeTJuSLWqoirm/rHGOWAAAAAKtBivUDvxta1d0QXE6J9x5VdSpAw2LIlXARKzmz+JRDtJcaj4KmGmXW/1GjZlMiUA==";
string decoded;
StringSource ssB64(
encoded,
true,
new Base64Decoder(
new StringSink(decoded)
)
);
// Separate IV, salt and ciphertext
string ivStr = decoded.substr(8, 16);
string saltStr = decoded.substr(24, 32);
string ciphertextStr = decoded.substr(127);
// Derive 32 bytes key using PBKDF2
char password[] = "my passphrase";
unsigned int iterations = 25000;
byte key[32];
size_t keyLen = sizeof(key);
PKCS5_PBKDF2_HMAC<SHA1> pbkdf;
pbkdf.DeriveKey(key, keyLen, 0, (byte*)password, sizeof(password), (byte*)saltStr.c_str(), saltStr.length(), iterations, 0.0f);
// Decrypt with AES-256, CBC, PKCS#7 padding
string decrypted;
CBC_Mode<AES>::Decryption decryption(key, keyLen, (byte*)ivStr.c_str());
StringSource ssDec(
ciphertextStr,
true,
new StreamTransformationFilter(
decryption,
new StringSink(decrypted),
BlockPaddingSchemeDef::BlockPaddingScheme::PKCS_PADDING
)
);
// Output
cout << "Decrypted: " << decrypted << "\n";
with the output:
Decrypted: The quick brown fox jumps over the lazy dog
The ciphertext was generated with EasyCrypto:
AesEncryption.EncryptWithPassword("The quick brown fox jumps over the lazy dog", "my passphrase");
The previous section focused on decryption. Note, however, that for security reasons, authentication is required before decryption and decryption may only be performed on successfully authenticated data.
For authentication also the MAC must be determined in addition to IV, salt and ciphertext. EasyCrypto applies an HMAC-SHA-384 as MAC. Only the ciphertext is used to determine the MAC, and the key for authentication is the same as the key for encryption.
For authentication, the calculated and the sent MAC must be compared. If both are the same, the authentication is successful (and the decryption can be performed).
A possible Crypto++ implementation for the authentication is:
// Get the sent MAC
string macSentStr = decoded.substr(75, 48);
// Calculate the MAC using ciphertext and encryption key
string macCalcStr;
HMAC<SHA384> hmac(key, keyLen);
StringSource ssMac(
ciphertextStr,
true,
new HashFilter(hmac,
new StringSink(macCalcStr)
)
);
// Compare both MACs
cout << (!macSentStr.compare(macCalcStr) ? "Authentication successful" : "Authentication failed") << endl; // compare returns 0 if both strings match
which successfully authenticates the sample data.
Related
An encryption C# code that has been in use for many years now needs to be converted to PHP 8.
I came close, and there's one remaining issue as described below:
For example, the secret below is longer than 71 characters and it is not encrypted correctly:
secret = "id=jsmith12×tamp=2022-07-06t11:10:43&expiration=2022-07-06t11:15:43"; //71 chars-long
However, these secrets will be encrypted correctly, since they are less than 71 chars long:
secret = "id=jsmith×tamp=2022-07-06t11:10:43&expiration=2022-07-06t11:15:43"; // 69 chars-long
secret = "id=jsmith1×tamp=2022-07-06t11:10:43&expiration=2022-07-06t11:15:43"; // 70 chars-long
There is an online page where you can test if the generated token is correct: https://www.mybudgetpak.com/SSOTest/
You can evaluate the token by providing the generated token, the key, and the encryption method (Rijndael or Triple DES).
If the evaluation (decryption of the token) is successful, the test page will diplay the id, timestamp and expiration values
used in the secret.
C# Code:
The secret, a concatenated query string values, what needs to be encrypted:
string secret = "id=jsmith123×tamp=2022-07-06t11:10:43&expiration=2022-07-06t11:15:43";
The key:
string key = "C000000000000000"; //16 character-long
ASCII encoded secret and key converted to byte array:
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] encodedSecret = encoding.GetBytes(secret);
byte[] encodedKey = encoding.GetBytes(key);
Option 1: Rijndael
// Call the generate token method:
string token = GenerateRijndaelSecureToken(encodedSecret, encodedKey);
private string GenerateRijndaelSecureToken(byte[] encodedSecret, byte[] encodedKey)
{
Rijndael rijndael = Rijndael.Create();
// the encodedKey must be a valid length so we pad it until it is (it checks // number of bits)
while (encodedKey.Length * 8 < rijndael.KeySize)
{
byte[] tmp = new byte[encodedKey.Length + 1];
encodedKey.CopyTo(tmp, 0);
tmp[tmp.Length - 1] = (byte)'\0';
encodedKey = tmp;
}
rijndael.Key = encodedKey;
rijndael.Mode = CipherMode.ECB;
rijndael.Padding = PaddingMode.Zeros;
ICryptoTransform ict = rijndael.CreateEncryptor();
byte[] result = ict.TransformFinalBlock(encodedSecret, 0, encodedSecret.Length);
// convert the encodedSecret to a Base64 string to return
return Convert.ToBase64String(result);
}
Option 2: Triple DES
// Call the generate token method:
string token = GenerateSecureTripleDesToken(encodedSecret, encodedKey);
private string generateSecureTripleDesToken(byte[] encodedSecret, byte[] encodedKey)
{
// Generate the secure token (this implementation uses 3DES)
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
// the encodedKey must be a valid length so we pad it until it is (it checks // number of bits)
while (encodedKey.Length * 8 < tdes.KeySize)
{
byte[] tmp = new byte[encodedKey.Length + 1];
encodedKey.CopyTo(tmp, 0);
tmp[tmp.Length - 1] = (byte) '\0';
encodedKey = tmp;
}
tdes.Key = encodedKey;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.Zeros;
ICryptoTransform ict = tdes.CreateEncryptor();
byte[] result = ict.TransformFinalBlock(encodedSecret, 0, encodedSecret.Length);
// convert the encodedSecret to a Base64 string to return
return Convert.ToBase64String(result);
}
PHP 8 code:
public $cipher_method = "AES-256-ECB";
// Will not work:
//$secret = "id=jsmith12×tamp=2022-07-06t11:10:43&expiration=2022-07-06t11:15:43";
// Will work:
//$secret = "id=jsmith×tamp=2022-07-06t11:10:43&expiration=2022-07-06t11:15:43";
$key = "C000000000000000";
$token = openssl_encrypt($secret, $cipher_method, $key);
There are two things to be aware of:
The C# code pads the key with 0x00 values to the required length, i.e. 256 bits for AES-256 and 192 bits for 3DES. Since PHP/OpenSSL automatically pads keys that are too short with 0x00 values, this does not need to be implemented explicitly in the PHP code (although it would be more transparent).
The C# code uses Zero padding. PHP/OpenSSL on the other hand applies PKCS#7 padding. Since PHP/OpenSSL does not support Zero padding, the default PKCS#7 padding must be disabled with OPENSSL_ZERO_PADDING (note: this does not enable Zero padding, the name of the flag is poorly chosen) and Zero padding must be explicitly implemented, e.g. with:
function zeropad($data, $bs) {
$length = ($bs - strlen($data) % $bs) % $bs;
return $data . str_repeat("\0", $length);
}
Here $bs is the block size (16 bytes for AES and 8 bytes for DES/3DES).
Further changes are not necessary! A possible implementation is:
$cipher_method = "aes-256-ecb"; // for AES (32 bytes key)
//$cipher_method = "des-ede3"; // for 3DES (24 bytes key)
// Zero pad plaintext (explicitly)
$bs = 16; // for AES
//$bs = 8; // for 3DES
$secret = zeropad($secret, $bs);
// Zero pad key (implicitly)
$key = "C000000000000000";
$token = openssl_encrypt($secret, $cipher_method, $key, OPENSSL_ZERO_PADDING); // disable PKCS#7 default padding, Base64 encode (implicitly)
print($token . PHP_EOL);
The ciphertexts generated in this way can be decrypted using the linked website (regardless of their length).
The wrong padding causes decryption to fail on the web site (at least to not succeed reliably). However, the logic is not correct that decryption fails only if the plaintext is larger than 71 bytes (even if only the range between 65 and 79 bytes is considered). For example, decryption fails also with 66 bytes. The page source provides a bit more information than the GUI:
Could not read \u0027expiration\u0027 as a date: 2022-07-06t11:15:43\u000e\u000e\u000e\u000e\u000e\u000e\u000e\u000e\u000e\u000e\u000e\u000e\u000e\u000e
The problem is (as expected) the PKCS#7 padding bytes at the end: 14 0x0e values for 66 bytes.
Why decryption works for some padding bytes and not for others can only be reliably answered if the decryption logic of the web site were known. In the end, however, the exact reason doesn't matter.
Note that the applied key expansion is insecure. Also, ECB is insecure, 3DES is outdated, and Zero padding is unreliable.
There might be just a minor mistake I have done that I cannot see. Perhaps someone else looking over this could figure out what I am doing wrong.
This is function in C# that I am trying to rewrite in Go, the objective is to output the same value when calling a function.
public static string NewEncrypt(string Input)
{
RijndaelManaged rijndaelManaged = new RijndaelManaged();
rijndaelManaged.KeySize = 256;
rijndaelManaged.BlockSize = 256;
rijndaelManaged.Padding = PaddingMode.PKCS7;
rijndaelManaged.Key = Convert.FromBase64String(Convert.ToBase64String(Encoding.UTF8.GetBytes("095fc90fe8b18e8f243e4b07a9c0d170")));
rijndaelManaged.IV = Convert.FromBase64String(Convert.ToBase64String(Encoding.UTF8.GetBytes("8bef55a546d27958ead1fdddba4d36ea")));
ICryptoTransform transform = rijndaelManaged.CreateEncryptor(rijndaelManaged.Key, rijndaelManaged.IV);
byte[] myArray = null;
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write))
{
byte[] bytes = Encoding.UTF8.GetBytes(Input);
cryptoStream.Write(bytes, 0, bytes.Length);
}
myArray = memoryStream.ToArray();
}
return Convert.ToBase64String(myArray);
}
You can call it using:
NewEncrypt("{\"randJsonList\":[ \"abc\" ], \"name\":\"baron\", \"support\":\"king\"}")
We have this return output (myArray):
DdSUyoYRYW/zDNSVaA1JZ39WqJt06qp0FiJUlCW5BbZWEt41GzsmtgVnGZuHigZNs7qKhI+kHAKMXL8EPnK1vg==
Now for my Go implementation (I was trying to make use of GitHub resources: https://gist.github.com/huyinghuan/7bf174017bf54efb91ece04a48589b22):
First thing you might notice is that I do not know where I can use global IV variable, each time you run this code you are presented with different output. I want to output the same result as in C#, unless the input string is modified
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
)
var KEY = []byte("095fc90fe8b18e8f243e4b07a9c0d170")
var IV = []byte("8bef55a546d27958ead1fdddba4d36ea")
func encrypt(myInput string) []byte {
plaintext := []byte(myInput)
// Create the AES cipher
block, err := aes.NewCipher(KEY)
if err != nil {
panic(err)
}
plaintext, _ = pkcs7Pad(plaintext, block.BlockSize())
// The IV needs to be unique, but not secure. Therefore it's common to
// include it at the beginning of the ciphertext.
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
bm := cipher.NewCBCEncrypter(block, iv)
bm.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
//stream := cipher.NewCFBEncrypter(block, iv)
//stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
return ciphertext
}
// pkcs7Pad right-pads the given byte slice with 1 to n bytes, where
// n is the block size. The size of the result is x times n, where x
// is at least 1.
func pkcs7Pad(b []byte, blocksize int) ([]byte, error) {
if blocksize <= 0 {
return nil, errors.New("invalid blocksize")
}
if b == nil || len(b) == 0 {
return nil, errors.New("invalid PKCS7 data (empty or not padded)")
}
n := blocksize - (len(b) % blocksize)
pb := make([]byte, len(b)+n)
copy(pb, b)
copy(pb[len(b):], bytes.Repeat([]byte{byte(n)}, n))
return pb, nil
}
func main() {
plainText := "{\"randJsonList\":[ \"abc\" ], \"name\":\"baron\", \"support\":\"king\"}"
x := encrypt(plainText)
outputString := base64.StdEncoding.EncodeToString(x)
fmt.Println(outputString)
}
Example output (not the same as C#):
PS D:\Software\Git\repositories\tet> go run .\main.go
N+hm5TItq367eXAz+WbtKXhhhMAy4woEKSngTf6rGUt8GZce7LsUxaqNtheceGDZ2dK8Bx187x87NeRPC1UQ6lUokjy7t1MLU8NcCtjODCM=
PS D:\Software\Git\repositories\tet> go run .\main.go
OT/CngTVs2O4BR4czjvR3MLVPoKFH2dUtW8LsIDUgLXfikJrRKsvKGaf0JFe39Cwf1/00HP7mvmCure7+IO+vupzAtdLX6nTQt1KZGsNp4o=
PS D:\Software\Git\repositories\tet> go run .\main.go
yDRHxWTvjX4HnSW8jbao+0Mhf77zgRj9tKXA3MNtAoF1I3bRou5Sv4Ds+r0HRuiA7NkoBR57m4aCYcU6quYzQA3R0GCGB8TGUfrWS5PvMNU=
The C# code uses Rijndael with a block size of 256 bits (see comments), a static IV (see comments) and returns only the ciphertext (i.e. without prepended IV).
The Go code applies AES with by definition a block size of 128 bits, a randomly generated IV (the static IV in the code is ignored) and returns the concatenation of IV and ciphertext.
AES is a subset of Rijndael. Rijndael defines different block sizes and key sizes between 128 and 256 bits in 32 bit steps, see here. For AES only the block size 128 bits is defined and the key sizes 128, 192 and 256 bits. Note that the standard is AES and not Rijndael, so AES should be preferred over Rijndael (many libraries do not even implement Rijndael, but AES instead).
A static IV is insecure. Key/IV pairs must not repeat for security reasons. Therefore, in general, with a fixed key, a random IV is generated for each encryption. The IV is not secret and is passed along with the ciphertext to the decryption side, typically concatenated in the order IV|ciphertext.
Therefore, the current Go code is a secure implementation (even more secure is authenticated encryption e.g. via GCM), while the C# code is not. So it would make more sense to modify the C# code to be functionally equivalent to the Go code.
However, since the C# code seems to be the reference, the following changes are needed in the Go code to make it functionally identical to the C# code:
Instead of AES, Rijndael must be applied. In the following example, pkg.go.dev/github.com/azihsoyn/rijndael256 is used. To do this, import "github.com/azihsoyn/rijndael256" and formally replace aes with rijndael256. You can of course apply another implementation.
The static IV is to be applied: bm := cipher.NewCBCEncrypter(block, IV).
iv and its filling is to be removed together with associated imports.
Only the ciphertext is returned in the enecrypt()-method: return ciphertext[rijndael256.BlockSize:].
The following Go code gives the result of the C# code:
package main
import (
"bytes"
"github.com/azihsoyn/rijndael256"
"crypto/cipher"
"encoding/base64"
"errors"
"fmt"
)
var KEY = []byte("095fc90fe8b18e8f243e4b07a9c0d170")
var IV = []byte("8bef55a546d27958ead1fdddba4d36ea")
func encrypt(myInput string) []byte {
plaintext := []byte(myInput)
// Create the AES cipher
block, err := rijndael256.NewCipher(KEY)
if err != nil {
panic(err)
}
plaintext, _ = pkcs7Pad(plaintext, block.BlockSize())
// The IV needs to be unique, but not secure. Therefore it's common to
// include it at the beginning of the ciphertext.
ciphertext := make([]byte, rijndael256.BlockSize+len(plaintext))
bm := cipher.NewCBCEncrypter(block, IV)
bm.CryptBlocks(ciphertext[rijndael256.BlockSize:], plaintext)
return ciphertext[rijndael256.BlockSize:]
}
// pkcs7Pad right-pads the given byte slice with 1 to n bytes, where
// n is the block size. The size of the result is x times n, where x
// is at least 1.
func pkcs7Pad(b []byte, blocksize int) ([]byte, error) {
if blocksize <= 0 {
return nil, errors.New("invalid blocksize")
}
if b == nil || len(b) == 0 {
return nil, errors.New("invalid PKCS7 data (empty or not padded)")
}
n := blocksize - (len(b) % blocksize)
pb := make([]byte, len(b)+n)
copy(pb, b)
copy(pb[len(b):], bytes.Repeat([]byte{byte(n)}, n))
return pb, nil
}
func main() {
plainText := "{\"randJsonList\":[ \"abc\" ], \"name\":\"baron\", \"support\":\"king\"}"
x := encrypt(plainText)
outputString := base64.StdEncoding.EncodeToString(x)
fmt.Println(outputString)
}
The output:
DdSUyoYRYW/zDNSVaA1JZ39WqJt06qp0FiJUlCW5BbZWEt41GzsmtgVnGZuHigZNs7qKhI+kHAKMXL8EPnK1vg==
is equal to that of the C# code.
I am trying to implement Speck 32/64 block Cipher in c# I'm stuck at encryption decryption algorithm. i know that i should split the plain text in to 2 word according to algorithm
x,y = plaintext words
--------------------------- key expansion --------------------------
for i = 0..T-2
[i+m-1] ← (k[i] + S−α
[i]) ⊕ i
k[i+1] ← S
β k[i] ⊕ `[i+m-1]
end for
---------------------------- encryption ----------------------------
for i = 0..T-1
x ← (S−α x + y) ⊕ k[i]
y ← S
βy ⊕ x
end for
References
The SIMON and SPECK Families of Lightweight Block Ciphers
https://eprint.iacr.org/2013/404
my question is the plaintext should be string then i convert to binary or what and use it in the above algo?
the algorithm didnot say the type of plaintext and there is example encryption
Key: 1918 1110 0908 0100
Plaintext: 6574 694c
Ciphertext: a868 42f2
SPECK 32/64 cipher expects 4 bytes as the input.
Plaintext: 6574 694c
means
byte[] plaintext = new byte[] {0x65, 0x74, 0x69, 0x4C};
where each byte is specified as hexadecimal value using the 0x prefix.
You will divide the plaintext in the first step:
byte[] x = new byte[] {plaintext[0], plaintext[1]};
byte[] y = new byte[] {plaintext[2], plaintext[3]};
Note: use some more clever array manipulation to speed up your cipher, the example above is for educational purposes only.
Note 2: handling input as a uint might be a good approach, it could be much faster than arrays with a little of bitwise magic:
uint plaintext = 0x6574694C;
ushort x = (ushort) (plaintext >> 16);
ushort y = (ushort) plaintext;
I am using this function to change public key and encrypt data:
public byte[] EncryptData(byte[] data2Encrypt)
{
string key = "109120132967399429278860960508995541528237502902798129123468757937266291492576446330739696001110603907230888610072655818825358503429057592827629436413108566029093628212635953836686562675849720620786279431090218017681061521755056710823876476444260558147179707119674283982419152118103759076030616683978566631413";
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
BigInteger intk;
BigInteger.TryParse(key, out intk);
RSAParameters privateKey = new RSAParameters();
byte[] expont = { 1, 0, 1 };
byte[] modulus = intk.ToByteArray();
Logger.log(Log_Type.ERROR, "Pierwszy bit: " + modulus[0]);
privateKey.Exponent = expont;
privateKey.Modulus = intk.ToByteArray();
rsa.ImportParameters(privateKey);
return rsa.Encrypt(data2Encrypt, false);
}
But it return me array with 129 length instead od 128 (What should be max lenght using 1024 bits i think). What can be a reason?
If you use BigInteger an additional bit is always placed before the
number. If your key has 1024 bits you get 1025 bits, so skip the
first byte if it is 0x00 (meaning a positive value)
BigInteger produces signed little-endian numbers, while RSAParameters requires unsigned big-endian. You can still use BigInteger though, just convert its output to what RSAParameters is expecting.
byte[] modulus = intk.ToByteArray().Reverse().Skip(1).ToArray();
Reverse to make the number big-endian, and Skip(1) to skip the sign.
I am not sure, that it should be even converted into BitInteger. RSA key what I am trying to get is similar to this function in C++
void Crypt::rsaSetPublicKey(const std::string& n, const std::string& e)
{
BN_dec2bn(&m_rsa->n, n.c_str());
BN_dec2bn(&m_rsa->e, e.c_str());
// clear rsa cache
if(m_rsa->_method_mod_n) { BN_MONT_CTX_free(m_rsa->_method_mod_n); m_rsa->_method_mod_n = NULL; }
}
Where 'n' is this key srting and 'e' is : "65537"
If it should not be a BigInteger, then what?
I'm trying to encrypt a byte array in C# using AES192 and a PBKDF2 password/salt based key and decrypt the same data in NodeJS. However my key generation produces different results in both NodeJS and C#.
The C# code is as follows:
private void getKeyAndIVFromPasswordAndSalt(string password, byte[] salt, SymmetricAlgorithm symmetricAlgorithm, ref byte[] key, ref byte[] iv)
{
Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt);
key = rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.KeySize / 8);
iv = rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.BlockSize / 8);
}
private byte[] encrypt(byte[] unencryptedBytes, string password, int keySize)
{
RijndaelManaged aesEncryption = new RijndaelManaged();
aesEncryption.KeySize = keySize;
aesEncryption.BlockSize = 128;
byte[] key = new byte[keySize];
byte[] iv = new byte[128];
getKeyAndIVFromPasswordAndSalt(password, Encoding.ASCII.GetBytes("$391Ge3%£2gfR"), aesEncryption, ref key, ref iv);
aesEncryption.Key = key;
aesEncryption.IV = iv;
Console.WriteLine("iv: {0}", Convert.ToBase64String(aesEncryption.IV));
Console.WriteLine("key: {0}", Convert.ToBase64String(aesEncryption.Key));
ICryptoTransform crypto = aesEncryption.CreateEncryptor();
// The result of the encryption and decryption
return crypto.TransformFinalBlock(unencryptedBytes, 0, unencryptedBytes.Length);
}
The NodeJS code reads like this:
crypto.pbkdf2("Test", "$391Ge3%£2gfR", 1000, 192/8, (err, key) => {
var binkey = new Buffer(key, 'ascii');
var biniv = new Buffer("R6taODpFa1/A7WhTZVszvA==", 'base64');
var decipher = crypto.createDecipheriv('aes192', binkey, biniv);
console.log("KEY: " + binkey.toString("base64"));
var decodedLIL = decipher.update(decryptedBuffer);
console.log(decodedLIL);
return;
});
The IV is hardcoded as I can't figure out how to calculate that using pbkdf2. I've looked through the nodeJS docs for more help but I'm at a loss as to what's going on here.
Any assistance would be greatly appreciated.
One of the issues I see is the encoding of the pound sign (£). crypto.pbkdf2 encodes the password and salt to a binary array by default, where each character is truncated to the lowest 8 bits (meaning the pound sign becomes the byte 0xA3).
However, your C# code converts the salt to ASCII, where each character is truncated to the lowest 7 bits (meaning the pound sign becomes the byte 0x23). Also it uses the Rfc2898DeriveBytes constructor that takes a String for the password. Unfortunately, the documentation doesn't say what encoding is used to convert the string to bytes. Fortunately, Rfc2898DeriveBytes does have another constructor that takes a byte array for the password and also takes an iteration count parameter, here 1000.
Accordingly, you should convert the password and salt strings to byte arrays by truncating each character to 8 bits, just like Node.js does by default. Here is an example:
var bytes=new byte[password.Length];
for(var i=0;i<bytes.Length;i++){
bytes[i]=(byte)(password[i]&0xFF);
}