Convert RSA Key into readable or binary format - rsa

I've been trying very hard to convert the rsa key into the binary or readable format using ASP.NET
and I went through a number of sites to sort out the problem
The key format I want is as below:
-----BEGIN PRIVATE KEY-----
BASE64 ENCODED DATA
-----END PRIVATE KEY-----
I have used the below code to create the key using RSA alogorithm. the key generated using the below code is in xml format but I want that in readable format or binary format.
Please help me.
Code Used is.
default.aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default:System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Cryptography.AssignNewKey();
}
protected void Button2_Click(object sender, EventArgs e)
{
txt2.Text = Cryptography.EncryptData(txt1.Text);
}
protected void Button3_Click(object sender, EventArgs e)
{
txt3.Text = Cryptography.DecryptData(txt2.Text);
}
}
Class: Cryptography.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Security.Cryptography;
/// <summary>
/// Summary description for Cryptography
/// </summary>
public class Cryptography
{
public Cryptography()
{
//
// TODO: Add constructor logic here
//
}
public static RSACryptoServiceProvider rsa;
public static void AssignParameter()
{
const int PROVIDER_RSA_FULL = 1;
const string CONTAINER_NAME = "SpiderContainer";
CspParameters cspParams;
cspParams = new CspParameters(PROVIDER_RSA_FULL);
cspParams.KeyContainerName = CONTAINER_NAME;
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
rsa = new RSACryptoServiceProvider(cspParams);
}
public static string EncryptData(string data2Encrypt)
{
AssignParameter();
//StreamReader reader = new StreamReader(#"C:\Inetpub\wwwroot\dotnetspiderencryption\publickey.xml");
StreamReader reader = new StreamReader("C:/keyscsharp/publickey.xml");
string publicOnlyKeyXML = reader.ReadToEnd();
rsa.FromXmlString(publicOnlyKeyXML);
reader.Close();
//read plaintext, encrypt it to ciphertext
byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt);
byte[] cipherbytes = rsa.Encrypt(plainbytes, false);
return Convert.ToBase64String(cipherbytes);
}
public static void AssignNewKey()
{
AssignParameter();
//provide public and private RSA params
//StreamWriter writer = new StreamWriter(#"C:\Inetpub\wwwroot\dotnetspiderencryption\privatekey.xml");
StreamWriter writer = new StreamWriter("C:/keyscsharp/privatekey.xml");
string publicPrivateKeyXML = rsa.ToXmlString(true);
writer.Write(publicPrivateKeyXML);
writer.Close();
//provide public only RSA params
//writer = new StreamWriter(#"C:\Inetpub\wwwroot\dotnetspiderencryption\publickey.xml");
writer = new StreamWriter("C:/keyscsharp/publickey.xml");
string publicOnlyKeyXML = rsa.ToXmlString(false);
writer.Write(publicOnlyKeyXML);
writer.Close();
}
public static string DecryptData(string data2Decrypt)
{
AssignParameter();
byte[] getpassword = Convert.FromBase64String(data2Decrypt);
//StreamReader reader = new StreamReader(#"C:\Inetpub\wwwroot\dotnetspiderencryption\privatekey.xml");
StreamReader reader = new StreamReader("C:/keyscsharp/privatekey.xml");
string publicPrivateKeyXML = reader.ReadToEnd();
rsa.FromXmlString(publicPrivateKeyXML);
reader.Close();
//read ciphertext, decrypt it to plaintext
byte[] plain = rsa.Decrypt(getpassword, false);
return System.Text.Encoding.UTF8.GetString(plain);
}
}
Please Help me out.

Related

How to write NUnit test for dependency injection service .net core

