Converting hmac sha256 to String Swift5 - swift

I am trying to obtain the results of a hmac sha256 as a String ,something similar to this "asdafsdfafs13rfafAafaasdfadfasdfa", but the code snippet below generates this 👇🏻👇🏻 byteArray.
var combinedString = "key1=val1&key2=val2"
//Using import BlueCryptor
let key = CryptoUtils.byteArray(fromHex: apikey!)
let data : [UInt8] = CryptoUtils.byteArray(fromHex: combinedString)
let hmac = HMAC(using: HMAC.Algorithm.sha256, key: key).update(byteArray: data)?.final()
print(hmac)
How do i convert it from a byteArray to a string ?

Related

How to generate RSA private Key in Swift?

I have encrypted a text with a public key generated using modulus and exponent, I followed that link : https://meniny.cn/posts/RSA_public_key_with_modulus_and_exponent/
I want to decrypt that text with a private key generated using another modulus and exponent.I didn't find a function in Swift or Objective-C that solve this issue.
So I use a Java code to get the private key as String and generate also a pem file.
Here is my code :
let PRIVATE_KEY = "MIGxAgEAMA0GCSqGSIb3DQEBAQUABIGcMIGZAgEAAkBXIKDI5NbyZd/d5tO6djSv\rt8GDc7soyNaqSqZq/w9A/zxiZTA0uwnvYv9E+OXKS9yjPCqpu9d1ELzxQxU9KRFD\rAgEAAkAYEBbX5PvIboJpkrqfIM5kSWfUmj3ygaVn2r4jhtX7qS8+0v09fwifoeMP\r5TgmB2B8+47n8+MQ55/cKbMs2QpBAgEAAgEAAgEAAgEAAgEA\r"
let data = PRIVATE_KEY.data(using: String.Encoding.utf8)!
let priv = data.base64EncodedString()
let keyData = Data(base64Encoded: priv)!
let dict = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
kSecAttrKeySizeInBits : NSNumber(value : 128),
] as [CFString : Any]
let key = SecKeyCreateWithData(keyData as NSData, dict as NSDictionary, nil)
let blockSize = SecKeyGetBlockSize(key!)
var encrypted = [UInt8](repeating: 0, count: blockSize)
var encSize = blockSize
let status = SecKeyDecrypt(key!,
SecPadding.PKCS1, x,
x.count, &encrypted,
&encSize)
let decData = NSData(bytes: &encrypted, length: encrypted.count)
let decString = decData.base64EncodedString(options: NSData.Base64EncodingOptions())
I always get nil for key value.
I tried to find a solution but I am unable to get the suitable private key to decrypt correctly my text.
Any help please?

AES encryption using CryptoSwift and CryptoJS

I was to trying encrypt a text using CryptoSwift for ios application, and CryptoJS for web application, which has to be decrypted in Java platform. I could able to encrypt successfully in javascript by using the following code.
var message = "Hello"
var password = "samplepasswordky"
function encrypt(message, password) {
var salt = CryptoJS.enc.Hex.parse("00000000000000000000000000000000");
var key = CryptoJS.PBKDF2(pass, salt, {
keySize: keySize/32,
iterations: iterations
});
var iv = CryptoJS.enc.Hex.parse("00000000000000000000000000000000");
var encrypted = CryptoJS.AES.encrypt(msg, key, {
iv: iv
});
var encryptedMessage = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
return encryptedMessage;
}
For the same in CryptoSwift I am doing the following, but I could not decrypt the text in Java.
let salt: [UInt8] = Array("0000000000000000".utf8)
let password: [UInt8] = Array("samplepasswordky".utf8)
let iv: [UInt8] = Array("0000000000000000".utf8)
let derivedKey = try! PKCS5.PBKDF2(password: password, salt: salt , iterations: 100, keyLength: 16, variant: .sha1).calculate()
let encrypted = try! AES(key: derivedKey, blockMode: CBC(iv: iv), padding: .pkcs5).encrypt(input)
print(encrypted.toHexString())
Kindly help me to make this work.
This line:
var salt = CryptoJS.enc.Hex.parse("00000000000000000000000000000000");
Is not the same as this line:
let salt: [UInt8] = Array("0000000000000000".utf8)
The utf8 encoding of "0000000000000000" is, in hex, 30303030303030303030303030303030 (0x30 is the UTF-8 encoding of the character "0").
What you meant to use here is Array(repeating: UInt8(0), count: 16).
You're also outputting a Base64 string in JavaScript, and a hex string in Swift, which are not the same things.
Unrelated side-note:
This implementation is working pretty hard to get little security. If your password is static, you could do much better by using a random key (i.e. 32 completely random bytes 0-255, not a string of characters). PKBDF2 isn't really buying you much here, excepting slowing down the system (not slowing down the attacker; just your app). Adding a random IV would significantly improve this system as well with little cost.

