encrypt PBEWithMD5AndDES in j2me - java-me

i'm triing to get this code to work on j2me
(it is working a java program)
but not yet in j2me
public static String generate(String plaintext, String passphase) throws Exception {
try {
PBEKeySpec pbeKeySpec = new PBEKeySpec(passphase.toCharArray());
PBEParameterSpec pbeParamSpec;
SecretKeyFactory keyFac;
// Salt
byte[] salt = {(byte) 0xc8, (byte) 0x73, (byte) 0x61, (byte) 0x1d, (byte) 0x1a, (byte) 0xf2, (byte) 0xa8, (byte) 0x99};
// Iteration count
int count = 20;
// Create PBE parameter set
pbeParamSpec = new PBEParameterSpec(salt, count);
keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
// Create PBE Cipher
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
// Initialize PBE Cipher with key and parameters
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
// Our cleartext
byte[] cleartext = plaintext.getBytes();
// Encrypt the cleartext
byte[] ciphertext = pbeCipher.doFinal(cleartext);
return ciphertext;
} catch (Exception ex) {
throw new Exception(ex.getMessage());
}
}
i found this lib
http://www.bouncycastle.org/java.html
the important thing is that i find a method for j2me that can encrypt using PBEWithMD5AndDES
anyone know the solution?
edit adding extra info
when i try to add the above code to a mobile project
following classes are not recognized (not included in j2me)
PBEKeySpec
PBEParameterSpec
SecretKeyFactory
so i need a package that allows me to encode plain text using PBEWithMD5AndDES
anyone know such a package compatible with j2me?
thx for the replies so far

A lot can go wrong when applying a primitive, you should use Jasypt.

Related

How to decrypt mp4 PKCS8 encoded file using private key in node js and crypto

I'm trying to decrypt a MP4 file that is encrypted using public key in pkcs8 format in Node JS and private key.
I tried this code:
var decrypted = crypto.privateDecrypt({ key: privateKey, padding: crypto.constants.RSA_PKCS1_PADDING }, buffer);
I'm getting the following error:
Error: error:0406506C:rsa routines:rsa_ossl_private_decrypt:data greater than mod len
I'm currently using this Java code that is working. I would like to swich to Node JS
final byte[] cekWrapped = Base64.getDecoder().decode(conn.getHeaderField("x-amz-meta-x-amz-key").getBytes());
final byte[] iv = Base64.getDecoder().decode(conn.getHeaderField("x-amz-meta-x-amz-iv").getBytes());
// Now we need to decrypt the envelope
Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
cipher.init(DECRYPT_MODE, privateKey);
final byte[] decryptedSymmetricKeyBytes = cipher.doFinal(cekWrapped);
final SecretKeySpec cek = new SecretKeySpec(decryptedSymmetricKeyBytes, "AES");
// Once we have the symmetric master key, we can decrypt the contents
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
try {
cipher.init(DECRYPT_MODE, cek, new IvParameterSpec(iv));
} catch (final InvalidKeyException e) {
System.out.println(
"Invalid key exception. Please make sure that Java Cryptography Extensions with unlimited " +
"jurisdiction are installed");
}
try (final InputStream in = conn.getInputStream()) {
try (final CipherInputStream cis = new CipherInputStream(in, cipher)) {
try (final FileOutputStream fos = new FileOutputStream(destination.toFile())) {
byte[] b = new byte[1024];
int bytesRead;
while ((bytesRead = cis.read(b)) >= 0) {
fos.write(b, 0, bytesRead);
}
}
}
}
RSA uses the difficulty of factoring large semi-primes as it's trap-door function.
As part of the RSA crypto-system two primes are generated during public/private key creation.
We call the two primes p and q. They multiply to form n, which is the modulus (a semi-prime).
Although RSA can be used to to encrypt data directly (via c=m^e mod{n}), you cannot encrypt data larger than the modulus directly.
Therefore if you are using 2048-bit primes to generate n, you can only encrypt 4096-bits of information directly with the keys (in practice even a little less).
Instead, for large data you need to generate a random symmetric key and send it to your counterpart encrypting it with their RSA public key, and then use the agreed key with a symmetric cipher like AES-GCM or xSalsa20.
Really though, you should move to using ECDH over elliptic curves.
tldr: If you encrypt some data with RSA, where data.length > modulus.length, you're gonna get nonsense when you decrypt it.