I have a service class with some injected services. It's dealing with my Azure storage requests. I need to write NUnit tests for that class.
I'm new to NUnit and I'm struggling with making the object of that my AzureService.cs
Below AzureService.cs. I have used some injected services
using System;
using System.Linq;
using System.Threading.Tasks;
using JohnMorris.Plugin.Image.Upload.Azure.Interfaces;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Nop.Core.Caching;
using Nop.Core.Configuration;
using Nop.Core.Domain.Media;
using Nop.Services.Logging;
namespace JohnMorris.Plugin.Image.Upload.Azure.Services
{
public class AzureService : IAzureService
{
#region Constants
private const string THUMB_EXISTS_KEY = "Nop.azure.thumb.exists-{0}";
private const string THUMBS_PATTERN_KEY = "Nop.azure.thumb";
#endregion
#region Fields
private readonly ILogger _logger;
private static CloudBlobContainer _container;
private readonly IStaticCacheManager _cacheManager;
private readonly MediaSettings _mediaSettings;
private readonly NopConfig _config;
#endregion
#region
public AzureService(IStaticCacheManager cacheManager, MediaSettings mediaSettings, NopConfig config, ILogger logger)
{
this._cacheManager = cacheManager;
this._mediaSettings = mediaSettings;
this._config = config;
this._logger = logger;
}
#endregion
#region Utilities
public string GetAzureStorageUrl()
{
return $"{_config.AzureBlobStorageEndPoint}{_config.AzureBlobStorageContainerName}";
}
public virtual async Task DeleteFileAsync(string prefix)
{
try
{
BlobContinuationToken continuationToken = null;
do
{
var resultSegment = await _container.ListBlobsSegmentedAsync(prefix, true, BlobListingDetails.All, null, continuationToken, null, null);
await Task.WhenAll(resultSegment.Results.Select(blobItem => ((CloudBlockBlob)blobItem).DeleteAsync()));
//get the continuation token.
continuationToken = resultSegment.ContinuationToken;
}
while (continuationToken != null);
_cacheManager.RemoveByPrefix(THUMBS_PATTERN_KEY);
}
catch (Exception e)
{
_logger.Error($"Azure file delete error", e);
}
}
public virtual async Task<bool> CheckFileExistsAsync(string filePath)
{
try
{
var key = string.Format(THUMB_EXISTS_KEY, filePath);
return await _cacheManager.Get(key, async () =>
{
//GetBlockBlobReference doesn't need to be async since it doesn't contact the server yet
var blockBlob = _container.GetBlockBlobReference(filePath);
return await blockBlob.ExistsAsync();
});
}
catch { return false; }
}
public virtual async Task SaveFileAsync(string filePath, string mimeType, byte[] binary)
{
try
{
var blockBlob = _container.GetBlockBlobReference(filePath);
if (!string.IsNullOrEmpty(mimeType))
blockBlob.Properties.ContentType = mimeType;
if (!string.IsNullOrEmpty(_mediaSettings.AzureCacheControlHeader))
blockBlob.Properties.CacheControl = _mediaSettings.AzureCacheControlHeader;
await blockBlob.UploadFromByteArrayAsync(binary, 0, binary.Length);
_cacheManager.RemoveByPrefix(THUMBS_PATTERN_KEY);
}
catch (Exception e)
{
_logger.Error($"Azure file upload error", e);
}
}
public virtual byte[] LoadFileFromAzure(string filePath)
{
try
{
var blob = _container.GetBlockBlobReference(filePath);
if (blob.ExistsAsync().GetAwaiter().GetResult())
{
blob.FetchAttributesAsync().GetAwaiter().GetResult();
var bytes = new byte[blob.Properties.Length];
blob.DownloadToByteArrayAsync(bytes, 0).GetAwaiter().GetResult();
return bytes;
}
}
catch (Exception)
{
}
return new byte[0];
}
#endregion
}
}
This is my test class below, I need to create new AzureService(); from my service class. But in my AzureService constructor, I'm injecting some service
using JohnMorris.Plugin.Image.Upload.Azure.Services;
using Nop.Core.Caching;
using Nop.Core.Domain.Media;
using Nop.Services.Tests;
using NUnit.Framework;
namespace JohnMorris.Plugin.Image.Upload.Azure.Test
{
public class AzureServiceTest
{
private AzureService _azureService;
[SetUp]
public void Setup()
{
_azureService = new AzureService( cacheManager, mediaSettings, config, logger);
}
[Test]
public void App_settings_has_azure_connection_details()
{
var url= _azureService.GetAzureStorageUrl();
Assert.IsNotNull(url);
Assert.IsNotEmpty(url);
}
[Test]
public void Check_File_Exists_Async_test(){
//To Do
}
[Test]
public void Save_File_Async_Test()(){
//To Do
}
[Test]
public void Load_File_From_Azure_Test(){
//To Do
}
}
}
Question is, what exactly do you want to test? If you want to test if NopConfig is properly reading values from AppSettings, then you do not have to test AzureService at all.
If you want to test that GetAzureStorageUrl method is working correctly, then you should mock your NopConfig dependency and focus on testing only AzureService methods like this:
using Moq;
using Nop.Core.Configuration;
using NUnit.Framework;
namespace NopTest
{
public class AzureService
{
private readonly NopConfig _config;
public AzureService(NopConfig config)
{
_config = config;
}
public string GetAzureStorageUrl()
{
return $"{_config.AzureBlobStorageEndPoint}{_config.AzureBlobStorageContainerName}";
}
}
[TestFixture]
public class NopTest
{
[Test]
public void GetStorageUrlTest()
{
Mock<NopConfig> nopConfigMock = new Mock<NopConfig>();
nopConfigMock.Setup(x => x.AzureBlobStorageEndPoint).Returns("https://www.example.com/");
nopConfigMock.Setup(x => x.AzureBlobStorageContainerName).Returns("containername");
AzureService azureService = new AzureService(nopConfigMock.Object);
string azureStorageUrl = azureService.GetAzureStorageUrl();
Assert.AreEqual("https://www.example.com/containername", azureStorageUrl);
}
}
}

