CryptoSwift: unresolved identifier 'GCM' - swift4.1

xcode version: 9.3.1 (9E145)
Swift version: 4.1
I have just downloaded the latest master copy and installed CryptoSwift using CocoaPods. Using the example given on the README:
do {
// In combined mode, the authentication tag is directly appended to the encrypted message. This is usually what you want.
let gcm = GCM(iv: iv, mode: .combined)
let aes = try AES(key: key, blockMode: gcm, padding: .noPadding)
let encrypted = try aes.encrypt(plaintext)
let tag = gcm.authenticationTag
catch {
// failed
}
I get the error of "Use of unresolved identifier 'GCM'". I have tried other functions like aes.encrypt and aes.decrypt and they all work fine

GCM is a part of Crypto Swift so you should import Crypto swift that's what is missing i think so import it first in your controller
import CryptoSwift

Related

Bitbucket is not a constructor using bitbucketjs

Im using this library to manage bitbucket api from nodejs.
I have received a message about a deprecated endpoint so I saw that library have released a new version (2).
So, I have uninstall bitbucket dependency and installed again to version 2.7.0
But now, Im getting an error like this:
let bitbucketAPI = new Bitbucket()
^
TypeError: Bitbucket is not a constructor
This is the change in package.json
- "bitbucket": "^1.15.1",
+ "bitbucket": "^2.7.0",
And this is my code:
let Bitbucket = require('bitbucket')
let bitbucketAPI = new Bitbucket()
I have deleted package-lock.json, node_modules/bitbucket folder, update dependencies with npm update but anything works..
Any idea?
The proper way to load this module is this:
const { Bitbucket } = require('bitbucket');
This is shown in the doc.
So, when you were just doing this:
let Bitbucket = require('bitbucket');
You were getting the module exports object, not the individual Bitbucket property of that object. To further understand,
// get module exports object
const bitBucketModule = require('bitbucket');
// get Bitbucket property from the module exports object
const Bitbucket = bitBucketModule.Bitbucket;
And, the recommended method using object desctructuring:
const { Bitbucket } = require('bitbucket');
is just a shortcut way to do it with less code.
Linked docs destructure Bitbucket:
const { Bitbucket } = require('bitbucket')

PDFNet Digital Signature in Node JS using Google KMS

I've seen example of signing https://www.pdftron.com/documentation/nodejs/guides/features/signature/sign-pdf
signOnNextSave uses PKCS #12 certificate, but I use Google KMS for asymmetric signing to keep private keys safe.
Here is example of signing and verifying by Google Cloud KMS
I tried to implement custom SignatureHandler but Node.JS API is different from Java or .NET
https://www.pdftron.com/api/pdfnet-node/PDFNet.SignatureHandler.html
How can I implement custom signing and verifying logic?
const data = Buffer.from('pdf data')
// We have 2048 Bit RSA - PSS Padding - SHA256 Digest key in Google Cloud KMS
const signAsymmetric = async () => {
const hash = crypto.createHash('sha256')
hash.update(data)
const digest = hash.digest()
const digestCrc32c = crc32c.calculate(digest)
// Sign the data with Cloud KMS
const [signResponse] = await client.asymmetricSign({
name: locationName,
digest: {
sha256: digest
},
digestCrc32c: {
value: digestCrc32c
}
})
if (signResponse.name !== locationName) {
throw new Error('AsymmetricSign: request corrupted in-transit')
}
if (!signResponse.verifiedDigestCrc32c) {
throw new Error('AsymmetricSign: request corrupted in-transit')
}
if (
crc32c.calculate(signResponse.signature) !==
Number(signResponse.signatureCrc32c.value)
) {
throw new Error('AsymmetricSign: response corrupted in-transit')
}
// Returns signature which is buffer
const encoded = signResponse.signature.toString('base64')
console.log(`Signature: ${encoded}`)
return signResponse.signature
}
// Verify data with public key
const verifyAsymmetricSignatureRsa = async () => {
const signatureBuffer = await signAsymmetric()
const publicKeyPem = await getPublicKey()
const verify = crypto.createVerify('sha256')
verify.update(data)
verify.end()
const key = {
key: publicKeyPem,
padding: crypto.constants.RSA_PKCS1_PSS_PADDING
}
// Verify the signature using the public key
const verified = verify.verify(key, signatureBuffer)
return verified
}
At this time, the PDFTron SDK only supports custom handlers on C++, Java, and C# (there are more plans to include additional languages in the future).
On a different platform like C++, you would extend the custom handler functions by putting hash.update(data) into SignatureHandler::AppendData, and the rest of signAsymmetric would go into SignatureHandler::CreateSignature. A name would be given to the custom handler for interoperability like Adobe.PPKLite (we do not yet support custom handler SubFilter entries, only Filter -- see PDF standard for the difference -- but this won't matter so long as you use a verification tool that supports Filter Adobe.PPKLite). Please see the following link for a concrete example:
https://www.pdftron.com/documentation/samples/cpp/DigitalSignaturesTest
As for verification, our code can already do this for you if your signatures fulfill the following conditions:
they use a standard digest algorithm
they use RSA to sign
they use the correct data formats according to the PDF standard (i.e. detached CMS, digital signature dictionary)
If you have more questions or require more details, please feel free to reach out to PDFTron support at support#pdftron.com

How am i doing this wrong: SubtleCrypto (Node.js) encryption to RSACryptoServiceProvider (.net) decryption with OAEP

I've been trying to crack this for a while with no success.
The server-side decryption uses RSACryptoServiceProvider RSA-OAEP. I can't change this
public void SetEncryptedPassword(string password) {
using (RSACryptoServiceProvider decrypter = new RSACryptoServiceProvider()) {
decrypter.FromXmlString(Resources.PrivateKey);
var decryptedBytes = decrypter.Decrypt(Convert.FromBase64String(password), true);
_password = Encoding.UTF8.GetString(decryptedBytes).ToSecureString();
}
}
I am trying to implement a web client that can access this service but I can't get the encryption right. I have tried loads of libraries but found the most help with SubtleCrypto, which at least can accept the public key provided by the server. I had to add the kty, alg and ext properties and encode the key as URL Base64, but it appears to import fine. Encryption does come back with something so I guess it's working?
const encrypt = async (msg)=>{
let msgBytes = stringToBytes(msg);
let publicKey2 = await window.crypto.subtle.importKey("jwk",publicKey, {name:"RSA-OAEP", hash:"SHA-256"}, true, ["encrypt"]).catch((issue)=>console.log(issue));
var result = await window.crypto.subtle.encrypt({name: "RSA-OAEP"}, publicKey2, msgBytes );
var toBase64 = _arrayBufferToBase64(result);
return toBase64;
}
I had a few issues getting a valid base64 string so now I'm using this
function _arrayBufferToBase64( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}
The result looks a little shorter than the outputs produced by the iPad and .net services, but I have no idea if that means anything.
The decryption always fails with the error "Error occurred while decoding OAEP padding.", which tells me that it fails at the first step.
Am I doing something wrong? Any advice would be helpful. I'll be watching comments and replies for most of the day so I can supply extra information if you ask for it.
Thanks in advance
CodeSandbox.io demo
The problem arises because in the C#-code SHA-1 is (implicitly) used for OAEP and in the JavaScript/Node.js-code SHA-256.
RSACryptoServiceProvider only supports PKCS#1 v1.5-padding and OAEP with SHA-1. The support of OAEP with SHA-2 is only
implemented for the newer RSA implementation, RSACng (available since .NET 4.6), which belongs to the new Cryptography API (Next Generation).
Since you can't change the C#-code according to your own statement, there is only the possibility to change the hash in the JavaScript/Node.js-code from SHA-256 to SHA-1.

Using xml-crypto with PSHA1

Is it possible to use XML Crypto using a PSHA1 (http://schemas.xmlsoap.org/ws/2005/02/trust/CK/PSHA1) key?
I have both secrets and generate a PSHA1 key string using them, however this fails with:
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
I'm not what format this key needs to be in to be accepted, it's not a PEM certificate, just a string based on 2 provided nonce's. One provided by the client during the request and one provided by the server in the response.
const sig = new SignedXml();
sig.addReference("/*[local-name()='Envelope']/*[local-name()='Header']/*[local-name()='Security']/*[local-name()='Timestamp']");
sig.signingKey = '<SIGNING_KEY>';
sig.computeSignature(xml);
fs.writeFileSync('signed.xml', sig.getSignedXml());
It fails on the signer.sign line here:
this.getSignature = function(signedInfo, signingKey) {
var signer = crypto.createSign("RSA-SHA1")
signer.update(signedInfo)
var res = signer.sign(signingKey, 'base64')
return res
}
The PSHA1 algorithm isn't implemented in the Crypto Library, but there's a PSHA1 npm package you can use to generate the secret key. After that you can generate a SHA1 hash using the message and key in the standard way.
I asked a very similar question here, which answers the question:
https://stackoverflow.com/a/55053741/5065447

UnhandledPromiseRejectionWarning: Error: The contract code couldn't be stored, please check your gas limit

I am trying to deploy my simple solidity smart contract onto the Rinkeby Network but I keep getting the error:
UnhandledPromiseRejectionWarning: Error: The contract code couldn't be
stored, please check your gas limit.
My solidity code is simple
pragma solidity ^0.4.18;
contract Greetings{
string public message;
function Greetings(string initialMessage) public{
message = initialMessage;
}
function setMessage(string newMessage) public {
message = newMessage;
}
}
and my deploy script is:
const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const { interface,bytecode} = require('./compile');
const provider = new HDWalletProvider(
'twelve word mnemonic...',
'https://rinkeby.infura.io/GLm6McXWuaih4gqq8nTY'
);
const web3 = new Web3(provider);
const deploy = async () => {
accounts = await web3.eth.getAccounts();
console.log('attempting to deploy from account',accounts[0]);
const result = await new web3.eth.Contract(JSON.parse(interface))
.deploy({data:bytecode, arguments:['Hello World']})
.send({from: accounts[0], gas:'1000000'});
console.log('Contract deployed to', result.options.address);
};
deploy();
Funny thing is, I used to be able to deploy successfully, but when i created a new project and re did the same code, i get this error now. Please help!
Had exactly same problem! Seems it is caused by the bug in the "truffle-hdwallet-provider" version 0.0.5. During the udemy course it was using "0.0.3" apparently.
If you do the following should be okay, it worked for me.
npm uninstall truffle-hdwallet-provider
npm install --save truffle-hdwallet-provider#0.0.3
Then I ran the same contract which has deployed successfully.
Good luck!
This issue can be solved by adding the '0x' as the prefix of the bytecode:
.deploy({ data: '0x' + bytecode, arguments: ['Hi there!'] })
More information is at https://ethereum.stackexchange.com/a/47654.
I believe bytecode is being treated as a single number rather than a series of bytes. Instead of submitting data:bytecode, try:
data:'0x0' + bytecode
it will "preserve" bytecode value as a string
Also just remove the gas field let metamask decide the gas limit. this way works for me.

Resources