Skip to content

Commit

Permalink
fix: accept intent fix
Browse files Browse the repository at this point in the history
  • Loading branch information
MdTeach committed Jun 27, 2023
1 parent 27281f5 commit c82d6e1
Show file tree
Hide file tree
Showing 20 changed files with 200 additions and 93 deletions.
9 changes: 6 additions & 3 deletions Sources/Chat/Conversation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -104,16 +104,19 @@ extension PushChat {
let secretKey = try Pgp.pgpDecrypt(
cipherText: encryptedSecret, toPrivateKeyArmored: privateKeyArmored)

let userMsg = AESCBCHelper.decrypt(cipherText: message, secretKey: secretKey)!
guard let userMsg = try AESCBCHelper.decrypt(cipherText: message, secretKey: secretKey) else {
throw PushChat.ChatError.dectyptionFalied
}

let userMsgStr = String(data: userMsg, encoding: .utf8)

if userMsgStr == nil {
return "Unable to decrypt message"
throw PushChat.ChatError.dectyptionFalied
}

return userMsgStr!
} catch {
return "Unable to decrypt message"
throw PushChat.ChatError.dectyptionFalied
}
}
}
4 changes: 3 additions & 1 deletion Sources/Chat/Inbox.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,11 @@ public struct PushChat {
var chats: [Feeds]
}

