We need to take Modulus and exponent from RSA keys. I have created my pubilc key using following methodology. Please let me know how can we take modulus and exponent part from it. I have already read this post.
NSData* tag = [#"com.x.x.x" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* attributes =
#{ (id)kSecAttrKeyType: (id)kSecAttrKeyTypeRSA,
(id)kSecAttrKeySizeInBits: #1024,
(id)kSecPrivateKeyAttrs:
#{ (id)kSecAttrIsPermanent: #YES,
(id)kSecAttrApplicationTag: tag,
},
};
CFErrorRef error = NULL;
SecKeyRef privateKey = SecKeyCreateRandomKey((__bridge CFDictionaryRef)attributes,
&error);
if (!privateKey) {
NSError *err = CFBridgingRelease(error);
// Handle the error. . .
}
SecKeyRef publicKey = SecKeyCopyPublicKey(privateKey);
// Now I want modulus and exponent form this publicKey
EDITED :-
I have also send base64 string to server but there we are facing quite a issue to find public key ref from base64 string. if someone has done it in c#, you can also help us with this
c# code snippet
const string pKey = "-----key-----"
byte[] publicKeyBytes = Convert.FromBase64String(pKey);
var stream = new MemoryStream(publicKeyBytes);
Asn1Object asn1Object = Asn1Object.FromStream(stream);
Now we need public key component which we are unable to parse. Any help would be great
On C# you can achieve the encryption using this way,
const string publicKey = "MIGJAoGBAMIt95f4xaP7vYV/+Hdyb4DK0oKvw495PrRYG3nsYgVP7zlBE/rTN6Nmt69W9d0nGefuRlJFIr9TA8vlJmqTus6uXEasBuEjzH7vM7HQeAK6i8qEbVy0T+Uuq+16yy059NL7i/VWljVE6rqTntDUELmbIwNBwj6oBuL1z3SnFoMjAgMBAAE="; //generated on iOS
byte[] publicKeyBytes = Convert.FromBase64String(pKey);
var stream = new MemoryStream(publicKeyBytes);
Asn1Object asn1Object = Asn1Object.FromStream(stream);
Asn1Encodable asn1Sequence = asn1Object;
AlgorithmIdentifier algorithmIdentifier = new
AlgorithmIdentifier(PkcsObjectIdentifiers.IdRsaesOaep);
SubjectPublicKeyInfo subjectPublicKeyInfo = new
SubjectPublicKeyInfo(algorithmIdentifier, asn1Sequence);
AsymmetricKeyParameter asymmetricKeyParameter2 =
PublicKeyFactory.CreateKey(subjectPublicKeyInfo);
RsaKeyParameters rsaKeyParameters =
(RsaKeyParameters)asymmetricKeyParameter2;
RSAParameters rsaParameters = new RSAParameters();
rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);
string test = "John snow is the true king";
byte[] encbyte = rsa.Encrypt(Encoding.UTF8.GetBytes(test), RSAEncryptionPadding.Pkcs1);
string encrt = Convert.ToBase64String(encbyte);
Related
I need to encrypt my steam login password. Before sending the auth data, steam sends this: "publickey_mod":"c511d72db5ebbba01977983eec2...","publickey_exp":"010001".
The browser encrypts password with this script:
var pubKey = RSA.getPublicKey(results.publickey_mod, results.publickey_exp);
password = password.replace(/[^\x00-\x7F]/g, ''); // remove non-standard-ASCII characters
var encryptedPassword = RSA.encrypt(password, pubKey);
I can't write a working algorithm in c# which will encrypt the password using modulus and exponent.
Here is what i tried:
static async Task Main()
{
var pubKey = SetPublicKey($"{response["publickey_mod"]}", $"{response["publickey_exp"]}");
string password = "123456";
byte[] password_byte = Encoding.ASCII.GetBytes(password);
byte[] encryptedPassword;
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSA.ImportParameters(pubKey);
encryptedPassword = RSA.Encrypt(password_byte, false);
}
string encodingPassword = Convert.ToHexString(encryptedPassword);
Console.WriteLine(encodingPassword);
}
public static RSAParameters SetPublicKey(string modulus, string exponent)
{
RSAParameters result = new RSAParameters();
result.Modulus = Convert.FromHexString(modulus);
result.Exponent = Convert.FromHexString(exponent);
return result;
}
working algorithm:
byte[] encryptedPasswordBytes;
using (var rsaEncryptor = new RSACryptoServiceProvider())
{
var passwordBytes = Encoding.ASCII.GetBytes(password);
var rsaParameters = rsaEncryptor.ExportParameters(false);
rsaParameters.Exponent = Convert.FromHexString($"{_response_getrsakey["publickey_exp"]}");
rsaParameters.Modulus = Convert.FromHexString($"{_response_getrsakey["publickey_mod"]}");
rsaEncryptor.ImportParameters(rsaParameters);
encryptedPasswordBytes = rsaEncryptor.Encrypt(passwordBytes, false);
}
string encryptedPassword = Convert.ToBase64String(encryptedPasswordBytes);
the next unit test export a privatekey and save it in bytes arrays using the rsa instance then encrypt the "hi" message, all is fine here, but the problem occur when It make rsa2 instance and import the previous privatekey in RSAParameter, then message can be decrypt after import privatekey, but It throw exception when you try to export privatekey of rsa2.
Please could you tell me why It can't extract Imported Private key
[TestMethod]
public void TestRsa()
{
var rsa = new RSACng(2048);
///Export private key to arrays
var rsaParam = rsa.ExportParameters(true);
byte[] yQ = new byte[rsaParam.Q.Length];
byte[] yP = new byte[rsaParam.P.Length];
byte[] yInverseQ = new byte[rsaParam.InverseQ.Length];
byte[] yDP = new byte[rsaParam.DP.Length];
byte[] yDQ = new byte[rsaParam.DQ.Length];
//Public Part Key
byte[] yPm = new byte[rsaParam.Modulus.Length];
byte[] yPe = new byte[rsaParam.Exponent.Length];
byte[] yD = new byte[rsaParam.D.Length];
rsaParam.Q.CopyTo(yQ, 0);
rsaParam.P.CopyTo(yP, 0);
rsaParam.InverseQ.CopyTo(yInverseQ, 0);
rsaParam.DP.CopyTo(yDP, 0);
rsaParam.DQ.CopyTo(yDQ, 0);
rsaParam.Modulus.CopyTo(yPm, 0);
rsaParam.Exponent.CopyTo(yPe, 0);
rsaParam.D.CopyTo(yD, 0);
var encrypt = rsa.Encrypt(Encoding.UTF8.GetBytes("hi"), RSAEncryptionPadding.Pkcs1);
///Importing private key in another instance of RSACng
var rsa2 = new RSACng(2048);
RSAParameters rsaParameters = new RSAParameters()
{
Q = yQ,
P = yP,
InverseQ = yInverseQ,
DP = yDP,
D = yD,
DQ = yDQ,
Exponent = yPe,
Modulus = yPm
};
rsa2.ImportParameters(rsaParameters);
var decryptData = rsa2.Decrypt(encrypt, RSAEncryptionPadding.Pkcs1);
Assert.AreEqual(Encoding.UTF8.GetString(decryptData), "hi");
rsa2.ExportParameters(true);///How can I prevent exception here
}
Thanks all!
In .NET Core the RSACng object should be in an exportable state when you use ImportParameters, and it should be the case in .NET Framework 4.7.2 as well.
You can put into an exportable state as long as you change the export policy before using the key (by trying to call Export or doing a sign/decrypt/encrypt/verify operation). For example, this works:
using (RSA rsa1 = new RSACng(2048))
using (RSACng rsa2 = new RSACng())
{
rsa2.ImportParameters(rsa1.ExportParameters(true));
rsa2.Key.SetProperty(
new CngProperty(
"Export Policy",
BitConverter.GetBytes((int)CngExportPolicies.AllowPlaintextExport),
CngPropertyOptions.Persist));
RSAParameters params2 = rsa2.ExportParameters(true);
Console.WriteLine(params2.D.Length);
}
Using the NCRYPT_EXPORT_POLICY_PROPERTY described at https://msdn.microsoft.com/en-us/library/windows/desktop/aa376242(v=vs.85).aspx.
The problem is the following:
I generate the key in Android (Xamarin.Droid):
public IPublicKey CreateKey(string keyID)
{
/*KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
keyPairGenerator.initialize(
new KeyGenParameterSpec.Builder(
"key1",
KeyProperties.PURPOSE_SIGN)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PSS)
.build());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
Signature signature = Signature.getInstance("SHA256withRSA/PSS");
signature.initSign(keyPair.getPrivate());
// The key pair can also be obtained from the Android Keystore any time as follows:
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
PrivateKey privateKey = (PrivateKey)keyStore.getKey("key1", null);
PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();*/
//App.Current.MainPage.DisplayAlert("Info", "Creating a new key pair", "Ok");
// UTILIZANDO RSA
KeyPairGenerator kpg =
KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, KEYSTORE_NAME);
kpg.Initialize(
new KeyGenParameterSpec.Builder(keyID,
KeyStorePurpose.Sign)
.SetSignaturePaddings(KeyProperties.SignaturePaddingRsaPss)
.SetDigests(KeyProperties.DigestSha1)
.Build()
);
KeyPair keyPair = kpg.GenerateKeyPair();
Log.Debug(TAG, "New key created for fingerprint authentication");
return keyPair.Public;
}
Then i generate a signature:
KeyStore.PrivateKeyEntry PKentry =
(KeyStore.PrivateKeyEntry)_keystore.GetEntry(keyID, null);
IPublicKey pk = (IPublicKey)PKentry.Certificate.PublicKey;
//this.pk = pk;
privKey = PKentry.PrivateKey;
//cipher.Init(Cipher.EncryptMode, privKey);
//byte[] output = cipher.DoFinal(Encoding.UTF8.GetBytes(input));
//String s = new string(cipher.DoFinal(input));
// signature
Signature sig = Signature.GetInstance("SHA1withRSA/PSS");
sig.InitSign(privKey);
byte[] inputDataToSign = Encoding.UTF8.GetBytes(input);
sig.Update(inputDataToSign);
byte[] signatureBytes = sig.Sign();
And i send the key and the signature to a ASP.net wep API 2 server.
Client side response generation:
RegistrationResponse registrationResponse = new RegistrationResponse();
string fcparams = Utils.Base64Encode(JsonConvert.SerializeObject(finalChallengeParams));
registrationResponse.fcParams = fcparams;
byte[] signedData = sign(fcparams, registrationRequest.username, facetID);
registrationResponse.signedData = signedData;
registrationResponse.Base64key = convertPublicKeyToString(publicKey);
...
...
private string convertPublicKeyToString(IPublicKey publicKey)
{
string publicKeyString = Base64.EncodeToString(publicKey.GetEncoded(), 0);
return publicKeyString;
}
I send it using Refit Nugget.
And this is the code i use when i receive the HTTPRequest on server side:
[Route("regResponse/")]
[HttpPost]
public IHttpActionResult ProcessClientRegistrationResponse([FromBody] RegistrationResponse registrationResponse)
{
//byte[] publicKeyBytes = Convert.FromBase64String(registrationResponse.Base64key);
byte[] publicKeyBytes = registrationResponse.Base64key;
AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(publicKeyBytes);
RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
RSAParameters rsaParameters = new RSAParameters();
rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);
/*****/
string alg = rsa.SignatureAlgorithm;
byte[] signedData = registrationResponse.signedData;
byte[] fcParamsBytes = Encoding.UTF8.GetBytes(registrationResponse.fcParams);
RSACng rsaCng = new RSACng();
rsaCng.ImportParameters(rsaParameters);
SHA1Managed hash = new SHA1Managed();
byte[] hashedData;
hashedData = hash.ComputeHash(signedData);
/*********/
bool rsaCngDataOk1 = rsaCng.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
bool rsaCngDataOk2 = rsaCng.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
bool rsaCngDataOk3 = rsaCng.VerifyData(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
bool rsaCngDataOk4 = rsaCng.VerifyData(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
bool rsaCngHashOk1 = rsaCng.VerifyHash(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
bool dataOK1 = rsa.VerifyData(fcParamsBytes, new SHA1CryptoServiceProvider(), signedData);
bool dataOk2 = rsa.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
bool hashOk = rsa.VerifyHash(hashedData, CryptoConfig.MapNameToOID("SHA1"), signedData);
return Ok(true);
}
EVERY bool is wrong. I think the problem is clearly on the public key.
The questions are,
does the method publickey.encode() do what i think? I think it converts my public key to a byte[] representation (source: Android developer Key Info)
do i convert the received byte[] representation of the key to a correct RSA key?
Is there any problem on algorithms? I don't think so but we never know...
I don't find the solution. I searched for ways to import public keys from strings in .net or c# and for ways to export Android Public key to string or byte[] but there's no much help for this concrete questions...
#James K Polk gave me the solution.
Apparently C# doesn't work well with PSS padding. I just had to change it to PKCS1. And i changed to digest algorithm too to SHA512.
I want functions for import/export PEM/DER strings in C#. I'm using RSA on python and C# but i had no solution who worked fine beetween both language.
After many many tries and many research, i finally found an solution who working for read PEM public key. The following code works :
// pubkey is the PEM file without header/footer and encoded base64
Asn1Object obj = Asn1Object.FromByteArray(pubkey_bytes);
DerSequence publicKeySequence = (DerSequence)obj;
DerSequence publicKey = (DerSequence)Asn1Object.FromByteArray(publicKeySequence.GetEncoded());
DerInteger modulus = (DerInteger)publicKey[0];
DerInteger exponent = (DerInteger)publicKey[1];
RsaKeyParameters keyParameters = new RsaKeyParameters(false, modulus.PositiveValue, exponent.PositiveValue);
RSAParameters parameters = DotNetUtilities.ToRSAParameters(keyParameters);
this code is inspired of a solution i found on StackOverflow. But when i'm trying to use the same solution for private key i have an exception "Spécified size too small". This error seems appears on the "InverseQ" line. Below the code i'm using :
// Private key encode base64 without header/footer
Asn1Object obj = Asn1Object.FromByteArray(privkey_bytes);
DerSequence privateKeySequence = (DerSequence)obj;
DerSequence privateKey = (DerSequence)Asn1Object.FromByteArray(privateKeySequence.GetEncoded());
DerInteger M = (DerInteger)privateKey[1];
DerInteger E = (DerInteger)privateKey[2];
DerInteger D = (DerInteger)privateKey[3];
DerInteger P = (DerInteger)privateKey[4];
DerInteger Q = (DerInteger)privateKey[5];
DerInteger DP = (DerInteger)privateKey[6];
DerInteger DQ = (DerInteger)privateKey[7];
DerInteger IQ = (DerInteger)privateKey[8];
var keyParameters = new RsaPrivateCrtKeyParameters(M.PositiveValue,
E.PositiveValue, D.PositiveValue, P.PositiveValue, Q.PositiveValue,
DP.PositiveValue, DQ.PositiveValue, IQ.PositiveValue);
RSAParameters parameters = DotNetUtilities.ToRSAParameters(keyParameters); // Exception here !
I tried also this code from another StackOverflow post, for fix padding issues, but it's not my problem here :
RSAParameters parameters = new RSAParameters();
parameters.Modulus = M.PositiveValue.ToByteArrayUnsigned();
parameters.Exponent = E.PositiveValue.ToByteArrayUnsigned();
parameters.P = P.PositiveValue.ToByteArrayUnsigned();
parameters.Q = Q.PositiveValue.ToByteArrayUnsigned();Modulus.Length);
parameters.DP = ConvertRSAParametersField(DP.PositiveValue, parameters.P.Length);
parameters.DQ = ConvertRSAParametersField(DQ.PositiveValue, parameters.Q.Length);
parameters.InverseQ = ConvertRSAParametersField(IQ.PositiveValue, parameters.Q.Length);
public static RSAParameters ToRSAParameters(RsaPrivateCrtKeyParameters privKey)
{
RSAParameters rp = new RSAParameters();
rp.Modulus = privKey.Modulus.ToByteArrayUnsigned();
rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned();
rp.P = privKey.P.ToByteArrayUnsigned();
rp.Q = privKey.Q.ToByteArrayUnsigned();
rp.D = ConvertRSAParametersField(privKey.Exponent, rp.Modulus.Length);
rp.DP = ConvertRSAParametersField(privKey.DP, rp.P.Length);
rp.DQ = ConvertRSAParametersField(privKey.DQ, rp.Q.Length);
rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.Q.Length); // Exception HERE
return rp;
}
private static byte[] ConvertRSAParametersField(BigInteger n, int size)
{
byte[] bs = n.ToByteArrayUnsigned();
if (bs.Length == size)
return bs;
if (bs.Length > size) // HERE
throw new ArgumentException("Specified size too small", "size");
byte[] padded = new byte[size];
Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);
return padded;
}
My private key is generated by python and i think it a normal key :
-----BEGIN RSA PRIVATE KEY-----
MIICYAIBAAKBgQCUkUk/vvyTI3begsdjz7eQVchjMTYMTyqt8HHHSXYXY2GrQCZS
VfBVxFLmx19brgMdLrKO93CjJWt+ACXAaLHmuGCsvNgGjCFqgg4XxM4Xamt9PeOc
F8HhMH7iS3OcgybQuu9GrekZB0yL2L9GVpyVrXpVlVHi4gBVjUr80e5LUwIDAQAB
AoGAGgK9wk1bxx8EZrya0BzD1J9QMB2jitApdr6MDQoNhNa/eM4IZ43oP/vZT9JE
Hbb/kJJmbKVhsQ6SHUNFO6qJA0FWYNqEA1xsTtat3RXAB/WCExxW9GwDG6pEXjK8
OrJFbKyIOhmqy3sBib9V76ROYsMi7Gioih8vtYKz8NFBiZECRQCmOHzCqEbsWJnK
5JUsUG8DyR3wg8mzi98m1qYGz3hsuBJMCW2M/QBSgyWGdDxExbQMcTb9lmTelq4W
sHbZLQ3FVxJsbwI9AOTP4ZCLDnzblroQjiUCW1vbVE6YnoO0YTb67Dj/g9CNOZpz
E0lJ3boUlg6lOEpDdwKxSswXhQU53OMJXQJFAKC+BaB0/Uk4EVnNHZkiG4lsp2Bd
AeR4wg8cCqiRYCK7Cy6u+1sZm4Mvwk05AMN88TYLEiO/mcJLswTMF9LDqAqLvoxP
AjxDmlPXo+4k37AZyzhkIN0jN5siGZ+D5DBw0RQoBv5ICOHDC0rgdW2IQ/rN2uzV
rDcmWYFy6WQI1j636ZUCRHWmzCi6ymkcUnqwlYXsjbZSVM7njOc3sJyVhaOgqs+o
1Zjbtpqq7DYEBHPFizh/nu6kf4lT3w5+vIKGs8r4k2IUMcJi
-----END RSA PRIVATE KEY-----
I have a doubt about the order of the parameters returned by "Asn1Object.FromByteArray()". I noticied the [0] was just a "0", that means empty for me. The length is 9 so it seems to be the good way, i'm just not sure about in which order they are returned. Tried to find some documentation but i found nothing.
Thanks in advance for people gonna help me
EDIT
First, i want to say my goal is to get a RSAParameters object.
As suggered by someone who deleted his post, i changed
rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.Q.Length);
to
rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.P.Length);
but after doing it, i got an exception System.Security.Cryptography.CryptographicException who telling me "Incorrect data." on the line
var csp = new RSACryptoServiceProvider(); // my csp object is already defined somewhere else but it change nothing
csp.ImportParameters(parameters); // Exception here, he doesn't like my object who doesn't seems valid for him.
The real problem seems to be "why my object is rejected by RSACryptoServiceProvider.ImportParameters()
I have used RSA Assymetric Key Encryption Algorithm in C# program (I have mentioned below) and I have to encrypt data through a java program. I want my java program to generate same encrypted key as like result of C# program.
Public Key:
<RSAKeyValue>
<Modulus>zgfXY1oUe4nyndX4qtobP1BMxtJ1/rfKU5csdAcWrSVu6ZaEAX3rL3cWnaSLzX4E1BNjSP9pjge6TH7UoaWqOQ==</Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>
C# Encryption Programme:
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(PublicKey); // read public key XML defined above
byte[] buffer = rsa.Encrypt(Encoding.UTF8.GetBytes(strToEncrypt), false);
string encryptedStr = HttpUtility.UrlEncode(buffer);// byteConverterGetString;
Java Encryption Programme:
byte[] modulusBytes = Base64.decode("zgfXY1oUe4nyndX4qtobP1BMxtJ1/rfKU5csdAcWrSVu6ZaEAX3rL3cWnaSLzX4E1BNjSP9pjge6TH7UoaWqOQ==");
byte[] exponentBytes = Base64.decode("AQAB");
BigInteger modulus = new BigInteger(1, modulusBytes );
BigInteger exponent = new BigInteger(1, exponentBytes);
RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(rsaPubKey);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] plainBytes = new String("Admin123").getBytes("UTF-8");
byte[] cipherData = cipher.doFinal( plainBytes );
String encryptedString = Base64.encodeBytes(cipherData);
System.out.println(URLEncoder.encode(encryptedString));
I tried above java program but it gives me result like:
o%2Bgw7%2BXhYxA9ltDV5zERsF4DyXgMTc%2Fgx82wRtT1xfR3suY0XBJLadp7bXjmSX7CplDVdoQyH05Jpqgkd%2B1G4A%3D%3D
and C# program generates like
%23E%03%c2%10)%40E%bf%7b%f9%11%87c0%12q%b9w%ba%2c%98%b4%b1%96%bc%ee%c5_%c9t%1e'%e71%85%b68t%00%3a%b7%d9%fb%a1%18%ba%10%b4%c3c%e1'*%3b%f6D%e2%cc6%82%80%f2%a6
so can anyone help me to correct my java program..
thanks
It seems to me that you're URL encoding two different things:
In Java you're encoding a Base64 encoded string, whereas
In C# you're doing it on a byte array
The result of these two different approaches will not be the same. Perhaps you should encode new String( cipherData ) in the Java part - or just compare the two byte[] arrays before encoding?
Cheers,
You are URLencoding diferent objects, just try this code:
byte[] modulusBytes = Base64.decode("zgfXY1oUe4nyndX4qtobP1BMxtJ1/rfKU5csdAcWrSVu6ZaEAX3rL3cWnaSLzX4E1BNjSP9pjge6TH7UoaWqOQ==");
byte[] exponentBytes = Base64.decode("AQAB");
BigInteger modulus = new BigInteger(1, modulusBytes );
BigInteger exponent = new BigInteger(1, exponentBytes);
RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(rsaPubKey);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] plainBytes = new String("Admin123").getBytes("UTF-8");
byte[] cipherData = cipher.doFinal( plainBytes );
String string = new String(cipherData);
System.out.println(URLEncoder.encode(string,"UTF-8"));