Encoding a String in NetSuite SuiteScript 2.0

I have to perform the following encoding on a string:
Calculate SHA1 hash value, with output in hexadecimal format
Apply a BASE64 encoding to the resulted hash
I'm trying to do this in the code below, 'str' being the input and 'digest' the final encoded string.
I've tried different ways without much success. The current code (below) throws an error:
WrappedException: Wrapped java.lang.IllegalArgumentException: contains illegal character for hexBinary: crypto.SecretKey
var str = nonce + timestamp + secret;
var secureString = HTTPS.createSecureString({
input: str
});
secureString = secureString.hash({
algorithm: CRYPTO.HashAlg.SHA1
});
var hexString = HTTPS.createSecretKey({
encoding: HTTPS.Encoding.HEX,
guid: secureString
});
var digest = ENCODE.convert({
string: hexString,
inputEncoding: ENCODE.Encoding.HEX,
outputEncoding: ENCODE.Encoding.BASE_64
});

SecKey (PCKS1) to Base64 (PCKS8) from p12

I have looked at other answers on StackOverflow and I didn't find what I was looking for (IOS11). I have a SecKey (privateKey) that when I print:
SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, block size: 2048 bits, addr: 0x1d0223f60
I have tried to convert it to Data and from there to Base64
let password = "1234"
let p12data = NSData(contentsOfFile: urls[0].path)!
var importResult: CFArray? = nil
let err = SecPKCS12Import(p12data as NSData,[kSecImportExportPassphrase as String: password] as NSDictionary,&importResult )
//GET IDENTITY
let identityDictionaries = importResult as! [[String:Any]]
var privateKey: SecKey?
//GET SECKEY
SecIdentityCopyPrivateKey(identityDictionaries[0][kSecImportItemIdentity as String] as! SecIdentity, &privateKey);
print(privateKey)
//Return data in PCKS1
let dataPrivate = SecKeyCopyExternalRepresentation(privateKey!, nil)
let b64Key:Data = dataPrivate as! Data
print(b64Key.base64EncodedString(options: .lineLength64Characters))
Apple documentation says that SecKeyCopyExternalRepresentation return PCKS1 data (https://developer.apple.com/documentation/security/1643698-seckeycopyexternalrepresentation) but I need PCKS8.
The result is a base64 from PCKS1 but I have to send it to a JAVA server to be processed and expected format is base64 from PCKS8.
is there a way to convert from PCKS1 to PCKS8 and then to base64?
I have found this article: https://blog.wingsofhermes.org/?p=42 that more or less is what I want but its in objective-c and I have not been able to convert it to swift

AES calculation CMAC Java to Swift

I am trying to calculate CMAC
byte[] key={0x09,0x11,0x12,0x34,0x56,0x78,0x00,0x01,0x01,0x13,0x14,0x36,0x58,0x7A,0x02,0x03};
AES mAES=new AES();
mAES.AesInit(key);
byte[] response = mAES.calcCMAC(challenge);
Swift i am using the lib CryptoSwift
let key = [0x09,0x11,0x12,0x34,0x56,0x78,0x00,0x01,0x01,0x13,0x14,0x36,0x58,0x7A,0x02,0x03] as [UInt8]
let message:NSData = NSData.fromHexString("DA55C255")
let mac = Authenticator.Poly1305(key: key).authenticate(message.arrayOfBytes())
But it's not working as expected.
the expected result is
Challenge isDA55C255
Response isED7CA01A
we don't find any solution, we have created our own classe
https://gist.github.com/bolom/b426a0163943b576175b