Cannot Append to Received String in UDP Listener C#

I have a Form that create a UDP object, in the UDP class a UDPClient is created and the received data is done in the BeginReceive Method using EndReceive.
When I print the string of the reveived data, after converting the byte[], to the console from within the beginreceive method, with text appended, only the received data prints not the appended text.
So it looks like the received data is incomplete.
When the string prints, the NewLine and appended "done" is not shown.
Any help would be great!!
Thanks
class Udp
{
public EventHandler _dataReceived;
public Udp()
{
int receiverPort = 1248;
UdpClient receiver = new UdpClient(receiverPort);
string discovery = "<?xml version=\"1.0\"?><ServiceQuery></ServiceQuery>";
receiver.BeginReceive(new AsyncCallback( DataReceived), receiver);
IPEndPoint end = new IPEndPoint(IPAddress.Broadcast, 1248);
receiver.Send(Encoding.ASCII.GetBytes(discovery + "\0"), discovery.Length + 1, end);
}
private void DataReceived(IAsyncResult ar)
{
UdpClient c = (UdpClient)ar.AsyncState;
IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 1248);
Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
string receivedText = ASCIIEncoding.ASCII.GetString(receivedBytes);
Console.WriteLine("\n");
if(_dataReceived != null)
{
Console.Write(receivedIpEndPoint + ": " + receivedText + Environment.NewLine + "done");
_dataReceived(receivedText, new EventArgs());
}
c.BeginReceive(new AsyncCallback(DataReceived), c);
}
}
The simplest repro I can think of for this problem is this code:
private void button1_Click(object sender, EventArgs e) {
Byte[] receivedBytes = new byte[] { 0x48, 0x65, 0x6c, 0x00, 0x6c, 0x6f };
string receivedText = Encoding.ASCII.GetString(receivedBytes);
Console.Write(receivedText + ", you won't see this");
}
Output after clicking the button several times:
HelHelHelHel
Surely you now recognize the poison-pill in the receivedBytes array, it is the presence of the 0x00 byte that causes the output string to get cut short. Nothing beyond that byte makes it into the Visual Studio Output window.
Explaining this behavior requires a pretty deep dive in how Console.Write() in a Winforms app works and how it is capable of generating output, even though your program has no console. It is a long-winded story that isn't that likely to entertain anybody so I'll punt for the short version. With the Visual Studio Hosting Process debugger option enabled, Console.Write() is equivalent to Debug.Write(). Debug output is intercepted by the DefaultTraceListener class, it pinvokes OutputDebugString() to get the text to appear in the debugger trace window. These winapi functions takes C strings, a C string is zero-terminated to indicate the end of the string.
There are several ways to fix this, the programmer's way is to convert the byte[] array content to hex:
Byte[] receivedBytes = new byte[] { 0x48, 0x65, 0x6c, 0x00, 0x6c, 0x6f };
string receivedText = BitConverter.ToString(receivedBytes);
Console.WriteLine(receivedText + ", you see this");
Output:
48-65-6C-00-6C-6F, you see this
48-65-6C-00-6C-6F, you see this
48-65-6C-00-6C-6F, you see this
Or you might want to take a better look at the data you transmit, ensuring it is actually printable text that can be properly converted with Encoding.ASCII

How to sign in using data from WebSecurity tables?

I want to sign users in with the standard WebSecurity tables; but in another language.
For example I have this ASP MVC website. I'm making an app using PHP now that has access to the same database, and I need to know how microsoft's password strategies work.
Here's an example of a table: http://gyazo.com/e55d76186472b17fe8f25481a3a3e1c9
I would guess it's just hash_password= hash(password . salt)
But which hashing does it use, etc etc.
Thanks a lot!
Well, reflector tells me that they use Crypto.HashPassword which looks like:
public static string HashPassword(string password)
{
byte[] salt;
byte[] buffer2;
if (password == null)
{
throw new ArgumentNullException("password");
}
using (System.Security.Cryptography.Rfc2898DeriveBytes bytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, 0x10, 0x3e8))
{
salt = bytes.Salt;
buffer2 = bytes.GetBytes(0x20);
}
byte[] dst = new byte[0x31];
Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
return Convert.ToBase64String(dst);
}

