Skip to content

Commit

Permalink
subtle.deriveBits() and fixes to importKey()
Browse files Browse the repository at this point in the history
  • Loading branch information
boorad committed Dec 14, 2023
1 parent ab060f3 commit 771fdc9
Show file tree
Hide file tree
Showing 10 changed files with 284 additions and 249 deletions.
145 changes: 37 additions & 108 deletions cpp/MGLKeys.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ std::optional<StringOrBuffer> WritePrivateKey(
}
}

bool err;
bool err = false;

PKEncodingType encoding_type = config.type_.value();
if (encoding_type == kKeyEncodingPKCS1) {
Expand Down Expand Up @@ -813,20 +813,20 @@ ManagedEVPPKey ManagedEVPPKey::GetParsedKey(jsi::Runtime& runtime,

return ManagedEVPPKey(std::move(pkey));
}
//
// KeyObjectData::KeyObjectData(
// ByteSource symmetric_key)
//: key_type_(KeyType::kKeyTypeSecret),
// symmetric_key_(std::move(symmetric_key)),
// symmetric_key_len_(symmetric_key_.size()),
// asymmetric_key_() {}
//

KeyObjectData::KeyObjectData(
ByteSource symmetric_key)
: key_type_(KeyType::kKeyTypeSecret),
symmetric_key_(std::move(symmetric_key)),
symmetric_key_len_(symmetric_key_.size()),
asymmetric_key_() {}

KeyObjectData::KeyObjectData(KeyType type,
const ManagedEVPPKey& pkey)
: key_type_(type),
// symmetric_key_(),
// symmetric_key_len_(0),
asymmetric_key_{pkey} {}
symmetric_key_(),
symmetric_key_len_(0),
asymmetric_key_{pkey} {}

std::shared_ptr<KeyObjectData> KeyObjectData::CreateSecret(ByteSource key)
{
Expand All @@ -847,20 +847,20 @@ KeyType KeyObjectData::GetKeyType() const {
}

ManagedEVPPKey KeyObjectData::GetAsymmetricKey() const {
// CHECK_NE(key_type_, kKeyTypeSecret);
CHECK_NE(key_type_, kKeyTypeSecret);
return asymmetric_key_;
}

// const char* KeyObjectData::GetSymmetricKey() const {
// CHECK_EQ(key_type_, kKeyTypeSecret);
// return symmetric_key_.data<char>();
// }
//
// size_t KeyObjectData::GetSymmetricKeySize() const {
// CHECK_EQ(key_type_, kKeyTypeSecret);
// return symmetric_key_len_;
// }
//
const char* KeyObjectData::GetSymmetricKey() const {
CHECK_EQ(key_type_, kKeyTypeSecret);
return symmetric_key_.data<char>();
}

size_t KeyObjectData::GetSymmetricKeySize() const {
CHECK_EQ(key_type_, kKeyTypeSecret);
return symmetric_key_len_;
}

// v8::Local<v8::Function> KeyObjectHandle::Initialize(Environment* env) {
// Local<Function> templ = env->crypto_key_object_handle_constructor();
// if (!templ.IsEmpty()) {
Expand Down Expand Up @@ -937,49 +937,6 @@ ManagedEVPPKey KeyObjectData::GetAsymmetricKey() const {
// MakeWeak();
//}
//
// void KeyObjectHandle::Init(const FunctionCallbackInfo<Value>& args) {
// KeyObjectHandle* key;
// ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
// MarkPopErrorOnReturn mark_pop_error_on_return;
//
// CHECK(args[0]->IsInt32());
// KeyType type = static_cast<KeyType>(args[0].As<Uint32>()->Value());
//
// unsigned int offset;
// ManagedEVPPKey pkey;
//
// switch (type) {
// case kKeyTypeSecret: {
// CHECK_EQ(args.Length(), 2);
// ArrayBufferOrViewContents<char> buf(args[1]);
// key->data_ = KeyObjectData::CreateSecret(buf.ToCopy());
// break;
// }
// case kKeyTypePublic: {
// CHECK_EQ(args.Length(), 5);
//
// offset = 1;
// pkey = ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(args, &offset);
// if (!pkey)
// return;
// key->data_ = KeyObjectData::CreateAsymmetric(type, pkey);
// break;
// }
// case kKeyTypePrivate: {
// CHECK_EQ(args.Length(), 5);
//
// offset = 1;
// pkey = ManagedEVPPKey::GetPrivateKeyFromJs(args, &offset, false);
// if (!pkey)
// return;
// key->data_ = KeyObjectData::CreateAsymmetric(type, pkey);
// break;
// }
// default:
// UNREACHABLE();
// }
//}
//
// void KeyObjectHandle::InitJWK(const FunctionCallbackInfo<Value>& args) {
// Environment* env = Environment::GetCurrent(args);
// KeyObjectHandle* key;
Expand Down Expand Up @@ -1072,7 +1029,6 @@ jsi::Value KeyObjectHandle::get(
case kKeyTypeSecret: {
// CHECK_EQ(args.Length(), 2);
// ArrayBufferOrViewContents<char> buf(args[1]);
// jsi::ArrayBuffer buf = args[1].asObject(rt).getArrayBuffer(rt);

ByteSource key = ByteSource::FromStringOrBuffer(rt, args[1]);
this->data_ = KeyObjectData::CreateSecret(std::move(key));
Expand All @@ -1084,7 +1040,7 @@ jsi::Value KeyObjectHandle::get(
offset = 1;
pkey = ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(rt, args, &offset);
if (!pkey)
return;
return false;
this->data_ = KeyObjectData::CreateAsymmetric(type, pkey);
break;
}
Expand All @@ -1094,7 +1050,7 @@ jsi::Value KeyObjectHandle::get(
offset = 1;
pkey = ManagedEVPPKey::GetPrivateKeyFromJs(rt, args, &offset, false);
if (!pkey)
return;
return false;
this->data_ = KeyObjectData::CreateAsymmetric(type, pkey);
break;
}
Expand All @@ -1105,49 +1061,18 @@ jsi::Value KeyObjectHandle::get(
return true;
});
}
else if (name == "export") {
return HOSTFN("export", 2) {
KeyType type = this->data_->GetKeyType();
if (type == kKeyTypeSecret) {

}
});
}

return {};
}

//
// void KeyObjectHandle::InitECRaw(const FunctionCallbackInfo<Value>& args) {
// Environment* env = Environment::GetCurrent(args);
// KeyObjectHandle* key;
// ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
//
// CHECK(args[0]->IsString());
// Utf8Value name(env->isolate(), args[0]);
//
// MarkPopErrorOnReturn mark_pop_error_on_return;
//
// int id = OBJ_txt2nid(*name);
// ECKeyPointer eckey(EC_KEY_new_by_curve_name(id));
// if (!eckey)
// return args.GetReturnValue().Set(false);
//
// const EC_GROUP* group = EC_KEY_get0_group(eckey.get());
// ECPointPointer pub(ECDH::BufferToPoint(env, group, args[1]));
//
// if (!pub ||
// !eckey ||
// !EC_KEY_set_public_key(eckey.get(), pub.get())) {
// return args.GetReturnValue().Set(false);
// }
//
// EVPKeyPointer pkey(EVP_PKEY_new());
// if (!EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()))
// args.GetReturnValue().Set(false);
//
// eckey.release(); // Release ownership of the key
//
// key->data_ =
// KeyObjectData::CreateAsymmetric(
// kKeyTypePublic,
// ManagedEVPPKey(std::move(pkey)));
//
// args.GetReturnValue().Set(true);
//}
//
// void KeyObjectHandle::InitEDRaw(const FunctionCallbackInfo<Value>& args) {
// Environment* env = Environment::GetCurrent(args);
// KeyObjectHandle* key;
Expand Down Expand Up @@ -1310,6 +1235,8 @@ jsi::Value KeyObjectHandle::get(
// args.GetReturnValue().Set(
// static_cast<uint32_t>(key->Data()->GetSymmetricKeySize()));
//}
//

//
// void KeyObjectHandle::Export(const FunctionCallbackInfo<Value>& args) {
// KeyObjectHandle* key;
Expand Down Expand Up @@ -1344,6 +1271,8 @@ jsi::Value KeyObjectHandle::get(
// if (!result.IsEmpty())
// args.GetReturnValue().Set(result.FromMaybe(Local<Value>()));
//}
//

//
// MaybeLocal<Value> KeyObjectHandle::ExportSecretKey() const {
// const char* buf = data_->GetSymmetricKey();
Expand Down
5 changes: 3 additions & 2 deletions cpp/MGLKeys.h
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,8 @@ class KeyObjectData {
// These functions allow unprotected access to the raw key material and should
// only be used to implement cryptographic operations requiring the key.
ManagedEVPPKey GetAsymmetricKey() const;
// const char* GetSymmetricKey() const;
// size_t GetSymmetricKeySize() const;
const char* GetSymmetricKey() const;
size_t GetSymmetricKeySize() const;

private:
explicit KeyObjectData(ByteSource symmetric_key);
Expand All @@ -148,6 +148,7 @@ class KeyObjectData {

const KeyType key_type_;
const ByteSource symmetric_key_;
const size_t symmetric_key_len_;
const ManagedEVPPKey asymmetric_key_;
};

Expand Down
2 changes: 1 addition & 1 deletion example/ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -661,4 +661,4 @@ SPEC CHECKSUMS:

PODFILE CHECKSUM: 50dd8e47b3ecade8a64d05a35069875c72371690

COCOAPODS: 1.13.0
COCOAPODS: 1.14.2
36 changes: 15 additions & 21 deletions example/src/testing/Tests/webcryptoTests/webcryptoTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,34 +81,28 @@ export function webcryptoRegisterTests() {
});

it('PBKDF2 importKey raw/deriveBits', async () => {
const password = 'password';
// const salt = 'salt';
// const iterations = 1;
// const length = 64;
// const algo = 'SHA-512';

const key = await crypto.subtle.importKey(
'raw',
base64ToArrayBuffer(password),
'password',
{ name: 'PBKDF2' },
false,
['deriveBits']
);
console.warn(key);
// const bits = await crypto.subtle.deriveBits({
// name: 'PBKDF2',
// salt: salt,
// iterations: iterations,
// hash: {
// name: algo,
// },
// },
// key,
// // eslint-disable-next-line no-bitwise
// length << 3
// );
const bits = await crypto.subtle.deriveBits(
{
name: 'PBKDF2',
salt: 'salt',
iterations: 1,
hash: {
name: 'SHA-512',
},
},
key,
// eslint-disable-next-line no-bitwise
64 << 3
);

// console.warn(bits);
console.warn(bits);
// chai
// .expect(bits)
// .to.equal(
Expand Down
17 changes: 15 additions & 2 deletions src/NativeQuickCrypto/webcrypto.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
import type { KeyType, KWebCryptoKeyFormat } from '../keys';
import type {
AsymmetricKeyType,
KeyEncoding,
KeyType,
KFormatType,
KWebCryptoKeyFormat,
} from '../keys';

type ECExportKey = (
format: KWebCryptoKeyFormat,
handle: KeyObjectHandle
) => ArrayBuffer;

export type KeyObjectHandle = {
export(
format?: KFormatType,
type?: KeyEncoding,
cipher?: string,
passphrase?: string
): ArrayBuffer;
getAsymmetricKeyType(): AsymmetricKeyType;
initECRaw(curveName: string, keyData: ArrayBuffer): boolean;
init(keyType: KeyType, key: ArrayBuffer): boolean;
init(keyType: KeyType, key: any): boolean;
};

type CreateKeyObjectHandle = () => KeyObjectHandle;
Expand Down
16 changes: 16 additions & 0 deletions src/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ export type Encoding =
// TODO(osp) should buffer be part of the Encoding type?
export type CipherEncoding = Encoding | 'buffer';

type DOMName =
| string
| {
name: string;
cause: any;
};

// Mimics node behavior for default global encoding
let defaultEncoding: CipherEncoding = 'buffer';

Expand Down Expand Up @@ -261,3 +268,12 @@ export function hasAnyNotIn(set: string[], checks: string[]) {
}
return false;
}

export function lazyDOMException(message: string, domName: DOMName): Error {
let cause = '';
if (typeof domName !== 'string') {
cause = `\nCaused by: ${domName.cause}`;
}

return new Error(`[${domName}]: ${message}${cause}`);
}
14 changes: 11 additions & 3 deletions src/ec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { NativeQuickCrypto } from './NativeQuickCrypto/NativeQuickCrypto';
import { bufferLikeToArrayBuffer, type BufferLike } from './Utils';
import {
bufferLikeToArrayBuffer,
type BufferLike,
type BinaryLike,
binaryLikeToArrayBuffer,
} from './Utils';
import {
type ImportFormat,
type SubtleAlgorithm,
Expand Down Expand Up @@ -167,7 +172,7 @@ export function ecExportKey(

export function ecImportKey(
format: ImportFormat,
keyData: BufferLike,
keyData: BufferLike | BinaryLike,
algorithm: SubtleAlgorithm,
extractable: boolean,
keyUsages: KeyUsage[]
Expand Down Expand Up @@ -270,7 +275,10 @@ export function ecImportKey(
// }
case 'raw': {
// verifyAcceptableEcKeyUse(name, true, usagesSet);
let buffer = bufferLikeToArrayBuffer(keyData);
let buffer =
typeof keyData === 'string'
? binaryLikeToArrayBuffer(keyData)
: bufferLikeToArrayBuffer(keyData);
keyObject = createECPublicKeyRaw(namedCurve, buffer);
break;
}
Expand Down
Loading

0 comments on commit 771fdc9

Please sign in to comment.