CCCrypt maximum time it returns nil. What is the problem in Encryption - encryption

I trying to write an encryption (AESCBC128) function based on CCCrypt and the CCCrypt is generating a random value.
for example, when I pass 016768821221 to function it'll return "0oTPFcKNWABTpBGgLlzsjw==" for the same iv and Key.
here's the iv: "khabbababab" and the key is : "khabbababab"
why it returns nil. The encryption is correct but some times it returns nil
extension String {
func aesEncrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
if let keyData = key.data(using: String.Encoding.utf8),
let data = self.data(using: String.Encoding.utf8),
let cryptData = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) {
let keyLength = kCCKeySizeAES128
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = CCOptions(kCCAlgorithmAES128)
let options: CCOptions = UInt32(options)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
CCOptions(options),
(keyData as NSData).bytes, keyLength,
iv,
(data as NSData).bytes, data.count,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
print(String(data: data, encoding: .utf8) as Any)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
let base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
print("succccc")
return base64cryptString
}
else {
print("nill nill llllllllll")
return nil
}
}
return nil
}
func aesDecrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
if let keyData = key.data(using: String.Encoding.utf8),
let data = NSData(base64Encoded: self, options: .ignoreUnknownCharacters),
let cryptData = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) {
let keyLength = size_t(kCCKeySizeAES128)
let operation: CCOperation = UInt32(kCCDecrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(options)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
(keyData as NSData).bytes, keyLength,
iv,
data.bytes, data.length,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
let unencryptedMessage = String(data: cryptData as Data, encoding:String.Encoding.utf8)
return unencryptedMessage
}
else {
return nil
}
}
return nil
}

Your aesEncrypt always passes a keylength of 16 to CCCrypt without checking that the key actually has at least 16 bytes of data.

Related

How to get Modulus and Exponent from RSA private key in iOS Swift?