enum ChatError: Error {
public enum ChatError: Error {
case invalidAddress
case decryptedPrivateKeyNecessary
case userNotFound
case dectyptionFalied
case chatError(String)
}

Expand Down
21 changes: 14 additions & 7 deletions Sources/Chat/Send.swift
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ extension PushChat {
) throws -> (String, String, String) {

let aesKey = getRandomHexString(length: 15)
let cipherText = AESCBCHelper.encrypt(messageText: messageContent, secretKey: aesKey)
let cipherText = try AESCBCHelper.encrypt(messageText: messageContent, secretKey: aesKey)
let encryptedAES = try Pgp.pgpEncryptV2(
message: aesKey, pgpPublicKeys: publicKeys)

Expand Down Expand Up @@ -139,8 +139,14 @@ extension PushChat {
}

static func getP2PChatPublicKeys(_ options: SendOptions) async throws -> [String] {
let anotherUser = try await PushUser.get(account: options.receiverAddress, env: options.env)!
let senderUser = try await PushUser.get(account: options.account, env: options.env)!
guard
let anotherUser = try await PushUser.get(account: options.receiverAddress, env: options.env)
else {
throw PushChat.ChatError.userNotFound
}
guard let senderUser = try await PushUser.get(account: options.account, env: options.env) else {
throw PushChat.ChatError.userNotFound
}
let publicKeys = [senderUser.getPGPPublickey(), anotherUser.getPGPPublickey()]

// validate the public keys else return empty
Expand Down Expand Up @@ -214,7 +220,8 @@ extension PushChat {

public static func sendIntent(_ sendOptions: SendOptions) async throws -> Message {
// check if user exists
let anotherUser = try await PushUser.get(account: sendOptions.receiverAddress, env: sendOptions.env)
let anotherUser = try await PushUser.get(
account: sendOptions.receiverAddress, env: sendOptions.env)

// else create the user frist and send unencrypted intent message
if anotherUser == nil {
Expand Down Expand Up @@ -247,7 +254,7 @@ extension PushChat {
throw URLError(.badServerResponse)
}

return String(data: data, encoding: .utf8)!
return try data.toString()
}

static func getApprovePayload(_ approveOptions: ApproveOptions) async throws
Expand All @@ -263,9 +270,9 @@ extension PushChat {
fromDID: approveOptions.fromDID,
toDID: approveOptions.toDID, status: "Approved")

let jsonString = try JSONEncoder().encode(apiData).toString()
let hash = generateSHA256Hash(
msg:
String(data: try JSONEncoder().encode(apiData), encoding: .utf8)!
msg: jsonString
)

let sig = try Pgp.sign(message: hash, privateKey: approveOptions.privateKey)
Expand Down
19 changes: 9 additions & 10 deletions Sources/Helpers/Chat/GetInboxList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,18 @@ private func decryptAndVerifySignature(
message: Message
) async throws -> String {
do {
print("doing")
let secretKey: String = try Pgp.pgpDecrypt(
cipherText: encryptedSecretKey, toPrivateKeyArmored: privateKeyArmored)

print("doing")
let userMsg = AESCBCHelper.decrypt(cipherText: cipherText, secretKey: secretKey)!
print("doing")
let userMsgStr = String(data: userMsg, encoding: .utf8)!
print("User", userMsg)
guard let userMsg = try AESCBCHelper.decrypt(cipherText: cipherText, secretKey: secretKey)
else {
throw PushChat.ChatError.chatError("Failed to decrypt the private key")
}

let userMsgStr = try userMsg.toString()
return userMsgStr
} catch {
return "Abishek Unable to decrypt message \(error)"
return "Unable to decrypt message \(error)"
}
}

Expand Down Expand Up @@ -73,8 +73,7 @@ public func getInboxLists(
pgpPrivateKey: String?,
env: ENV
) async throws -> [PushChat.Feeds] {
let connectedUser = try await PushUser.get(account: user, env: env)
if connectedUser == nil {
guard let connectedUser = try await PushUser.get(account: user, env: env) else {
throw PushChat.ChatError.invalidAddress
}
var feeds: [PushChat.Feeds] = []
Expand Down Expand Up @@ -123,7 +122,7 @@ public func getInboxLists(
if toDecrypt {
return try await decryptFeeds(
feeds: feeds,
connectedUser: connectedUser!,
connectedUser: connectedUser,
pgpPrivateKey: pgpPrivateKey,
env: env
)
Expand Down
38 changes: 23 additions & 15 deletions Sources/Helpers/Crypto/AESCBC.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,37 @@ import CryptoKit
import Foundation

public struct AESCBCHelper {
public static func decrypt(cipherText: String, secretKey: String) -> Data? {
let (secret, iv, chiper) = AESCBCHelper.getAESParams(
public static func decrypt(cipherText: String, secretKey: String) throws -> Data? {
let (secret, iv, chiper) = try AESCBCHelper.getAESParams(
ciphertextCombined: cipherText, passPhrase: secretKey)

let dec = AESCBCHelper._decrypt(data: chiper, key: secret, iv: iv)
return dec
}

public static func encrypt(messageText: String, secretKey: String) -> String {
// let _secrectKey = encodeToBase64(secretKey)
let passcode = secretKey.data(using: .utf8)!
public enum AES_CBC_ERROR: Error {
case AES_CBC_DECRYPTION_FAILED
case FAILED_TO_DECODE_AES_PARAMS
}

public static func encrypt(messageText: String, secretKey: String) throws -> String {
let passcode = try secretKey.toData()

let cipherTextPrefix = "Salted__".data(using: .utf8)!
let cipherTextPrefix = try "Salted__".toData()
let salt = getRandomBytes(length: 8)

let messageData = messageText.data(using: .utf8)!
let messageData = try messageText.toData()

let (originalkey, iv) = deriveKeyAndIV(passcode: passcode, salt: salt)

let originalCipher = _encrypt(data: messageData, key: originalkey, iv: iv)!
let originalCipher = try _encrypt(data: messageData, key: originalkey, iv: iv)
let cipherPacked = cipherTextPrefix + salt + originalCipher
let cipherBase64 = cipherPacked.base64EncodedString()

return cipherBase64
}

static func _encrypt(data: Data, key: Data, iv: Data) -> Data? {
static func _encrypt(data: Data, key: Data, iv: Data) throws -> Data {
// Output buffer (with padding)
let outputLength = data.count + kCCBlockSizeAES128
var outputBuffer = [UInt8](
Expand All @@ -49,7 +53,7 @@ public struct AESCBCHelper {
outputLength,
&numBytesEncrypted)
guard status == kCCSuccess else {
return nil
throw AESCBCHelper.AES_CBC_ERROR.AES_CBC_DECRYPTION_FAILED
}
let outputBytes = outputBuffer.prefix(numBytesEncrypted)
return Data(outputBytes)
Expand Down Expand Up @@ -83,12 +87,16 @@ public struct AESCBCHelper {
return Data(outputBytes)
}

public static func getAESParams(ciphertextCombined: String, passPhrase: String) -> (
public static func getAESParams(ciphertextCombined: String, passPhrase: String) throws -> (
Data, Data, Data
) {
guard let cipherDataAll = Data(base64Encoded: ciphertextCombined) else {
throw UtilsError.RUNTIME_ERROR("String")
}

let cipherDataAll = Data(base64Encoded: ciphertextCombined)!
let passcode = passPhrase.data(using: .utf8)!
guard let passcode = passPhrase.data(using: .utf8) else {
throw UtilsError.RUNTIME_ERROR("String")
}

let salt = cipherDataAll[8..<16]
let ciphertext = cipherDataAll[16...]
Expand Down Expand Up @@ -128,7 +136,7 @@ func deriveKeyAndIV(passcode: Data, salt: Data) -> (Data, Data) {
return (originalkey, iv)
}

func encodeToBase64(_ string: String) -> String {
let data = string.data(using: .utf8)!
func encodeToBase64(_ string: String) throws -> String {
let data = try string.toData()
return data.base64EncodedString()
}
6 changes: 3 additions & 3 deletions Sources/Helpers/Crypto/AESGCM.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,14 @@ public struct AESGCMHelper {
)

let res = try AES.GCM.open(box, using: derivedKey)
return String(data: res, encoding: .utf8)!
return try res.toString()
}

public static func encrypt(message: String, secret: String, nonceHex: String, saltHex: String)
throws -> String
{
// Chat AES Info
let messageData = message.data(using: .utf8)!
let messageData = try message.toData()
let nonce = hexToData(characters: nonceHex)
let salt = hexToData(characters: saltHex)

Expand Down Expand Up @@ -112,7 +112,7 @@ public struct AESGCMHelper {
)
let sealedBox = try AES.GCM.SealedBox(combined: cipherData)
let decryptedData = try AES.GCM.open(sealedBox, using: derivedKey)
return String(data: decryptedData, encoding: .utf8)!
return try decryptedData.toString()
}

func encryptAES(message: Data, key: SymmetricKey) throws -> Data {
Expand Down
7 changes: 4 additions & 3 deletions Sources/Helpers/Crypto/Pgp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,14 @@ public struct Pgp {

public func getSecretKey() -> String {
let pgpsec = Armor.armored(self.secretKey, as: .secretKey)
return filterPgpInfo(pgpsec)
return pgpsec
// return filterPgpInfo(pgpsec)
}

public static func GenerateNewPgpPair() throws -> Self {
let key = KeyGenerator(
algorithm: .RSA, keyBitsLength: 2048, cipherAlgorithm: .AES128, hashAlgorithm: .SHA256
).generate(for: "", passphrase: "")
algorithm: .RSA, keyBitsLength: 2048, cipherAlgorithm: .plaintext, hashAlgorithm: .SHA256
).generate(for: "", passphrase: nil)

let publicKey = try key.export(keyType: .public)
let secretKey = try key.export(keyType: .secret)
Expand Down
26 changes: 26 additions & 0 deletions Sources/Helpers/Crypto/Utils.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,32 @@
import CryptoKit
import Foundation

extension String {
enum ConversionError: Error {
case encodingFailed
}

func toData(using encoding: String.Encoding = .utf8) throws -> Data {
guard let data = self.data(using: encoding) else {
throw ConversionError.encodingFailed
}
return data
}
}

extension Data {
enum ConversionError: Error {
case encodingFailed
}

func toString(using encoding: String.Encoding = .utf8) throws -> String {
guard let str = String(data: self, encoding: .utf8) else {
throw ConversionError.encodingFailed
}
return str
}
}

public func generateSHA256Hash(msg: String) -> String {
let data = msg.data(using: .utf8)!
let hash = SHA256.hash(data: data)
Expand Down
5 changes: 5 additions & 0 deletions Sources/Helpers/Errors.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
public enum UtilsError: Error {
case ERROR_CONVERTING_ENCRYPTED_PRIVATEkEY_TO_DATA
case ERROR_CONVERTING_MSG_HASH_TO_DATA
case RUNTIME_ERROR(String)
}
20 changes: 11 additions & 9 deletions Sources/User/CreateUser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,6 @@ extension PushUser {
public var level: ProgressLevel
}

public enum UserError: Error {
case ONE_OF_ACCOUNT_OR_SIGNER_REQUIRED
case INVALID_ETH_ADDRESS
case RUNTIME_ERROR(String)
}

private struct CreateUserHashData: Encodable {
var caip10: String
var did: String
Expand Down Expand Up @@ -116,8 +110,11 @@ extension PushUser {
let encryptedPrivateKey: EncryptedPrivateKeyV2 = try await keyPairs.encryptPGPKey(
wallet: wallet)

let encryptedPrivateKeyString = String(
data: try JSONEncoder().encode(encryptedPrivateKey), encoding: .utf8)!
guard let encryptedPrivateKeyData = try? JSONEncoder().encode(encryptedPrivateKey),
let encryptedPrivateKeyString = String(data: encryptedPrivateKeyData, encoding: .utf8)
else {
throw UtilsError.ERROR_CONVERTING_ENCRYPTED_PRIVATEkEY_TO_DATA
}

options.progressHook?(
ProgressHookType(
Expand All @@ -134,10 +131,15 @@ extension PushUser {
encryptedPrivateKey: encryptedPrivateKeyString
)

guard let apiDataString = String(data: try JSONEncoder().encode(apiData), encoding: .utf8)
else {
throw UtilsError.ERROR_CONVERTING_MSG_HASH_TO_DATA
}
let hash = generateSHA256Hash(
msg:
String(data: try JSONEncoder().encode(apiData), encoding: .utf8)!
apiDataString
)

let _ = try await wallet.getEip191Signature(message: hash, version: "v2")

let updatedData = CreateUserAPIOptions(
Expand Down
5 changes: 4 additions & 1 deletion Sources/User/DecryptPgp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ extension PushUser {

let wallet = try await Wallet(signer: signer)

let jsonData = encryptedPrivateKey.data(using: .utf8)!
guard let jsonData = encryptedPrivateKey.data(using: .utf8) else {
throw UtilsError.ERROR_CONVERTING_ENCRYPTED_PRIVATEkEY_TO_DATA
}

let decoder = JSONDecoder()
let pp = try decoder.decode(EncryptedPrivateKey.self, from: jsonData)

Expand Down
Loading

0 comments on commit c82d6e1

Please sign in to comment.