I am new to Java. I have a string like the following:
str="4*5";
Now I have to get the result of 20 by using the string. I know in some other languages the eval function will do this. How do I do this in Java?
Hello!
I have a dictionary with non unique values and I want to count the matches of a string versus the values.
Basically I now do dict.ContainsValue(a) to get a bool telling me if the string a exists in dict, but I want to know not only if it exists but how many times it exists (and maybee even get a list of the keys it exists bound to)
Is there a way to do this using dictionary, or should I look for a different collection?
/Rickard Haake
Hey everyone,
Further to my question here, I have another question regarding salts.
When someone says "use a random salt" to pre/append to a password, does this mean:
Creating a static a 1 time randomly generated string of characters, or
Creating a string of characters that changes at random every time a
password is created?
If the salt is random for every user and stored along with the hashed password, how is the original salt ever retrieved back for verification?
Thanks!
I have a byte array generated by a random number generator. I want to put this into the STL bitset.
Unfortunately, it looks like Bitset only supports the following constructors:
A string of 1's and 0's like "10101011"
An unsigned long. (my byte array will be longer)
The only solution I can think of now is to read the byte array bit by bit and make a string of 1's and 0's. Does anyone have a more efficient solution?
In c# I can initialize a List at creation time like
var list = new List<String>() {"string1", "string2"};
is there a similar thing in VB.Net?
Currently I can do it like
Dim list As New List(Of String)
list.Add("string1")
list.Add("string2")
list.Add("string3")
but I want to avoid boring .Add lines
i have the following code snapshot:
public void getResults( String expression, String collection ){
ReferenceList list;
Vector lists = new Vector();
list = invertedIndex.get( 1 )//invertedIndex is class member
lists.add(list);
}
when the method is finished, i supose that the local objects ( list, lists) are "destroyed". Can you tell if the memory occupied by list stored in invertedIndex is released as well? Or does java allocate new memory for list when assigning list = invertedIndex.get( 1 );
I recently began to start using functions to make casting easier on my fingers for one instance I had something like this
((Dictionary<string,string>)value).Add(foo);
and converted it to a tiny little helper function so I can do this
ToDictionary(value).Add(foo);
Is this a code smell?
(also I've marked this language agnostic even though my example is C#)
Hi All,
I have two lists,
Status
Name (string)
Active (yes/no)
Task
Name (string)
Status (Lookup to Status list)
I have the following statuses (These can be changed at any time by the client):
New, Active = Yes
Open, Active = Yes
Not Resolved, Active = No
Resolved, Active = No
I want to create a view for the Projects list, that shows all active tasks... How would I go about this?
Thanks!
Albert
I am encrypting a string in objective-c and also encrypting the same string in Java using AES and am seeing some strange issues. The first part of the result matches up to a certain point but then it is different, hence when i go to decode the result from Java onto the iPhone it cant decrypt it.
I am using a source string of "Now then and what is this nonsense all about. Do you know?"
Using a key of "1234567890123456"
The objective-c code to encrypt is the following: NOTE: it is a NSData category so assume that the method is called on an NSData object so 'self' contains the byte data to encrypt.
- (NSData *)AESEncryptWithKey:(NSString *)key {
char keyPtr[kCCKeySizeAES128+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES128,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
And the java encryption code is...
public byte[] encryptData(byte[] data, String key) {
byte[] encrypted = null;
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
byte[] keyBytes = key.getBytes();
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
encrypted = new byte[cipher.getOutputSize(data.length)];
int ctLength = cipher.update(data, 0, data.length, encrypted, 0);
ctLength += cipher.doFinal(encrypted, ctLength);
} catch (Exception e) {
logger.log(Level.SEVERE, e.getMessage());
} finally {
return encrypted;
}
}
The hex output of the objective-c code is -
7a68ea36 8288c73d f7c45d8d 22432577 9693920a 4fae38b2 2e4bdcef 9aeb8afe 69394f3e 1eb62fa7 74da2b5c 8d7b3c89 a295d306 f1f90349 6899ac34 63a6efa0
and the java output is -
7a68ea36 8288c73d f7c45d8d 22432577 e66b32f9 772b6679 d7c0cb69 037b8740 883f8211 748229f4 723984beb 50b5aea1 f17594c9 fad2d05e e0926805 572156d
As you can see everything is fine up to -
7a68ea36 8288c73d f7c45d8d 22432577
I am guessing I have some of the settings different but can't work out what, I tried changing between ECB and CBC on the java side and it had no effect.
Can anyone help!? please....
In the control ObjectListView(http://objectlistview.sourceforge.net/html/cookbook.htm), I'm trying to add a custom sorter where it ignores "The" and "A" prefixes.
I managed to do it with a regular ListView, but now that I switched to ObjectListView(a lot more features, and ease), I can't seem to do the same.
The following is the Main comparer in the ObjectListView code i think...
public int Compare(object x, object y)
{
return this.Compare((OLVListItem)x, (OLVListItem)y);
}
Original Sorter for ascending, as an example (Ignoring "A" and "The")
public class CustomSortAsc : IComparer
{
int IComparer.Compare(Object x, Object y)
{
string[] px = Convert.ToString(x).Split(' ');
string[] py = Convert.ToString(y).Split(' ');
string newX = "";
string newY = "";
for (int i = 0; i < px.Length; i++)
{
px[i] = px[i].Replace("{", "");
px[i] = px[i].Replace("}", "");
}
for (int i = 0; i < py.Length; i++)
{
py[i] = py[i].Replace("{", "");
py[i] = py[i].Replace("}", "");
}
if ((px[1].ToLower() == "a") || (px[1].ToLower() == "the"))
{
if (px.Length > 1)
{
for (int i = 2; i < px.Length; i++)
newX += px[i];
}
}
else
{
for (int i = 1; i < px.Length; i++)
newX += px[i];
}
if ((py[1].ToLower() == "a") || (py[1].ToLower() == "the"))
{
if (py.Length > 1)
{
for (int i = 2; i < py.Length; i++)
newY += py[i];
}
}
else
{
for (int i = 1; i < py.Length; i++)
newY += py[i];
}
return ((new CaseInsensitiveComparer()).Compare(newX, newY));
}
[Disclaimer: This has been cross posted on the Android Developers Google Group
I am trying to use a CompoundButton in a project I am working on. Every time I try and use it by declaring it in my layout xml file I receive the error "01-04 12:27:46.471: ERROR/AndroidRuntime(1771): Caused by: android.view.InflateException: Binary XML file line #605: Error inflating class android.widget.CompoundButton"
After fighting the error for a half an hour I decided to try a minimalistic example. I am using the latest eclipse developer tools, and targeting android 2.2 makign the minimum sdk required 2.2 (8).
Here is the activity java code:
package com.example.CompoundButtonExample;
import android.app.Activity;
import android.os.Bundle;
public class CompoundButtonExampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Here is the layout xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<CompoundButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
Here is the manifest xml code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.CompoundButtonExample"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".CompoundButtonExampleActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
As you can see it is just the default hello world project that eclipse creates for you when you start a new Android project. It only differs in the fact that I add a "CompoundButton" to the main layout in a vertical LinearLayout.
Can anyone confirm this bug? Or tell me what I am doing wrong?
Hi all,
I have my users DOB as a string (don't ask), how can I reliably check to see if they are over 18? Would I use DateDiff? How would I convert the string to a date first? The date is in dd/mm/yyyy format.
Many thanks
Jonathan
Big class contains Format-interfcase and Format-class. The Format-class contains the methods and the interface has the values of the fields. I could have the fields in the class Format but the goal is with Interface. So do I just create dummy-vars to get the errors away, design issue or something ELSE?
KEY: Declaration VS Initialisation
Explain by the terms, why you have to init in interface.
What is the logic behind it?
To which kind of problems it leads the use of interface?
Sample Code having the init-interface-problem
import java.util.*;
import java.io.*;
public class FormatBig
{
private static class Format implements Format
{
private static long getSize(File f){return f.length();}
private static long getTime(File f){return f.lastModified();}
private static boolean isFile(File f){if(f.isFile()){return true;}}
private static boolean isBinary(File f){return Match.isBinary(f);}
private static char getType(File f){return Match.getTypes(f);}
private static String getPath(File f){return getNoErrPath(f);}
//Java API: isHidden, --- SYSTEM DEPENDED: toURI, toURL
Format(File f)
{
// PUZZLE 0: would Stack<Object> be easier?
size=getSize(f);
time=getTime(f);
isfile=isFile(f);
isBinary=isBinary(f);
type=getType(f);
path=getPath(f);
//PUZZLE 1: how can simplify the assignment?
values.push(size);
values.push(time);
values.push(isfile);
values.push(isBinary);
values.push(type);
values.push(path);
}
}
public static String getNoErrPath(File f)
{
try{return f.getCanonicalPath();
}catch(Exception e){e.printStackTrace();}
}
public static final interface Format
{
//ERR: IT REQUIRES "="
public long size;
public long time;
public boolean isFile=true; //ERROR goes away if I initialise wit DUMMY
public boolean isBinary;
public char type;
public String path;
Stack<Object> values=new Stack<Object>();
}
public static void main(String[] args)
{
Format fm=new Format(new File("."));
for(Object o:values){System.out.println(o);}
}
}
Our office currently uses telnet to query an external server. The procedure is something like this.
Connect - telnet opent 128........ 25000
Query - we paste the query and then hit alt + 019
Response - We receive the response as text in the telnet window
So I’m trying to make this queries automatic using a c# app. My code is the following
First the connection. (No exceptions)
SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
String szIPSelected = txtIPAddress.Text;
String szPort = txtPort.Text;
int alPort = System.Convert.ToInt16(szPort, 10);
System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(szIPSelected);
System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, alPort);
SocketClient.Connect(remoteEndPoint);
Then I send the query (No exceptions)
string data ="some query";
byte[] byData = System.Text.Encoding.ASCII.GetBytes(data);
SocketClient.Send(byData);
Then I try to receive the response
byte[] buffer = new byte[10];
Receive(SocketClient, buffer, 0, buffer.Length, 10000);
string str = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
txtDataRx.Text = str;
public static void Receive(Socket socket, byte[] buffer, int offset, int size, int timeout)
{
int startTickCount = Environment.TickCount;
int received = 0; // how many bytes is already received
do
{
if (Environment.TickCount > startTickCount + timeout)
throw new Exception("Timeout.");
try
{
received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.WouldBlock ||
ex.SocketErrorCode == SocketError.IOPending ||
ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
{
// socket buffer is probably empty, wait and try again
Thread.Sleep(30);
}
else
throw ex; // any serious error occurr
}
} while (received < size);
}
Every time I try to receive the response I get "an exsiting connetion has forcibly closed by the remote host" if open telnet and send the same query I get a response right away
Any ideas, or suggestions?
Hi!
How to find items in Outlook inbox by from email?
This version works and finds email:
String sCriteria = "[From] = 'Sebastian Nowak'";
Outlook.Items filteredItems = inbox.Items.Restrict(sCriteria);
This version doesn't work, doesn't find any mail:
String sCriteria = "[From] = '[email protected]'";
Outlook.Items filteredItems = inbox.Items.Restrict(sCriteria);
How do I should search by email from wich mail was sent.
I'd like to make a call to a function and send either a string or an integer...
function getImage(val:*):void{
if(val == String){
switch(val){
case'next':
loadNext();
break;
case'prev':
loadPrev();
break
}
}
}else{
loadImg(val);
}
}
and vary my function accordingly... anyone know how to detect the parameter type?
Thanks
-J
Is there an actual package in CPAN to convert such string:
my $string = "54.4M"
my $string2 = "3.2G"
into the actual number in bytes:
54,400,000
3,200,000,000
And vice versa.
Hi all.
Going round in circles here i think.
I have an activity called Locate;
public class Locate extends Activity {
public static String lat;
public static String lon;
public static String number;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locate);
final Button buttonMaps = (Button) findViewById(R.id.ButtonMaps);
buttonMaps.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(), "Button Pressed", Toast.LENGTH_SHORT).show();
try {
Intent i = new Intent(getBaseContext(), displayMap.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
catch (ActivityNotFoundException e) {
Toast.makeText(getBaseContext(), "Activity Not Found", Toast.LENGTH_SHORT).show();
}
}});
// Toast.makeText(getBaseContext(), "lat: " + lat + " long: " + lon + " from: " + testname, Toast.LENGTH_LONG).show();
}
If I make the displayMap class into a normal Activity, and just have display a toast message confirming it has loaded - then it works fine.
If i do this though;
public class displayMap extends MapActivity
{
/** Called when the activity is first created. */
public void onCreate()
{
setContentView(R.layout.displaymap);
Toast.makeText(getBaseContext(), "Display Map", Toast.LENGTH_SHORT).show();
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Then as soon as I click the Button, I get a force close.
I have the correct 'uses-library' tag in my manifest;
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-library android:name="com.google.android.maps" />
I don't get what it just force closes everytime i try and load it.
If I make this my onClick handler then it will fire up a working googlemaps/default mapview
public void onClick(View v) {
Toast.makeText(getBaseContext(), "Button Pressed", Toast.LENGTH_SHORT).show();
Uri uri=Uri.parse("geo:"+Locate.lat+","+Locate.lon);
StartActivity(new Intent(Intent.ACTION_VIEW, uri));
}
But that is not what I am trying to do, I want my own - so that I can add overlays etc to it. But it does prove that the permission are set correctly and that the lib is there.
The logcat error when the app FCs is a Unexpected DEX error.
Can anyone point in the right direction here?
On my personal website, i would like to make it "pronounce" something
I solved the "concept" problem, as in here, and on my desktop it works smoothly when launched from visual web developer. Creates a file, and then an embedded player in the page will play it. Perfect.
So, I uploaded it on the server... I get this error 500:
Server Error in '/sapi' Application.
Access is denied. (Exception from
HRESULT: 0x80070005 (E_ACCESSDENIED))
Description: An unhandled exception
occurred during the execution of the
current web request. Please review the
stack trace for more information about
the error and where it originated in
the code.
Exception Details:
System.UnauthorizedAccessException:
Access is denied. (Exception from
HRESULT: 0x80070005 (E_ACCESSDENIED))
ASP.NET is not authorized to access
the requested resource. Consider
granting access rights to the resource
to the ASP.NET request identity.
ASP.NET has a base process identity
(typically {MACHINE}\ASPNET on IIS 5
or Network Service on IIS 6) that is
used if the application is not
impersonating. If the application is
impersonating via , the identity
will be the anonymous user (typically
IUSR_MACHINENAME) or the authenticated
request user.
(...)
Source Error:
See it below
Source File:
c:\mypath\sapi\myfile.aspx.cs
Line: 21
Stack Trace:
[UnauthorizedAccessException: Access
is denied. (Exception from HRESULT:
0x80070005 (E_ACCESSDENIED))]
SpeechLib.SpVoiceClass.Speak(String
Text, SpeechVoiceSpeakFlags Flags) +0
prova.Button1_Click(Object sender,
EventArgs e) in
c:\mypath\sapi\prova.aspx.cs:21
System.Web.UI.WebControls.Button.OnClick(EventArgs
e) +111
System.Web.UI.WebControls.Button.RaisePostBackEvent(String
eventArgument) +110
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
sourceControl, String eventArgument)
+13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection
postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +1565
Version Information: Microsoft .NET
Framework Version:2.0.50727.3053;
ASP.NET Version:2.0.50727.3053
This is the source
Source Error:
Line 19: myfile.Open(@"C:\mypath\sapi\gen\hi.wav",SpeechStreamFileMode.SSFMCreateForWrite,false);
Line 20: voice.AudioOutputStream = myfile;
Line 21: voice.Speak("Hi",SpeechVoiceSpeakFlags.SVSFDefault);
I get error on line 21, Voice.speak
That probably means that the aspnet worker user has not some right permission
The generation folder has all the right permissions: an empty file is created.
So, i have to give permission of execute to some system dll?
Do you know which dll? It is not bin\Interop.SpeechLib.dll, on this one the aspnet user has full control
Ps: i have full control on the (windows) server (i mean, access by RDC, is not a shared hosting)
Hello
I am fighting with this problem:
I have a usercontrol which contains a textbox and a button (the button calls some functions to set the textbox's text), here is the xaml:
<UserControl x:Class="UcSelect"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Control1Name"
<Grid x:Name="grid1" MaxHeight="25">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="25"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
</Grid.RowDefinitions>
<TextBox x:Name="txSelect" Text="{Binding UcText, Mode=TwoWay}" />
<Button x:Name="pbSelect" Background="Red" Grid.Column="1" Click="pbSelect_Click">...</Button>
</Grid>
And here the code behind:
Partial Public Class UcSelect
Private Shared Sub textChangedCallBack(ByVal [property] As DependencyObject, ByVal args As DependencyPropertyChangedEventArgs)
Dim UcSelectBox As UcSelect = DirectCast([property], UcSelect)
End Sub
Public Property UcText() As String
Get
Return GetValue(UcTextProperty)
End Get
Set(ByVal value As String)
SetValue(UcTextProperty, value)
End Set
End Property
Public Shared ReadOnly UcTextProperty As DependencyProperty = _
DependencyProperty.Register("UcText", _
GetType(String), GetType(UcSelect), _
New FrameworkPropertyMetadata(String.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, New PropertyChangedCallback(AddressOf textChangedCallBack)))
Public Sub New()
InitializeComponent()
grid1.DataContext = Me
End Sub
Private Sub pbSelect_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
'just demo
UcText = UcText + "!"
End Sub
End Class
The UserControl works fine when used as a single control in this way:
<local:UcSelect Grid.Row="1" x:Name="ucSingle1" UcText="{Binding FirstName, Mode=TwoWay}"/>
Now I wanted to use the control in a custom datagrid column. As I like to have binding support I choosed to derive from DataGridtextColumn instead of using a DataGridTemplateColumn, here is the derived column class:
Public Class DerivedColumn
Inherits DataGridTextColumn
Protected Overloads Overrides Function GenerateElement(ByVal oCell As DataGridCell, ByVal oDataItem As Object) As FrameworkElement
Dim oElement = MyBase.GenerateElement(oCell, oDataItem)
Return oElement
End Function
Protected Overloads Overrides Function GenerateEditingElement(ByVal oCell As DataGridCell, ByVal oDataItem As Object) As FrameworkElement
Dim oUc As New UcSelect
Dim oBinding As Binding = CType(Me.Binding, Binding)
oUc.SetBinding(UcSelect.UcTextProperty, oBinding)
Return oUc
End Function
End Class
The column is used in xaml in the following way:
<local:DerivedColumn Header="Usercontrol" Binding="{Binding FirstName, Mode=TwoWay}"></local:DerivedColumn>
If I start my program all seems to be fine, but changes I make in the custom column are not reflected in the object (property "FirstName"), the changes are simply rolled back when leaving the cell.
I think there must be something wrong with my GenerateEditingElement code, but have no idea ...
Any Help would really be appreciated
Regards
Klaus
Hello,
the related Questions couldn't help me very much.
How can i loop through a HashMap in jsp like this example:
<%
HashMap<String, String> countries = MainUtils.getCountries(l);
%>
<select name="ccountry" id="ccountry" >
<% //HERE I NEED THE LOOP %>
</select>*<br/>
Say I have this list
List<string> sampleList = new List<string>
{
"C:\\Folder1",
"D:\\Folder2",
"C:\\Folder1\\Folder3",
"C:\\Folder111\\Folder4"
};
I'd like to remove the paths that are contained in other folders, for example we have C:\Folder1 and C:\Folder1\Folder3
the second entry should go away because C:\Folder1 contains C:\Folder1\Folder3
is there something that does that in the .net framework or do i have to write the algo myself?
How can I perform bitwise operations on strings in ruby?
I would like to do bitwise & a 4-byte string with a 4-byte long hex such as ("abcd" & 0xDA2DFFD3). I cannot get the byte values of the string. Thanks for your help.
Can anyone please identify is there any possible memory leaks in following code. I have tried with .Net Memory Profiler and it says "CreateEncryptor" and some other functions are leaving unmanaged memory leaks as I have confirmed this using Performance Monitors.
but there are already dispose, clear, close calls are placed wherever possible please advise me accordingly. its a been urgent.
public static string Encrypt(string plainText, string key)
{
//Set up the encryption objects
byte[] encryptedBytes = null;
using (AesCryptoServiceProvider acsp = GetProvider(Encoding.UTF8.GetBytes(key)))
{
byte[] sourceBytes = Encoding.UTF8.GetBytes(plainText);
using (ICryptoTransform ictE = acsp.CreateEncryptor())
{
//Set up stream to contain the encryption
using (MemoryStream msS = new MemoryStream())
{
//Perform the encrpytion, storing output into the stream
using (CryptoStream csS = new CryptoStream(msS, ictE, CryptoStreamMode.Write))
{
csS.Write(sourceBytes, 0, sourceBytes.Length);
csS.FlushFinalBlock();
//sourceBytes are now encrypted as an array of secure bytes
encryptedBytes = msS.ToArray(); //.ToArray() is important, don't mess with the buffer
csS.Close();
}
msS.Close();
}
}
acsp.Clear();
}
//return the encrypted bytes as a BASE64 encoded string
return Convert.ToBase64String(encryptedBytes);
}
private static AesCryptoServiceProvider GetProvider(byte[] key)
{
AesCryptoServiceProvider result = new AesCryptoServiceProvider();
result.BlockSize = 128;
result.KeySize = 256;
result.Mode = CipherMode.CBC;
result.Padding = PaddingMode.PKCS7;
result.GenerateIV();
result.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
byte[] RealKey = GetKey(key, result);
result.Key = RealKey;
// result.IV = RealKey;
return result;
}
private static byte[] GetKey(byte[] suggestedKey, SymmetricAlgorithm p)
{
byte[] kRaw = suggestedKey;
List<byte> kList = new List<byte>();
for (int i = 0; i < p.LegalKeySizes[0].MaxSize; i += 8)
{
kList.Add(kRaw[(i / 8) % kRaw.Length]);
}
byte[] k = kList.ToArray();
return k;
}