How to import randomly generated 4096bit Java RSA public key from String

I have a network app that I'm trying to use with Java and Flutter and encryption. I'm using a 4096 bit RSA randomly generated keypair in Java and I'm using it to encrypt a randomly generated AES 256 bit key
I only need the Dart code as the Java code is already working.
In Java I am using this class
/**
* Create a key pair
* #return The pair
*/
public static KeyPair generateKeyPairs() {
KeyPairGenerator keyGen;
try {
keyGen = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
keyGen.initialize(4096);
return keyGen.generateKeyPair();
}
public static String toBase64(Key publicKey) {
byte[] encodedPublicKey = publicKey.getEncoded();
return Base64.getEncoder().encodeToString(encodedPublicKey);
}
public static PublicKey toPublicKey(String base64PublicKey){
PublicKey publicKey;
try{
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey.getBytes()));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}
In Dart I am using PointyCastle and this method; however it doesn't work
static RSAAsymmetricKey rsaPublicKeyFromString(String key) {
String keyWithHeader = "-----BEGIN RSA PUBLIC KEY-----\n" + utf8.decode(base64Decode(key)) + "\n-----END RSA PUBLIC KEY-----";
return RSAKeyParser().parse(keyWithHeader);
}
Use the excellent basic_utils package.
Dart
import 'package:pointycastle/export.dart';
import 'package:basic_utils/basic_utils.dart';
void main() {
var javaEncoded =
'MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAnitmaCHY8T171EiimoIN8MUg6IMi2JXbZBFioFJK9fiXnX/bo/6+1fuNgk+T/r6fbtk0iCogBCL30j/K7L+3J9p06rhvpM0/XAxi7YhMrIU5zetToZPBStzWt/qS1vOF2WFK6OfloFwFNAJltNljeVl7M7KbAkYcLxhfwyaPZTvmumAsCkkVhQevaVNBD2i6BWbMWb+3aki20FE2+nwzSa0ZgtwA9FJ4AV023eA1sw1ON9KS9eqdz78d/ve4aJJ/pv2Tvvc3iY2HhlvJmzS81tcocO660QediiI3K7rXus1QmGpHNEBvv818ai+RS4sehvyAhZl6dr+HH9zpdV0QESHqsyi7zJaal2GYeILdNGZtyYEsaqEq8K8MiynCvk7HSXHGZsx7zNFtVztc8T6ubN9sBDx4myFj/a1pdDltQ8OJGvomLX6wBwC0ywiroDeMAdbpfU1xNBYUqj8S0dTkrlul+ucbOySTpTpQJOnj9X98kptGnL2ESqi71vQh+qcMALjF/OqbGVOnPzzEqPlUWsR9jykmjBHkgeC9vSoMeGMdx+pUV7D1AXrXGs3ALOuBoUcBR00JPwIQ69wSZ/WFL9C9+gPfIvO802NEuckEYQB1eHVQFnhxdNF+slii+RBZ7UqnH3Fzvai4rPq5Yd/+Enxa8Gd3dqkO0QmkP5OSPzECAwEAAQ==';
var pem =
'-----BEGIN RSA PUBLIC KEY-----\n$javaEncoded\n-----END RSA PUBLIC KEY-----';
RSAPublicKey public = CryptoUtils.rsaPublicKeyFromPem(pem);
print(public.modulus);
}
where the long string was produced by this Java - shown for completeness.
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(4096);
KeyPair pair = keyGen.generateKeyPair();
byte[] encodedPublicKey = pair.getPublic().getEncoded();
System.out.println(Base64.getEncoder().encodeToString(encodedPublicKey));

Excel File Upload using GWT