How to parse RSA private key in order to get modulus(n) and exponent(e) from it?
RSA Private Key Example --->
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEApSrpu9xy2MGlmKBpSarF5w2vGk77DXmU3brJyJxKOLzf4ARo
zjNcfO87T/8F23ES5iOU6z8Y6HUfLKkDHa2IwfraUWDoMudDZTCrROH4bA74TFo/
Mlhh1awotNqB1D24H3wnhkd87BcLVZWv2qDV1SVmWu9xW6GrffyjkWojkqzYwSHT
viPKfWzsQ6cbedN7WUyUZt+78YZlY13fMoXLY26xgxuBYld2vLI3qHooJnRTf32u
8aqM+X52h0/6MoYJgc9zwUTNBWrd3G6GHnRXbYpao56IYAoUtwBJHzQ5md0FVUKH
Vqfk8eJp3YKujYyrpSFKj7rKI/pHHZawnmPQLQIDAQABAoIBABNisgRGn4QpVlJP
oYvv60JvLLodwwGV348WuVA+Z8e5A127psFs7dIMEh4VhI54+wrf6j6iLT47YOlQ
/PiiwYZi9vTONvKiihp6V9/B1fJ431O20+wIy5LUngJ8EvjiNZYccFcmVNcw7Tei
Vf2HGxHlTdomeFuU4hfraxdKKdqxFnvT/lfbo/uX5tN660DSAGd1xRmUf08w9OUU
nG0LVk20hz/dn+WUnF+GnZfFjVI06IwvfMiDN2Z7zXP+IBOH7fDwQZUy6ExnesnR
79iswCEyVx0FFveAMpHvLMUhEKg2iYIRXzD/Oy4sX5pDZT2fE289MtkgZbHxXDLJ
cbucSVECgYEA1/tjvX1zdxGG9wT4zld+WYRa9ax+EeECWqOXn95c3BY3bTUlMQlX
4HlOiYUAzwIf58LaKuTYRjUiv9J9Axw7jkxd4P6Y7BYOatdAfv8PG1Y+SA7r0utM
D37DCesroD0C4IuRc+YzVvjdtvsNDgpKf5cXFKWoNQVX4t4UbUcRaA8CgYEAw8VC
vZieW/eM8yKqna8BFt3siun8ucieh/PGutBfq8W7sdqDb0JZpdWYOj12P/0/9gSG
dlaSpTq7svxTj9wdb5kU1Yp56CWM7wy+adCQvWyMXJ6s/CA8SZM9KCmWt6w4vRAm
+6oElxyT4exYFvXebRN6GXs0TWucuqQ64/z+6AMCgYBn1kC5lVqx4AdXM1i7O21P
dEaW3nst9VPAZ+45uhpC5Zt4MZjT3n4VObz8eKlO3OKh9hgVjzg7aMhwGK5plGU9
oJFx3nV+64u66gnkBJQqvGftFN9j5CQJPxRd7GZo/2wmsHMZmY8NPVC67C/2lBQF
C4rZLluUQiFivQptD0HbGQKBgEOAT5vZ9LhXKdVnnZaTEfgVewsG1OomH2tXBa3C
TUqH+ki/xFPnd8uzUzK5oH090AD+3HIPNa8dCj0Tvag7yDaDfOiIP7JoyChgp4MK
s+1scRU6bQDeCIuB5jNj66DXFBU0bYyWudB0vRTIDjOUgSXw8ke48HbFZRwBpoCX
6jiLAoGAGhHvi9NUPaWv3fpPTQnbo2aaYSXyniW7s5bGgUQmIjuFDo/GHomIh6T/
RJgyQYxBlUqCLs/C6YABa6hce/qMSS0JEt10uqknYfYjZ3jZEZSKPy8vpxaZX6ot
dHruKemEoO1yLKhGI56KCdhWMrfsn7VbY+wCX2S1J/MZjWBIKNY=
-----END RSA PRIVATE KEY-----
func parsePrivateSecKey(privateKey: SecKey) -> (mod: Data, exp: Data) {
let pubAttributes = SecKeyCopyAttributes(privateKey) as! [String: Any]
print("pubAttributes----\(pubAttributes)")
// let keydata = pubAttributes[kSecPrivateKeyAttrs as String] as! [String: Any]
// print("----key data ------===\(keydata)")
let data = Data(base64Encoded: "")
// Check that this is really an RSA key
guard Int(pubAttributes[kSecAttrKeyType as String] as! String)
== Int(kSecAttrKeyTypeRSA as String) else {
// throw "Tried to parse non-RSA key as RSA key"
return (mod: data!, exp: data!)
}
// Check that this is really a private key
guard Int(pubAttributes[kSecAttrKeyClass as String] as! String)
== Int(kSecAttrKeyClassPrivate as String)
else {
// throw "Tried to parse non-private key as private key"
return (mod: data!, exp: data!)
}
let keySize = pubAttributes[kSecAttrKeySizeInBits as String] as! Int
// Extract values
let pubData = pubAttributes[kSecValueData as String] as! Data
print("pubData---\(pubData)")
// SecKeyCopyModulus
//Find modulus data length
let modulusLengthData = pubData.subdata(in: 9..<11)
print(modulusLengthData as NSData)
let modulusLength = BigUInt(modulusLengthData)
print("mod lenth ===\(modulusLength)")
//find MODULUS
var modulus = pubData.subdata(in: 11..<(Int(modulusLength) + 11))
let reqMod = BigUInt(modulus)
print("final modulus====\(reqMod)")
//Find exponent data length
var expDataLength = pubData.subdata(in: (Int(modulusLength) + 11 + 7)..<(Int(modulusLength) + 11 + 7 + 1))
print(expDataLength as NSData)
var bytes_to_find : [UInt8] = [0xFF] //0xFF = 255 size
let datafind = Data(bytes: &bytes_to_find, count: bytes_to_find.count)
let range = expDataLength.range(of: datafind, options: [], in: Range(NSRange(location: 0, length: expDataLength.count)))
var exponentLength = BigUInt(expDataLength)
print("exponent lenth ===\(exponentLength)")
//Find EXPONENT
var exponent = pubData.subdata(in: (Int(modulusLength) + 11 + 7 + 1)..<(Int(modulusLength) + 11 + 7 + 1 + Int(exponentLength)))
//check if its size is 255 or more and get data length accordingly
if range == nil {
expDataLength = pubData.subdata(in: (Int(modulusLength) + 11 + 7)..<(Int(modulusLength) + 11 + 7 + 2))
print("0xFF not found...")
exponentLength = BigUInt(expDataLength)
print("exponent lenth ===\(exponentLength)")
//Find EXPONENT
exponent = pubData.subdata(in: (Int(modulusLength) + 11 + 7 + 1)..<(Int(modulusLength) + 11 + 7 + 2 + Int(exponentLength)))
}
let reqExp = BigUInt(exponent)
print("final exponent====\(reqExp)")
if modulus.count > keySize / 8 { // --> 257 bytes
modulus.removeFirst(1)
}
return (mod: modulus, exp: exponent)
}

