I am writing 3DES (using SHA1 HASH) encryption algorithm using C #. Key size error - sha1

I am writing 3DES (using SHA1 HASH) encryption algorithm using C #.
Size error in tdes.Key = keyArray of the following code. I do not know what went wrong.
public static string Encrypt(string toEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
// Get the key from config file
string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
//System.Windows.Forms.MessageBox.Show(key);
if (useHashing)
{
SHA1CryptoServiceProvider objSHA1CryptoService = new SHA1CryptoServiceProvider();
keyArray = objSHA1CryptoService.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
objSHA1CryptoService.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
}

Related

iOS using CryptoSwift Encryption AES/CBC/PKCS5PADDING Equivalent encryption with java not working properly

I am building a swift application where I need to have AES/CBC/PKCS5PADDING Encryption type. To encrypt API params and decrypt API response.
I have successfully added in android java and that works fine.
Now I am trying to implement the same formate type of encryption 'AES/CBC/PKCS5PADDING' cipher size 16 in swift.
Problem: I am getting different encryption result for both android and iOS
Example:
String: Hi how are u
Encrypted String for android: +A3p093WWrXU3Ey9i/Lv1Q==
Encrypted String for swift(iOS): Bp23PQX6yaCghvKFTieJDw==
Swift Implementation
import Foundation
import CommonCrypto
func aesEncrypt(key: String, iv: String, message: String) throws -> String{
let data = message.data(using: .utf8)!
// let enc = try AES(key: key, iv: iv, padding: .pkcs5).encrypt([UInt8](data))
let enc = try AES(key: Array(key.utf8), blockMode: CBC(iv: Array(iv.utf8)), padding: .pkcs5).encrypt([UInt8](data))
let encryptedData = Data(enc)
return encryptedData.base64EncodedString()
}
func aesDecrypt(key: String, iv: String, message: String) throws -> String {
let data = NSData(base64Encoded: message, options: NSData.Base64DecodingOptions(rawValue: 0))!
let dec = try AES(key: key, iv: iv, padding: .pkcs5).decrypt([UInt8](data))
let decryptedData = Data(dec)
return String(bytes: decryptedData.bytes, encoding: .utf8) ?? "Could not decrypt"
}
Android Implementation
package com.example.uribanew.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class EncrytData {
private static String CIPHER_NAME = "AES/CBC/PKCS5PADDING";
private static int CIPHER_KEY_LEN = 16; //128 bits
private static String KEY = ""; // key to use should be 16 bytes long (128 bits)
private static String IV = ""; // initialization vector
/**
* Encrypt data using AES Cipher (CBC) with 128 bit key
*
* #param data - data to encrypt
* #return encryptedData data in base64 encoding with iv attached at end after a :
*/
public static String encrypt(String data) {
try {
IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes("UTF-8"));
SecretKeySpec secretKey = new SecretKeySpec(fixKey(KEY).getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance(EncrytData.CIPHER_NAME);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
byte[] encryptedData = cipher.doFinal((data.getBytes()));
String encryptedDataInBase64 = android.util.Base64.encodeToString(encryptedData, android.util.Base64.DEFAULT); //Base64.getEncoder().encodeToString(encryptedData);
return encryptedDataInBase64;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private static String fixKey(String key) {
if (key.length() < EncrytData.CIPHER_KEY_LEN) {
int numPad = EncrytData.CIPHER_KEY_LEN - key.length();
for (int i = 0; i < numPad; i++) {
key += "0"; //0 pad to len 16 bytes
}
return key;
}
if (key.length() > EncrytData.CIPHER_KEY_LEN) {
return key.substring(0, CIPHER_KEY_LEN); //truncate to 16 bytes
}
return key;
}
/**
* Decrypt data using AES Cipher (CBC) with 128 bit key
*
* #param data - encrypted data with iv at the end separate by :
* #return decrypted data string
*/
public static String decrypt(String data) {
try {
IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes("UTF-8"));
// SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
SecretKeySpec secretKey = new SecretKeySpec(fixKey(KEY).getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance(EncrytData.CIPHER_NAME);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
byte[] decodedEncryptedData = android.util.Base64.decode(data, android.util.Base64.DEFAULT); //Base64.getDecoder().decode(parts[0]);
byte[] original = cipher.doFinal(decodedEncryptedData);
return new String(original);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
Please let me know why with the same encryption type I am getting different encrypted string for both android and iOS. Let me know what I am doing wrong

Compatible AES encryption and decryption for Flutter and javascript

I am trying to write two functions in flutter and Javascript which I can use throughout my project to encrypt or decrypt data using AES when data is exchanged.
For Flutter, I am using the pointycastle package based on instructions
https://gist.github.com/proteye/e54eef1713e1fe9123d1eb04c0a5cf9b?signup=true
import 'dart:convert';
import 'dart:typed_data';
import "package:pointycastle/export.dart";
import "./convert_helper.dart";
// AES key size
const KEY_SIZE = 32; // 32 byte key for AES-256
const ITERATION_COUNT = 1000;
class AesHelper {
static const CBC_MODE = 'CBC';
static const CFB_MODE = 'CFB';
static Uint8List deriveKey(dynamic password,
{String salt = '',
int iterationCount = ITERATION_COUNT,
int derivedKeyLength = KEY_SIZE}) {
if (password == null || password.isEmpty) {
throw new ArgumentError('password must not be empty');
}
if (password is String) {
password = createUint8ListFromString(password);
}
Uint8List saltBytes = createUint8ListFromString(salt);
Pbkdf2Parameters params =
new Pbkdf2Parameters(saltBytes, iterationCount, derivedKeyLength);
KeyDerivator keyDerivator =
new PBKDF2KeyDerivator(new HMac(new SHA256Digest(), 64));
keyDerivator.init(params);
return keyDerivator.process(password);
}
static Uint8List pad(Uint8List src, int blockSize) {
var pad = new PKCS7Padding();
pad.init(null);
int padLength = blockSize - (src.length % blockSize);
var out = new Uint8List(src.length + padLength)..setAll(0, src);
pad.addPadding(out, src.length);
return out;
}
static Uint8List unpad(Uint8List src) {
var pad = new PKCS7Padding();
pad.init(null);
int padLength = pad.padCount(src);
int len = src.length - padLength;
return new Uint8List(len)..setRange(0, len, src);
}
static String encrypt(String password, String plaintext,
{String mode = CBC_MODE}) {
Uint8List derivedKey = deriveKey(password);
KeyParameter keyParam = new KeyParameter(derivedKey);
BlockCipher aes = new AESFastEngine();
var rnd = FortunaRandom();
rnd.seed(keyParam);
Uint8List iv = rnd.nextBytes(aes.blockSize);
BlockCipher cipher;
ParametersWithIV params = new ParametersWithIV(keyParam, iv);
switch (mode) {
case CBC_MODE:
cipher = new CBCBlockCipher(aes);
break;
case CFB_MODE:
cipher = new CFBBlockCipher(aes, aes.blockSize);
break;
default:
throw new ArgumentError('incorrect value of the "mode" parameter');
break;
}
cipher.init(true, params);
Uint8List textBytes = createUint8ListFromString(plaintext);
Uint8List paddedText = pad(textBytes, aes.blockSize);
Uint8List cipherBytes = _processBlocks(cipher, paddedText);
Uint8List cipherIvBytes = new Uint8List(cipherBytes.length + iv.length)
..setAll(0, iv)
..setAll(iv.length, cipherBytes);
return base64.encode(cipherIvBytes);
}
static String decrypt(String password, String ciphertext,
{String mode = CBC_MODE}) {
Uint8List derivedKey = deriveKey(password);
KeyParameter keyParam = new KeyParameter(derivedKey);
BlockCipher aes = new AESFastEngine();
Uint8List cipherIvBytes = base64.decode(ciphertext);
Uint8List iv = new Uint8List(aes.blockSize)
..setRange(0, aes.blockSize, cipherIvBytes);
BlockCipher cipher;
ParametersWithIV params = new ParametersWithIV(keyParam, iv);
switch (mode) {
case CBC_MODE:
cipher = new CBCBlockCipher(aes);
break;
case CFB_MODE:
cipher = new CFBBlockCipher(aes, aes.blockSize);
break;
default:
throw new ArgumentError('incorrect value of the "mode" parameter');
break;
}
cipher.init(false, params);
int cipherLen = cipherIvBytes.length - aes.blockSize;
Uint8List cipherBytes = new Uint8List(cipherLen)
..setRange(0, cipherLen, cipherIvBytes, aes.blockSize);
Uint8List paddedText = _processBlocks(cipher, cipherBytes);
Uint8List textBytes = unpad(paddedText);
return new String.fromCharCodes(textBytes);
}
static Uint8List _processBlocks(BlockCipher cipher, Uint8List inp) {
var out = new Uint8List(inp.lengthInBytes);
for (var offset = 0; offset < inp.lengthInBytes;) {
var len = cipher.processBlock(inp, offset, out, offset);
offset += len;
}
return out;
}
}
and class flutter convert_helper.dart
import "dart:typed_data";
import 'dart:convert';
import 'package:convert/convert.dart' as convert;
Uint8List createUint8ListFromString(String s) {
var ret = new Uint8List(s.length);
for (var i = 0; i < s.length; i++) {
ret[i] = s.codeUnitAt(i);
}
return ret;
}
Uint8List createUint8ListFromHexString(String hex) {
var result = new Uint8List(hex.length ~/ 2);
for (var i = 0; i < hex.length; i += 2) {
var num = hex.substring(i, i + 2);
var byte = int.parse(num, radix: 16);
result[i ~/ 2] = byte;
}
return result;
}
Uint8List createUint8ListFromSequentialNumbers(int len) {
var ret = new Uint8List(len);
for (var i = 0; i < len; i++) {
ret[i] = i;
}
return ret;
}
String formatBytesAsHexString(Uint8List bytes) {
var result = new StringBuffer();
for (var i = 0; i < bytes.lengthInBytes; i++) {
var part = bytes[i];
result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}');
}
return result.toString();
}
List<int> decodePEM(String pem) {
var startsWith = [
"-----BEGIN PUBLIC KEY-----",
"-----BEGIN PRIVATE KEY-----",
"-----BEGIN ENCRYPTED MESSAGE-----",
"-----BEGIN PGP PUBLIC KEY BLOCK-----\r\nVersion: React-Native-OpenPGP.js 0.1\r\nComment: http://openpgpjs.org\r\n\r\n",
"-----BEGIN PGP PRIVATE KEY BLOCK-----\r\nVersion: React-Native-OpenPGP.js 0.1\r\nComment: http://openpgpjs.org\r\n\r\n",
];
var endsWith = [
"-----END PUBLIC KEY-----",
"-----END PRIVATE KEY-----",
"-----END ENCRYPTED MESSAGE-----",
"-----END PGP PUBLIC KEY BLOCK-----",
"-----END PGP PRIVATE KEY BLOCK-----",
];
bool isOpenPgp = pem.indexOf('BEGIN PGP') != -1;
for (var s in startsWith) {
if (pem.startsWith(s)) {
pem = pem.substring(s.length);
}
}
for (var s in endsWith) {
if (pem.endsWith(s)) {
pem = pem.substring(0, pem.length - s.length);
}
}
if (isOpenPgp) {
var index = pem.indexOf('\r\n');
pem = pem.substring(0, index);
}
pem = pem.replaceAll('\n', '');
pem = pem.replaceAll('\r', '');
return base64.decode(pem);
}
List<int> decodeHex(String hex) {
hex = hex
.replaceAll(':', '')
.replaceAll('\n', '')
.replaceAll('\r', '')
.replaceAll('\t', '');
return convert.hex.decode(hex);
}
For the Javascript solution, I am using CryptoJS
var AESKey = "20190225165436_15230006321670000"
cc = CryptoJS.AES.encrypt( ("abcdef ha ha "), AESKey, { mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 } ).toString()
CryptoJS.AES.decrypt(cc, AESKey).toString(CryptoJS.enc.Utf8); //return abcdef ha ha
Both solutions work well within their own environment, however, the flutter or Javascript hashes can't be exchanged, they will not decrypt. My guess is that the character encoding has something to do with it, hence why the base64 sizes differ so much. Does anyone have an idea to get this working together? Thanks!
Does anyone have an idea to get this working together?
import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:tuple/tuple.dart';
import 'package:encrypt/encrypt.dart' as encrypt;
String encryptAESCryptoJS(String plainText, String passphrase) {
try {
final salt = genRandomWithNonZero(8);
var keyndIV = deriveKeyAndIV(passphrase, salt);
final key = encrypt.Key(keyndIV.item1);
final iv = encrypt.IV(keyndIV.item2);
final encrypter = encrypt.Encrypter(
encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: "PKCS7"));
final encrypted = encrypter.encrypt(plainText, iv: iv);
Uint8List encryptedBytesWithSalt = Uint8List.fromList(
createUint8ListFromString("Salted__") + salt + encrypted.bytes);
return base64.encode(encryptedBytesWithSalt);
} catch (error) {
throw error;
}
}
String decryptAESCryptoJS(String encrypted, String passphrase) {
try {
Uint8List encryptedBytesWithSalt = base64.decode(encrypted);
Uint8List encryptedBytes =
encryptedBytesWithSalt.sublist(16, encryptedBytesWithSalt.length);
final salt = encryptedBytesWithSalt.sublist(8, 16);
var keyndIV = deriveKeyAndIV(passphrase, salt);
final key = encrypt.Key(keyndIV.item1);
final iv = encrypt.IV(keyndIV.item2);
final encrypter = encrypt.Encrypter(
encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: "PKCS7"));
final decrypted =
encrypter.decrypt64(base64.encode(encryptedBytes), iv: iv);
return decrypted;
} catch (error) {
throw error;
}
}
Tuple2<Uint8List, Uint8List> deriveKeyAndIV(String passphrase, Uint8List salt) {
var password = createUint8ListFromString(passphrase);
Uint8List concatenatedHashes = Uint8List(0);
Uint8List currentHash = Uint8List(0);
bool enoughBytesForKey = false;
Uint8List preHash = Uint8List(0);
while (!enoughBytesForKey) {
int preHashLength = currentHash.length + password.length + salt.length;
if (currentHash.length > 0)
preHash = Uint8List.fromList(
currentHash + password + salt);
else
preHash = Uint8List.fromList(
password + salt);
currentHash = md5.convert(preHash).bytes;
concatenatedHashes = Uint8List.fromList(concatenatedHashes + currentHash);
if (concatenatedHashes.length >= 48) enoughBytesForKey = true;
}
var keyBtyes = concatenatedHashes.sublist(0, 32);
var ivBtyes = concatenatedHashes.sublist(32, 48);
return new Tuple2(keyBtyes, ivBtyes);
}
Uint8List createUint8ListFromString(String s) {
var ret = new Uint8List(s.length);
for (var i = 0; i < s.length; i++) {
ret[i] = s.codeUnitAt(i);
}
return ret;
}
Uint8List genRandomWithNonZero(int seedLength) {
final random = Random.secure();
const int randomMax = 245;
final Uint8List uint8list = Uint8List(seedLength);
for (int i=0; i < seedLength; i++) {
uint8list[i] = random.nextInt(randomMax)+1;
}
return uint8list;
}
Please refer below link for solution.
https://medium.com/#chingsuehok/cryptojs-aes-encryption-decryption-for-flutter-dart-7ca123bd7464
For those people who are looking for a solution for C# (RijndaelManaged & Rfc2898DeriveBytes) and Flutter link
The main problem is that the two key derivation algorithms are different.
In your Dart/PC code you are using PBKDF2, but the KDF used by CryptoJS.AES.encrypt is OpenSSL's EVP_BytesToKey
You could implement the equivalent of EVP_BytesToKey in Dart using PC. However it would probably be easier to change the JavaScript code to derive its key using PBKDF2, which is already supported by CryptoJS. That will give you a key and IV to be used like this:
var encrypted = CryptoJS.AES.encrypt("Message", key, { iv: iv });

Post trade Order Binance Signature error

I am trying to make trade using binance api from ios.
Always gives error ["code": -1022, "msg": Signature for this request is not valid.]
Code:
public override func requestFor(api: APIType) -> NSMutableURLRequest {
let mutableURLRequest = api.mutableRequest
if let key = key, let secret = secret, api.authenticated {
var postData = api.postData
//postData["symbol"] = "BNBBTC"
//postData["timestamp"] = "\(Int(Date().timeIntervalSince1970 * 1000))"
postData["symbol"] = "BNBBTC"
postData["side"] = "SELL"
postData["type"] = "MARKET"
postData["recvWindow"] = "5000"
postData["quantity"] = "0.1"
postData["timestamp"] = "\(Int(Date().timeIntervalSince1970 * 1000))"
if let hmac_sha = try? HMAC(key: secret, variant: .sha256).authenticate(Array(postData.queryString.utf8)) {
let signature = Data(bytes: hmac_sha).toHexString()
postData["signature"] = signature
}
var postDataString = ""
if let data = postData.data, let string = data.string, postData.count > 0 {
postDataString = string
if case .GET = api.httpMethod {
mutableURLRequest.httpBody = data
} else if case .POST = api.httpMethod {
var urlString = mutableURLRequest.url?.absoluteString
urlString?.append("?")
urlString?.append(postData.queryString)
let url = URL(string: urlString!)
mutableURLRequest.url = url
}
api.print("Request Data: \(postDataString)", content: .response)
}
mutableURLRequest.setValue(key, forHTTPHeaderField: "X-MBX-APIKEY")
}
return mutableURLRequest
}
Edit: While using account api i am not facing any issues with the signature. It gives response as expected
I had same ... problem and I found answer. When you generate signature, inputs for Test Order and Account Info are different.
Inputs for account info:
string input = "timestamp=1535623795177";
string apiSecret = "YOUR API SECRET"
Inputs for test limit order:
string input = "symbol=ETHBTC&side=BUY&recvWindow=6500&type=LIMIT&timeInForce=GTC&quantity=100&price=0.1&timestamp=1535623795177";
string apiSecret = "YOUR API SECRET"
and generate signature working example (C#):
private string GenerateSignature(string input, string apiSecret)
{
var encoding = new UTF8Encoding();
byte[] keyByte = encoding.GetBytes(apiSecret);
byte[] messageBytes = encoding.GetBytes(input);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashMessage = hmacsha256.ComputeHash(messageBytes);
return String.Concat(hashMessage.Select(b => b.ToString("x2")));
}
}

IMAP OAuth2 with Chilkat

I was looking for a way to Authenticate an IMAP session with google's Service account
But Since we already use Chilkat how do we do it, I found the following:
http://www.cknotes.com/imap-authentication-using-oauth/
allowing me to send a raw command:
imap.SendRawCommand("AUTHENTICATE XOAUTH <base64_data>");
This shows how to strucure the command:
https://developers.google.com/gmail/xoauth2_protocol
But having trouble putting it all together.
limilabs puts things together nicely in this example:
http://www.limilabs.com/blog/oauth2-gmail-imap-service-account
They have a neat imap.LoginOAUTH2(userEmail, credential.Token.AccessToken); that wraps things up into a command. How do I do this as a raw command for Chilkat?
const string serviceAccountEmail = "service-account-xxxxxx#developer.gserviceaccount.com";
const string serviceAccountCertPath = #"service-xxxxxx.p12";
const string serviceAccountCertPassword = "notasecret";
const string userEmail = "user#domain.com";
X509Certificate2 certificate = new X509Certificate2(
serviceAccountCertPath,
serviceAccountCertPassword,
X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { "https://mail.google.com/" },
User = userEmail
}.FromCertificate(certificate));
bool success = credential.RequestAccessTokenAsync(CancellationToken.None).Result;
using (Chilkat.Imap imap = new Chilkat.Imap())
{
imap.UnlockComponent("unlock-code");
imap.Ssl = true;
imap.Port = 993;
imap.Connect("imap.gmail.com");
var authString = String.Format("user={0}" + "\x001" + "auth=Bearer {1}" + "\x001" + "\x001",userEmail, credential.Token.AccessToken);
var encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(authString));
string response = imap.SendRawCommand("AUTHENTICATE XOAUTH2 " + encoded);
imap.SelectMailbox("Inbox");
bool bUid;
bUid = false;
string mimeStr;
int i;
int n;
n = imap.NumMessages;
for (i = 1; i <= n; i++)
{
// Download the email by sequence number.
mimeStr = imap.FetchSingleAsMime(i, bUid);
Chilkat.Email chilkatEmail = new Chilkat.Email();
chilkatEmail.SetFromMimeText(mimeStr);
Console.WriteLine(chilkatEmail.Subject);
}
imap.CloseMailbox("Inbox");
Console.ReadLine();
}
}