I am not able to upload excel file and parse using GWT 2.7.0. Referred many links Link1 Link2
using above technique and RequestBuilder I couldn't send parsed excel data back to client. Finally implemented GWT RPC technique but having problem load Excel file as GWT cannot implement File.io api on client(Javascript or browser cannot read)
Code:
Client side FileUploading
public class MyFileUpload extends Composite implements Constants{
private ExcelClientServiceImpl excelServiceClient;
private VerticalPanel vPanel;
public MyFileUpload(ExcelClientServiceImpl excelServiceClient){
this.excelServiceClient = excelServiceClient;
this.vPanel = new VerticalPanel();
initWidget(this.vPanel);
}
public void initiateUpload() {
// Create a FormPanel and point it at a service.
final FormPanel form = new FormPanel();
form.setAction("/excelParser");
// Because we're going to add a FileUpload widget, we'll need to set the
// form to use the POST method, and multipart MIME encoding.
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
// Create a panel to hold all of the form widgets.
vPanel = new VerticalPanel();
form.setWidget(vPanel);
// Create a FileUpload widget.
final FileUpload upload = new FileUpload();
//upload.setName("uploadFormElement");
vPanel.add(upload);
System.out.println("File name is : "+upload.getFilename());
// Add a 'submit' button.
vPanel.add(new Button("Submit", new ClickHandler() {
public void onClick(ClickEvent event) {
Window.alert("In Button >>>>>> "+event);
form.submit();
}
}));
// Add an event handler to the form.
form.addSubmitHandler(new FormPanel.SubmitHandler() {
public void onSubmit(SubmitEvent event) {
Window.alert("In Handler >>>>>> "+event);
}
});
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
public void onSubmitComplete(SubmitCompleteEvent event) {
// When the form submission is successfully completed, this event is
// fired. Assuming the service returned a response of type text/html,
// we can get the result text here (see the FormPanel documentation for
// further explanation).
Window.alert("In complete >>>>>> "+event.getResults());
}
});
RootPanel.get().add(form);
}
}
Client Interface
public interface ExcelClientServiceInt {
void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber,
String separator);
void readingExcel();
}
Client Implementation
public class ExcelClientServiceImpl implements ExcelClientServiceInt{
private ExcelServiceIntAsync service;
private MyFileUpload excelUpload;
public ExcelClientServiceImpl(String url){
this.service = GWT.create(ExcelParserService.class);
ServiceDefTarget endpoint = (ServiceDefTarget) this.service;
endpoint.setServiceEntryPoint(url);
this.excelUpload = new MyFileUpload(this);
}
#Override
public void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber,
String separator) {
this.service.parse(fileName, lines, integerNumber, floatNumber, separator, new DefaultCallback());
}
#Override
public void readingExcel() {
this.service.readingExcel(null, new DefaultCallback());
}
private class DefaultCallback implements AsyncCallback{
#Override
public void onFailure(Throwable caught) {
System.out.println("Output failed");
}
#Override
public void onSuccess(Object result) {
System.out.println("Output reieved successfully "+result);
}
}
}
Service Interface
#RemoteServiceRelativePath("excelParser")
public interface ExcelServiceInt extends RemoteService{
void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber, String separator);
public List readingExcel(String fileName);
}
Async Call Back
public interface ExcelServiceIntAsync{
void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber,
String separator, AsyncCallback<Void> callBack);
void readingExcel(String fileName, AsyncCallback<List<String>> callBack);
}
Server side Service
public class ExcelParserService extends RemoteServiceServlet implements ExcelServiceInt{
public void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber,
String separator) {
ExcelParser.parse(fileName, lines, integerNumber, floatNumber, separator);
}
public List<String> readingExcel(String fileName) {
return ExcelParser.readingExcel(fileName);
}
}

My program does not save or load infomation in or from data base

I created a database and three pages for a register & login form & the third is for a lottery between my usernames .
I don't have any errors but the whole thing is not using the data base,
it does not save or load from database .
This is my register form:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _2 : System.Web.UI.Page
{
protected void btnRegister_Click(object sender, EventArgs e)
{
string strcon = "Data Source=.;uid=sa;pwd=123;database=Login_Register";
SqlConnection con = new SqlConnection(strcon);
SqlCommand com = new SqlCommand("strlogin", con);
com.CommandType = System.Data.CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("username", txtUserName.Text.ToString());
SqlParameter p2 = new SqlParameter("email", txtEmail.Text.ToString());
SqlParameter p3 = new SqlParameter("password", txtpassword.Text.ToString());
com.Parameters.Add(p1);
com.Parameters.Add(p2);
com.Parameters.Add(p3);
con.Open();
Label4.Text ="ثبت نام با موفقیت انجام شد".ToString();
Label4.Visible = true;
con.Close();
com.ExecuteNonQuery();
}
private SqlDbType ToString(object text)
{
throw new NotImplementedException();
}
}
public class Label4
{
internal static object Text;
internal static bool Visible;
}
public class txtUserName
{
internal static object Text;
internal static bool Visible;
}
public class txtEmail
{
internal static object Text;
internal static bool Visible;
}
public class txtpassword
{
internal static object Text;
internal static bool Visible;
}
Look at your code
con.Open();
Label4.Text ="ثبت نام با موفقیت انجام شد".ToString();
Label4.Visible = true;
con.Close();
com.ExecuteNonQuery();
You are opening the connection, closing it and then executing.
it should be:
con.Open();
Label4.Text ="ثبت نام با موفقیت انجام شد".ToString();
Label4.Visible = true;
com.ExecuteNonQuery();
con.Close();//close connection after execute.
also it would be a good idea to add try/catch block around it - in case connection cannot be opened