J2ME AES Decryption Error(org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted)

I am doing encryption and decryption using AES Algorithm with bouncy castle
My encryption and decryption works ok but it gives me error when my plain text size is bigger
even sometimes it is giving non decrypted data
public static boolean setEncryptionKey(String keyText)
{
byte[] keyBytes = keyText.getBytes();
key = new KeyParameter(keyBytes);
engine = new AESFastEngine();
cipher = new PaddedBufferedBlockCipher(engine);
return true;
}
Encryption:
public static String encryptString(String plainText)
{
byte[] plainArray = plainText.getBytes();
cipher.init(true, key);
byte[] cipherBytes = new byte[cipher.getOutputSize(plainArray.length)];
int cipherLength = cipher.processBytes(plainArray, 0, plainArray.length, cipherBytes, 0);
cipher.doFinal(cipherBytes, cipherLength);
String cipherString = new String(cipherBytes);
return cipherString;
}
Decryption:
public static String decryptString(String encryptedText)
{
byte[] cipherBytes = encryptedText.getBytes();
cipher.init(false, key);
byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)];
int decryptedLength = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0);
cipher.doFinal(decryptedBytes, decryptedLength);
String decryptedString = new String(decryptedBytes);
int index = decryptedString.indexOf("\u0000");
if (index >= 0)
{
decryptedString = decryptedString.substring(0, index);
}
return decryptedString;
}
This decryption is giving me following error
org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted
at org.bouncycastle.crypto.paddings.PKCS7Padding.padCount(+30)
at org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.doFinal(+190)
at com.NewCrypto.decryptString(NewCrypto.java:103)
at com.New_Midlet.startApp(New_Midlet.java:23)
at javax.microedition.midlet.MIDletProxy.startApp(MIDletProxy.java:44)
at com.sun.midp.midlet.Scheduler.schedule(Scheduler.java:375)
at com.sun.midp.main.Main.runLocalClass(Main.java:477)
at com.sun.midp.main.Main.main(+80)
what could be the problem ?
The line
String cipherString = new String(cipherBytes);
is a bug. cipherBytes is a byte array with arbitrary values and cannot be converted to a string using any of the Java string decoders. You should just send/save the cipher as a byte array. If you must make it a string then you'll have to use an encoder. Base64 encoders are often used, as are Base16 (hex). You can use the Apache Commons Codec or my favorite, the Harder Base64 codec.

AES Encryption/Decryption with Bouncycastle Example in J2ME

i want to Encrypt and Decrypt data in J2ME using AES Algorithm with bouncy castle
can any one give me sample code for that
i want to use ECB with PKCS5Padding
Thanks in Advance.
I'm sure there are examples out there but I haven't found them. Here are a few hints to help you get started. You need to learn how to connect the BC classes together. First, get the bouncycastle source code and be prepared to look at it when you have questions. It's actually very readable so don't be afraid to examine it when the documentation is poor. For example, many classes want an instance of a CipherParameters object, but it is rare for the documentation to specify any more detail. However, in the source code it will be obvious as to which implementing classes are expected.
Choose one of the AES engines, for example AESEngine, as the encryption engine. Next pick a mode; ECB is rarely correct, so for example if you pick CBC mode then create a CBCBlockCipher object from your AESEngine object. Next, use this object to create a PaddedBufferBlockCipher object. The default constructor uses PKCS7 padding which is identical to the PKCS5 padding you want. Now you need to create an object to hold the key and IV. This is the CipherParameters interface. You create the object in two steps. First, you create a KeyParameter object with your key. Next, you create a ParametersWithIV object with your KeyParameter object and your IV. This object is supplied to the init method of the PaddedBufferBlockCipher object and then your are ready to go.
EDIT
Here is small example:
private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data)
throws Exception
{
int minSize = cipher.getOutputSize(data.length);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
int actualLength = length1 + length2;
byte[] result = new byte[actualLength];
System.arraycopy(outBuf, 0, result, 0, result.length);
return result;
}
private static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv) throws Exception
{
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
new AESEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
aes.init(false, ivAndKey);
return cipherData(aes, cipher);
}
private static byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception
{
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
new AESEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
aes.init(true, ivAndKey);
return cipherData(aes, plain);
}

Resources