How to get gmail attachment into local device store with intent filter

In my application i want to open gmail attachment with my application, i used intent filter for that,
I am getting URI and i want to use that and copy that attachment to my local device and want to display that with my application .
url = {content://com.google.android.gm.sapi/abc#gmail.com/message_attachment_external/%23thread-f%3A1610966348228029097/%23msg-f%3A1610966348228029097/0.1?account_type=com.google&mimeType=application%2Foctet-stream&rendition=1}
After a days of research and implementation, Here is a final solution for gmail attachment file , to view and down load in our application.
[IntentFilter(new string[] { Intent.ActionView }, Categories = new string[] { Intent.CategoryDefault, Intent.CategoryBrowsable }, DataScheme = "content", DataMimeType = "application/octet-stream")]
Stream inputsTream = resolver.OpenInputStream(url);
fs = File.Create(fileName);
byte[] buffer = new byte[32768];
int count;
int offset = 0;
while ((count = inputsTream.Read(buffer, offset, buffer.Length)) > 0)
{
fs.Write(buffer, 0, count);
}
fs.Close();
inputsTream.Close();
private fun deepLinkAcceptor(){
var ins: InputStream? = null
var os: FileOutputStream? = null
var fullPath: String? = null
var file: File;
try {
val action = intent.action
if (Intent.ACTION_VIEW != action) {
return
}
val uri = intent.data
val scheme = uri!!.scheme
var name: String? = null
if (scheme == "content") {
val cursor = contentResolver.query(
uri!!, arrayOf(
MediaStore.MediaColumns.DISPLAY_NAME
), null, null, null
)
cursor!!.moveToFirst()
val nameIndex = cursor!!.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
if (nameIndex >= 0) {
name = cursor!!.getString(nameIndex)
}
} else {
return
}
if (name == null) {
return
}
val n = name.lastIndexOf(".")
val fileName: String
val fileExt: String
if (n == -1) {
return
} else {
fileName = name.substring(0, n)
fileExt = name.substring(n)
}
// create full path to where the file is to go, including name/ext
fullPath = ""
val filenm = fileName + fileExt
file = File(cacheDir, filenm)
ins = contentResolver.openInputStream(uri!!)
os = FileOutputStream(file.getPath())
val buffer = ByteArray(4096)
var count: Int
while (ins!!.read(buffer).also { count = it } > 0) {
os!!.write(buffer, 0, count)
}
os!!.close()
ins!!.close()
println("===onfile path: " + file.getAbsolutePath())
println("===onFile name: " + file.readText())
} catch (e: Exception) {
if (ins != null) {
try {
ins.close()
} catch (e1: Exception) {
}
}
if (os != null) {
try {
os.close()
} catch (e1: Exception) {
}
}
if (fullPath != null) {
val f = File(fullPath)
f.delete()
}
}
}

Range of all linkAttributed String in MutableAttributedString in swift

I have a mutableAttributedString in which few strings are linkAttributed,I want to find the Range of all link attributed string. How to do that in swift3 ?
When user start type # in textview i show list of few name. If user select any row then following method gets called.
func didSelectMemberId(_ model: BaseModel) {
var fullName = ""
if model.entityType == ReceiverType.Active.rawValue{
fullName = model.name
}else{
fullName = AtMention + model.name + " " + model.name2
}
let attributedString = NSMutableAttributedString(string:fullName, attributes:[NSFontAttributeName:(appNeedsAutoResize ? (UIUtils.getFontForApproprieteField(.headlineWithoutBold).font) : UIFont.systemFont(ofSize: 14))])
attributedString.addAttribute(NSLinkAttributeName, value: "connectmention://\(model.entityId.stringValue())", range: NSRange(location: 0, length: fullName.length))
attributedString.append(NSAttributedString(string: emptySpaceStringByUC, attributes:[NSFontAttributeName:(appNeedsAutoResize ? (UIUtils.getFontForApproprieteField(.headlineWithoutBold).font) : UIFont.systemFont(ofSize: 14))]))
self.composeBar.textView.textStorage.insert(attributedString, at:self.composeBar.textView.selectedRange.location)
}
self.composeBar.textView.selectedRange = NSMakeRange(self.composeBar.textView.selectedRange.location+fullName.length, 0 )
To get the link proprty I am using the following method
func getlinkActionRange(attributeString: NSAttributedString) -> [MentionStruct] {
var arrMentions = [MentionStruct]()
_ = attributeString.enumerateAttribute(NSLinkAttributeName, in: NSRange.init(location: 0, length: attributeString.length), options: [], using: { (value, range, stop) in
if let url = value {
let occurrence = (attributeString.string as NSString).substring(with:range)
arrMentions.append(MentionStruct(link: url as! String, text: occurrence, range: range))
}
})
return arrMentions
}
If user type anything after inserting that name , that type string also coming.

Firebase snapshot prints optional

As i run a snapshot from a firebase database below it returns
Optional(498895446)
when i only want it to return
498895446
as an int. I have tried toint() but it is not working as i get an error. How can i get rid of this optional.
let ref = FIRDatabase.database().reference().child("Users + infomation").child(currentuser).child("timeStamp ")
ref.observeSingleEventOfType(.Value, withBlock : {(snapShot) in
let val = snapShot.value
if snapShot.exists(){
print("\(val)")
}
else if snapShot.exists() == false {
print("snappyaintexist")
}
})
Try:-
let ref = FIRDatabase.database().reference().child("Users + infomation").child(currentuser).child("timeStamp ")
ref.observeSingleEventOfType(.Value, withBlock : {(snapShot) in
if let val = snapShot.value as? Int{
print("\(val!)")
}else{
print("snappyaintexist")
}
})

Swift Dictionary Filter

So it looks like the filter function on a Swift (2.x) dictionary returns a tuple array. My question is there an elegant solution to turning it back into a dictionary? Thanks in advance.
let dictionary: [String: String] = [
"key1": "value1",
"key2": "value2",
"key3": "value3"
]
let newTupleArray: [(String, String)] = dictionary.filter { (tuple: (key: String, value: String)) -> Bool in
return tuple.key != "key2"
}
let newDictionary: [String: String] = Dictionary(dictionaryLiteral: newTupleArray) // Error: cannot convert value of type '[(String, String)]' to expected argument type '[(_, _)]'
If you are looking for a more functional approach:
let result = dictionary.filter {
$0.0 != "key2"
}
.reduce([String: String]()) { (var aggregate, elem) in
aggregate[elem.0] = elem.1
return aggregate
}
reduce here is used to construct a new dictionary from the filtered tuples.
Edit: since var parameters has been deprecated in Swift 2.2, you need to create a local mutable copy of aggregate:
let result = dictionary.filter {
$0.0 != "key2"
}
.reduce([String: String]()) { aggregate, elem in
var newAggregate = aggregate
newAggregate[elem.0] = elem.1
return newAggregate
}
You can extend Dictionary so that it takes a sequence of tuples as initial values:
extension Dictionary {
public init<S: SequenceType where S.Generator.Element == (Key, Value)>(_ seq: S) {
self.init()
for (k, v) in seq { self[k] = v }
}
}
and then do
let newDictionary = Dictionary(newTupleArray)

Resources