C# - duplicated output for start date in date range iteration

I am trying to make simple app and got stuck. User chooses start date from date picker1 28.01.2015 and end date picker2 29.01.2015 then marks what he/she wants via checkboxes and presses button. The output in console should look similar to this depending on what is marked.
tar zxcvf /.../c/folder/folder/$HOSTNAME.20150128.log;zxcvf /.../c/folder/folder/$HOSTNAME.20150129.log`
but instead date picked as start date is returned twice in console and I have no idea what is wrong:
zxcvf /.../c/folder/folder/$HOSTNAME.20150128.log;zxcvf /.../c/folder/folder/$HOSTNAME.20150128.log;zxcvf /.../c/folder/folder/$HOSTNAME.20150129.log
Code below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Renci.SshNet;
using System.Configuration;
namespace TestApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
GlobalMethods configRead = new GlobalMethods();
configRead.ConfigRead();
}
...
private void button1_Click(object sender, EventArgs e)
{
GlobalMethods configRead = new GlobalMethods();
configRead.ConfigRead();
GlobalMethods dateIterator = new GlobalMethods();
dateIterator.Iterator();
GlobalVariables.comminit = null;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
GlobalVariables.cLM = true;
}
else if (!checkBox1.Checked)
{
GlobalVariables.cLM = false;
}
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
GlobalVariables.dateStart = dateTimePicker1.Value;
}
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
GlobalVariables.dateEnd = dateTimePicker2.Value;
//string endDate = dateTimePicker2.Value.ToString("yyyyMMdd");
}
}
public static class GlobalVariables
{
// Log variables below
public static Boolean mLM;
public static Boolean cLM;
public static Boolean hLM;
public static Boolean pLM;
public static Boolean prLM;
public static Boolean compressMarked = true;
public static String iterate;
public static String comminit;
public static String pH;
public static String pP;
public static String pC;
public static String ppP;
public static String pM;
// Time variables below
public static DateTime dateStart = DateTime.Now;
public static DateTime dateEnd = DateTime.Now;
}
public class Instructions
{
public static String hLl()
{
if (GlobalVariables.compressMarked)
{
return "tar zxcvf " + GlobalVariables.pH + "$HOSTNAME." + GlobalVariables.iterate + ".log;";
}
else { return "wget " + GlobalVariables.pH + "$HOSTNAME." + GlobalVariables.iterate + ".log;"; }
}
...
public static String commandsBath()
{
if (GlobalVariables.mLM == true)
{
GlobalVariables.comminit += mLl();
}
if (GlobalVariables.cLM == true)
{
GlobalVariables.comminit += cLl();
}
if (GlobalVariables.hLM == true)
{
GlobalVariables.comminit += hLl();
}
if (GlobalVariables.pLM == true)
{
GlobalVariables.comminit += pLl();
}
if (GlobalVariables.prLM == true)
{
GlobalVariables.comminit += pLlp();
}
return GlobalVariables.comminit;
}
}
public class GlobalMethods
{
public void Iterator()
{
for (DateTime i = GlobalVariables.dateStart; i <= GlobalVariables.dateEnd; i = i.AddDays(1))
{
string iterated = i.ToString("yyyyMMdd");
GlobalVariables.iterate = iterated;
}
}
public void ConfigRead()
{
...
}
public void ConfigWrite()
{
...
}
}
}
Hopefully someone can help.
Never mind, found the solution. Instead of using += and add results of if statements it is better to use String builder like below. This way it works correctly and is more simple.
var sb = new StringBuilder();
if (GlobalVariables.mLM == true) sb.Append(mLl());
if (GlobalVariables.cLM == true) sb.Append(cLl());
...
return GlobalVariables.comminit = sb.ToString();