本文整理匯總了TypeScript中node-opcua-crypto.toPem函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript toPem函數的具體用法?TypeScript toPem怎麽用?TypeScript toPem使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了toPem函數的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: _verify_serverCertificate
/**
* check if certificate is trusted or untrusted
*/
function _verify_serverCertificate(serverCertificate: Certificate, callback: ErrorCallback) {
// todo:
// - use Certificate manager to deal with trusted/ untrusted certificate
// - add certificate verification and validity check
const pkiFolder = process.cwd() + "/pki";
// istanbul ignore next
if (!fs.existsSync(pkiFolder)) {
fs.mkdirSync(pkiFolder);
}
const pkiRejectedCertificateFolder = path.join(pkiFolder, "rejected");
// istanbul ignore next
if (!fs.existsSync(pkiRejectedCertificateFolder)) {
fs.mkdirSync(pkiRejectedCertificateFolder);
}
const thumbprint = makeSHA1Thumbprint(serverCertificate);
const certificateFilename = path.join(pkiRejectedCertificateFolder, thumbprint.toString("hex") + ".pem");
fs.writeFile(certificateFilename, toPem(serverCertificate, "CERTIFICATE"), () => {
setImmediate(callback);
});
}
示例2: RSAPKCS1OAEPSHA256_Verify
function RSAPKCS1OAEPSHA256_Verify(buffer: Buffer, signature: Signature, certificate: Certificate): boolean {
const options = {
algorithm: "RSA-SHA256",
publicKey: toPem(certificate, "CERTIFICATE"),
signatureLength: 0
};
return verifyMessageChunkSignature(buffer, signature, options);
}
示例3: it
it("SCT-4 should be possible to change the certificate and PrivateKey of the server", async () => {
// Given a server with push management
const server = await constructServerWithPushCertificate();
// Given that we known the server key pair before it is changed
const privateKey1PEM = await promisify(fs.readFile)(server.serverCertificateManager.privateKey, "utf8");
const certificateBefore = server.getCertificate();
const privateKeyBefore = server.getPrivateKey();
// Given that the server is started
await server.start();
// Given the server connection endpoint
const endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl!;
// Given that the sever has some client connected to it
await startOnGoingConnection(endpointUrl);
try {
// when an administrative client replaces the certificate & PrivateKey
const { certificate, privateKey } = await replaceServerCertificateAndPrivateKeyUsingPushCertificateManagerMethod(endpointUrl);
// then I should verify that the server certificate has changed
const certificateAfter = server.getCertificate();
certificateBefore.toString("base64").should.not.eql(certificateAfter.toString("base64"));
// and I should verify that the new server certificate matches the new certificate provided by the admin client
certificateAfter.toString("base64").should.eql(certificate.toString("base64"));
// then I should verify that the server private key has changed
const privateKeyAfter: PrivateKeyPEM = server.getPrivateKey();
privateKeyBefore.should.not.eql(privateKeyAfter);
// and I should verify that the new server private key matches the new private key provided by the admin client
privateKeyAfter.should.eql(toPem(privateKey, "RSA PRIVATE KEY"));
await new Promise((resolve) => setTimeout(resolve, 3000));
await testWithSimpleClient(endpointUrl);
onGoingClient.isReconnecting.should.eql(false, "client shall not be reconnected");
} catch (err) {
errorLog("---------------------------------------------- ERROR ! in Test ");
errorLog(err);
throw err;
} finally {
await stopOnGoingConnection();
// now stop the server
await server.shutdown();
}
});
示例4: RSAPKCS1V15SHA1_Verify
function RSAPKCS1V15SHA1_Verify(buffer: Buffer, signature: Signature, certificate: Certificate): boolean {
assert(certificate instanceof Buffer);
assert(signature instanceof Buffer);
const options = {
algorithm: "RSA-SHA1",
publicKey: toPem(certificate, "CERTIFICATE"),
signatureLength: 0,
};
return verifyMessageChunkSignature(buffer, signature, options);
}
示例5: simulateCertificateAndPrivateKeyChange
async function simulateCertificateAndPrivateKeyChange(server: OPCUAServer) {
const _server = server as any as OPCUAServerPartial;
// create a new key pair
const { certificate, privateKey } = await produceCertificateAndPrivateKey();
_server.$$privateKeyPEM = toPem(privateKey, "RSA PRIVATE KEY");
_server.$$certificateChain = certificate;
_server.$$certificate = undefined;
await server.suspendEndPoints();
await server.shutdownChannels();
await server.resumeEndPoints();
}
示例6: _getApplicationUri
/**
*
* @private
*/
private _getApplicationUri() {
const certificate = this.getCertificate();
let applicationUri: string;
if (certificate) {
const e = exploreCertificate(certificate);
if (e.tbsCertificate.extensions !== null) {
applicationUri = e.tbsCertificate.extensions.subjectAltName.uniformResourceIdentifier[0];
} else {
errorLog("Certificate has no extension");
errorLog(toPem(certificate, "CERTIFICATE"));
applicationUri = makeApplicationUrn(getFullyQualifiedDomainName(), this.applicationName);
}
} else {
errorLog("client has no certificate");
applicationUri = makeApplicationUrn(getFullyQualifiedDomainName(), this.applicationName);
}
return resolveFullyQualifiedDomainName(applicationUri);
}
示例7: _produceCertificate
async function _produceCertificate(
certificateSigningRequest: Buffer,
startDate: Date,
validity: number
): Promise<Buffer> {
// Given a Certificate Authority
const certificateAuthority = new CertificateAuthority({
keySize: 2048,
location: path.join(_tempFolder, "CA")
});
await certificateAuthority.initialize();
// --- now write the certificate signing request to the disc
const csrFilename = "signing_request.csr";
const csrFile = path.join(certificateAuthority.rootDir, csrFilename);
await promisify(fs.writeFile)(csrFile,
toPem(certificateSigningRequest,
"CERTIFICATE REQUEST"), "utf8");
// --- generate the certificate
const certificate = path.join(certificateAuthority.rootDir, "newCertificate.pem");
if (fs.existsSync(certificate)) {
// delete existing file
await promisify(fs.unlink)(certificate);
}
await certificateAuthority.signCertificateRequest(
certificate,
csrFile, {
applicationUri: "urn:MACHINE:MyApplication",
dns: [os.hostname()],
startDate,
validity
});
const certificatePEM = await promisify(fs.readFile)(certificate, "utf8");
return convertPEMtoDER(certificatePEM);
}
示例8: main
async function main() {
const optionsInitial = {
endpoint_must_exist: false,
keepSessionAlive: true,
connectionStrategy: {
initialDelay: 2000,
maxDelay: 10 * 1000,
maxRetry: 10
}
};
client = OPCUAClient.create(optionsInitial);
client.on("backoff", (retry: number, delay: number) => {
console.log(chalk.bgWhite.yellow("backoff attempt #"), retry, " retrying in ", delay / 1000.0, " seconds");
});
console.log(" connecting to ", chalk.cyan.bold(endpointUrl));
console.log(" strategy", client.connectionStrategy);
await client.connect(endpointUrl);
const endpoints = await client.getEndpoints();
if (argv.debug) {
fs.writeFileSync("tmp/endpoints.log", JSON.stringify(endpoints, null, " "));
console.log(treeify.asTree(endpoints, true));
}
const table = new Table();
let serverCertificate: Certificate;
let i = 0;
for (const endpoint of endpoints) {
table.cell("endpoint", endpoint.endpointUrl + "");
table.cell("Application URI", endpoint.server.applicationUri);
table.cell("Product URI", endpoint.server.productUri);
table.cell("Application Name", endpoint.server.applicationName.text);
table.cell("Security Mode", endpoint.securityMode.toString());
table.cell("securityPolicyUri", endpoint.securityPolicyUri);
table.cell("Type", ApplicationType[endpoint.server.applicationType]);
table.cell("certificate", "..." /*endpoint.serverCertificate*/);
endpoint.server.discoveryUrls = endpoint.server.discoveryUrls || [];
table.cell("discoveryUrls", endpoint.server.discoveryUrls.join(" - "));
serverCertificate = endpoint.serverCertificate;
const certificate_filename = path.join(__dirname, "../certificates/PKI/server_certificate" + i + ".pem");
if (serverCertificate) {
fs.writeFile(certificate_filename, toPem(serverCertificate, "CERTIFICATE"), () => {/**/
});
}
table.newRow();
i++;
}
console.log(table.toString());
for (const endpoint of endpoints) {
console.log("Identify Token for : Security Mode=", endpoint.securityMode.toString(), " Policy=", endpoint.securityPolicyUri);
const table2 = new Table();
for (const token of endpoint.userIdentityTokens!) {
table2.cell("policyId", token.policyId);
table2.cell("tokenType", token.tokenType.toString());
table2.cell("issuedTokenType", token.issuedTokenType);
table2.cell("issuerEndpointUrl", token.issuerEndpointUrl);
table2.cell("securityPolicyUri", token.securityPolicyUri);
table2.newRow();
}
console.log(table2.toString());
}
await client.disconnect();
// reconnect using the correct end point URL now
console.log(chalk.cyan("Server Certificate :"));
console.log(chalk.yellow(hexDump(serverCertificate!)));
const options = {
securityMode,
securityPolicy,
serverCertificate,
defaultSecureTokenLifetime: 40000,
endpoint_must_exist: false,
connectionStrategy: {
initialDelay: 2000,
maxDelay: 10 * 1000,
maxRetry: 10
}
};
console.log("Options = ", options.securityMode.toString(), options.securityPolicy.toString());
client = OPCUAClient.create(options);
console.log(" reconnecting to ", chalk.cyan.bold(endpointUrl));
//.........這裏部分代碼省略.........
示例9: createUserNameIdentityToken
function createUserNameIdentityToken(
session: ClientSessionImpl,
userName: string | null,
password: string | null
): UserNameIdentityToken {
// assert(endpoint instanceof EndpointDescription);
assert(userName === null || typeof userName === "string");
assert(password === null || typeof password === "string");
const endpoint = session.endpoint;
assert(endpoint instanceof EndpointDescription);
/**
* OPC Unified Architecture 1.0.4: Part 4 155
* Each UserIdentityToken allowed by an Endpoint shall have a UserTokenPolicy specified in the
* EndpointDescription. The UserTokenPolicy specifies what SecurityPolicy to use when encrypting
* or signing. If this SecurityPolicy is omitted then the Client uses the SecurityPolicy in the
* EndpointDescription. If the matching SecurityPolicy is set to None then no encryption or signature
* is required.
*
*/
const userTokenPolicy = findUserTokenPolicy(endpoint, UserTokenType.UserName);
// istanbul ignore next
if (!userTokenPolicy) {
throw new Error("Cannot find USERNAME user token policy in end point description");
}
let securityPolicy = fromURI(userTokenPolicy.securityPolicyUri);
// if the security policy is not specified we use the session security policy
if (securityPolicy === SecurityPolicy.Invalid) {
securityPolicy = session._client._secureChannel.securityPolicy;
}
let identityToken;
let serverCertificate: Buffer | string | null = session.serverCertificate;
// if server does not provide certificate use unencrypted password
if (!serverCertificate) {
identityToken = new UserNameIdentityToken({
encryptionAlgorithm: null,
password: Buffer.from(password as string, "utf-8"),
policyId: userTokenPolicy ? userTokenPolicy!.policyId : null,
userName
});
return identityToken;
}
assert(serverCertificate instanceof Buffer);
serverCertificate = toPem(serverCertificate, "CERTIFICATE");
const publicKey = extractPublicKeyFromCertificateSync(serverCertificate);
const serverNonce: Nonce = session.serverNonce || Buffer.alloc(0);
assert(serverNonce instanceof Buffer);
// If None is specified for the UserTokenPolicy and SecurityPolicy is None
// then the password only contains the UTF-8 encoded password.
// note: this means that password is sent in clear text to the server
// note: OPCUA specification discourages use of unencrypted password
// but some old OPCUA server may only provide this policy and we
// still have to support in the client?
if (securityPolicy === SecurityPolicy.None) {
identityToken = new UserNameIdentityToken({
encryptionAlgorithm: null,
password: Buffer.from(password!, "utf-8"),
policyId: userTokenPolicy.policyId,
userName
});
return identityToken;
}
// see Release 1.02 155 OPC Unified Architecture, Part 4
const cryptoFactory = getCryptoFactory(securityPolicy);
// istanbul ignore next
if (!cryptoFactory) {
throw new Error(" Unsupported security Policy");
}
identityToken = new UserNameIdentityToken({
encryptionAlgorithm: cryptoFactory.asymmetricEncryptionAlgorithm,
password: Buffer.from(password as string, "utf-8"),
policyId: userTokenPolicy.policyId,
userName
});
// now encrypt password as requested
const lenBuf = createFastUninitializedBuffer(4);
lenBuf.writeUInt32LE(identityToken.password.length + serverNonce.length, 0);
const block = Buffer.concat([lenBuf, identityToken.password, serverNonce]);
identityToken.password = cryptoFactory.asymmetricEncrypt(block, publicKey);
return identityToken;
}