working with NSmutable Dictionary

im trying to do something like this..i have an array with some data. im going to check some condition regarding the data in that array and after that, i want to create a list by using my array objects. i have done this using hashmaps in my android app. i want to do the same thing here..i have heard about NSDictionary..can someone guide me please..
below is my android code..i want to do the same thing in iOS
public ArrayList<HashMap<String, String>> getDuplicated(String date,String startTime,String endTime){
ArrayList<HashMap<String, String>> duplicateList = new ArrayList<HashMap<String, String>>();
JsonParser jp = new JsonParser();
String caregiverID = MainActivity.confirm.toString();
JSONObject param = new JSONObject();
JSONObject job = new JSONObject();
try {
param.put("caregiverPersonId", caregiverID);
job = jp.getJSONFromUrl(param, url);
JSONArray array = job.getJSONArray("d");
if(array.length()>0)
{
JSONObject c1 = array.getJSONObject(0);
JSONObject apoinmentObj1 = c1.getJSONObject(TAG_APOINMENT);
userId = apoinmentObj1.getString("UserId");
}
for (int i=0;i<array.length();i++){
//JSONObject toProcess = forShortList.getJSONObject(i).getJSONObject("Appointment");
JSONObject c = array.getJSONObject(i);
// Storing JSON item in a Variable
JSONObject apoinment = c.getJSONObject(TAG_APOINMENT);
//String fname = c.getJSONObject("PatientProfile").getString(TAG_Fname);
String appoinmntID = apoinment.getString(TAG_APOINMENTID);
JSONObject apoinmentObj = c.getJSONObject(TAG_APOINMENT).getJSONObject("DayTimeSlot");
String fname = c.getJSONObject("PatientProfile").getString(TAG_Fname);
String lname = c.getJSONObject("PatientProfile").getString(TAG_Lname);
String imageUrl = c.getJSONObject("PatientProfile").getString(TAG_url);
if(!imageUrl.equalsIgnoreCase("null")){
if(!imageUrl.equalsIgnoreCase("") ) {
String newUrl = imageUrl.substring(3);
// ActualImage = "http://vardle.paragoncmb.com"+newUrl;
ActualImage = "http://qa.vardle.com/"+newUrl;
}
else{
ActualImage = null;
}
}
else{
ActualImage = null;
}
String timeOfStart = apoinmentObj.getString(TAG_START);
SimpleDateFormat df=new SimpleDateFormat("hh:mm aa");
Date st=df.parse(timeOfStart);
Date st_fromClick = df.parse(startTime);
//String x = df.format(dt);
// Integer st = Integer.valueOf(timeOfStart.substring(0, 2));
// Integer st_fromClick = Integer.valueOf(startTime.substring(0, 2));
String timeOfEnd = apoinmentObj.getString(TAG_END);
// Integer et = Integer.valueOf(timeOfEnd.substring(0, 2));
// Integer et_fromClick = Integer.valueOf(endTime.substring(0, 2));
SimpleDateFormat df2=new SimpleDateFormat("hh:mm aa");
Date et=df.parse(timeOfEnd);
Date et_fromClick = df.parse(endTime);
String jsonDate = apoinmentObj.getString(TAG_DATE);
String ackwardRipOff = jsonDate.replace("/Date(", "").replace(")/", "");
Long Ldat = Long.valueOf(ackwardRipOff);
Date theDate = new Date(Ldat);
String dateOfAppoinmnt = (String) DateFormat.format("MM/dd/yy", theDate);
//HERE IS THE POINT IM TALKNG ABOUT
if((st.before(et_fromClick) && et.after(st_fromClick)) && dateOfAppoinmnt.equalsIgnoreCase(date)){
HashMap<String, String> mapForShort = new HashMap<String, String>();
mapForShort.put(TAG_START, timeOfStart);
mapForShort.put(TAG_END, timeOfEnd);
mapForShort.put(TAG_DATE, dateOfAppoinmnt);
mapForShort.put(TAG_UID, userId);
mapForShort.put(TAG_APOINMENTID, appoinmntID);
mapForShort.put(TAG_Fname, fname);
mapForShort.put(TAG_Lname, lname);
mapForShort.put(TAG_url, ActualImage);
duplicateList.add(mapForShort);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return duplicateList;
}
You can create a new NSMutableDictionary and NSMutableArray:
NSMutableArray* myList = [NSMutableArray array];
NSMutableDictionary* mydictionary = [NSMutableDictionary dictionary];
dictionary[#"TAG_START"] = timeOfStart;
[myList addObject:dictionary];
Take a look at this web site for good beginner tutorials on the various data types, including NSDictionary: http://rypress.com/tutorials/objective-c/data-types/nsdictionary.html

Resources