当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript node-opcua-crypto.readCertificate函数代码示例

本文整理汇总了TypeScript中node-opcua-crypto.readCertificate函数的典型用法代码示例。如果您正苦于以下问题:TypeScript readCertificate函数的具体用法?TypeScript readCertificate怎么用?TypeScript readCertificate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了readCertificate函数的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: beforeEach

    beforeEach(async () => {

        const pkiFolder = path.join(temporaryFolder1, "pki");
        if (!fs.existsSync(pkiFolder)) {
            await rimraf.sync(pkiFolder);
        }
        if (fs.existsSync(temporaryFolder1)) {
            await rimraf.sync(temporaryFolder1);
            await fs.mkdirSync(temporaryFolder1);
        }
        if (fs.existsSync(temporaryFolder2)) {
            await rimraf.sync(temporaryFolder2);
            await fs.mkdirSync(temporaryFolder2);
        }

        acceptingCertificateMgr = new OPCUACertificateManager({
            automaticallyAcceptUnknownCertificate: true,
            rootFolder: temporaryFolder1
        });

        rejectingCertificateMgr = new OPCUACertificateManager({
            automaticallyAcceptUnknownCertificate: false,
            rootFolder: temporaryFolder2
        });

        certificate = await readCertificate(certificate1File);

        certificateThumbprint = makeSHA1Thumbprint(certificate).toString("hex");

        await acceptingCertificateMgr.initialize();
        await rejectingCertificateMgr.initialize();

    });
开发者ID:node-opcua,项目名称:node-opcua,代码行数:33,代码来源:test_certificate_manager.ts

示例2: performTest1

    function performTest1(
      sizeC: number,
      sizeS: number,
      securityPolicy: SecurityPolicy,
      done: (err?: Error) => void
    ): void {
        function m(file: string): string {
            const fullpathname = path.join(__dirname,
              "../../../packages/node-opcua-end2end-test/certificates/" + file);
            if (!fs.existsSync(fullpathname)) {
                throw new Error("file must exist: " + fullpathname);
            }
            return fullpathname;
        }

        const serverCertificateFile = m(`server_cert_${sizeS}.pem`);
        const serverPrivateKeyFile = m(`server_key_${sizeS}.pem`);
        const serverCertificate = readCertificate(serverCertificateFile);
        const serverPrivateKey = readKeyPem(serverPrivateKeyFile);

        const clientCertificateFile = m(`client_cert_${sizeC}.pem`);
        const clientPrivateKeyFile = m(`client_key_${sizeC}.pem`);
        const clientCertificate = readCertificate(clientCertificateFile);
        const clientPrivateKey = readKeyPem(clientPrivateKeyFile);

        performTest({
            clientCertificate,
            clientPrivateKey,
            securityMode: MessageSecurityMode.Sign,
            securityPolicy,
            serverCertificate,
            serverPrivateKey
            //   shouldFailAtClientConnection: false,
        }, done);

    }
开发者ID:node-opcua,项目名称:node-opcua,代码行数:36,代码来源:test_security.ts

示例3: describe

describe("SessionContext - with  dedicated SessionContext and certificate ", () => {

    let addressSpace: AddressSpace;
    let namespace: Namespace;
    let sessionContext: SessionContext;

    const mockUserManager = {

        isValidUser: (userName: string, password: string) => {

            if (userName === "NodeOPCUA") {
                return true;
            }

            if (userName === "user1" && password === "password1") {
                return true;
            }
            if (userName === "user2" && password === "password2") {
                return true;
            }
            return false;
        },

        // see OPCUA 1.04 part 3 4.8.2 Well know role
        // Anonymous          The Role has very limited access for use when a Session has anonymous credentials.
        // AuthenticatedUser  The Role has limited access for use when a Session has valid non-anonymous credentials
        //                    but has not been explicitly granted access to a Role.
        // Observer           The Role is allowed to browse, read live data, read historical data/events or subscribe to
        //                    data/events.
        // Operator           The Role is allowed to browse, read live data, read historical data/events or subscribe to
        //                    data/events.
        //                    In addition, the Session is allowed to write some live data and call some Methods.
        // Engineer           The Role is allowed to browse, read/write configuration data, read historical data/events,
        //                    call Methods or subscribe to data/events.
        // Supervisor         The Role is allowed to browse, read live data, read historical data/events, call Methods
        //                    or subscribe to data/events.
        // ConfigureAdmin     The Role is allowed to change the non-security related configuration settings.
        // SecurityAdmin      The Role is allowed to change security related settings.

        getUserRole(username: string): string {
            if (username === "anonymous") {
                return "Anonymous";
            }
            if (username === "NodeOPCUA") {
                return "AuthenticatedUser;SecurityAdmin";
            }
            return "None";
        }
    };

    const mockServer = {
        userManager: mockUserManager
    };

    const certificateFilename = path.join(__dirname, "../../node-opcua-samples/certificates/client_cert_2048.pem");

    const certificate = readCertificate(certificateFilename);
    const mockSession = {
        userIdentityToken: new X509IdentityToken({
            certificateData: certificate
        })
    };

    before(async () => {

        sessionContext = new SessionContext({
            server: mockServer,
            session: mockSession
        });
        addressSpace = await getMiniAddressSpace();
        namespace = addressSpace.getOwnNamespace();
    });
    after(() => {
        addressSpace.dispose();
    });

    it("should provide a default session context - getCurrentUserRole", () => {
        const context = sessionContext;
        context.getCurrentUserRole().should.eql("AuthenticatedUser;SecurityAdmin");
    });

    it("should provide a  default session context - checkPermission", () => {
        const context = sessionContext;

        const someNode = addressSpace.getOwnNamespace().addVariable({
            browseName: "SomeNode",
            dataType: DataType.Double,
            nodeId: "i=12",
            userAccessLevel: "CurrentRead"
        });
        context.checkPermission(someNode, "CurrentRead").should.eql(true);
        context.checkPermission(someNode, "CurrentWrite").should.eql(false);

    });
});
开发者ID:node-opcua,项目名称:node-opcua,代码行数:95,代码来源:test_session_context.ts

示例4: performTest

    async function performTest(
      _messageCreateSessionResponsePacket: Buffer,
      _messageActivateSessionRequestPacket: Buffer,
      securityPolicy: SecurityPolicy
    ): Promise<void> {

        const createSessionResponse =
          await decodeMessage(_messageCreateSessionResponsePacket) as CreateSessionResponse;

        const activateSessionRequest =
          await decodeMessage(_messageActivateSessionRequestPacket) as ActivateSessionRequest;

        // Verify signature
        const serverNonce = createSessionResponse.serverNonce;
        const serverCertificate = createSessionResponse.serverCertificate;

        const userIdentityToken = activateSessionRequest.userIdentityToken as X509IdentityToken;

        // create a fake server userTokenPolicy
        const userTokenPolicy: any = {
            policyId: userIdentityToken.policyId
        };

        const userCertificate = readCertificate(path.join(__dirname, "./fixtures/user1_certificate.pem"));
        const privateKey = readPrivateKeyPEM(path.join(__dirname, "./fixtures/private_key.pem"));

        const signatureData = rebuildSignature(
          serverCertificate,
          serverNonce,
          privateKey,
          securityPolicy
        );

        if (doDebug) {

            console.log("policyId = ", userIdentityToken.policyId);
            console.log("serverNonce\n", createSessionResponse.serverNonce.toString("hex"));
            console.log("user certificate from file            \n", userCertificate.toString("hex"));
            console.log("user certificate from activate session\n", userIdentityToken.certificateData.toString("hex"));

            console.log("\nsignature recomputed by the test\n", signatureData.signature!.toString("hex"));
            console.log("", signatureData.algorithm);

            console.log("signature generated by the client \n", activateSessionRequest.userTokenSignature.signature.toString("hex"));
            console.log("", activateSessionRequest.userTokenSignature.algorithm);
        }
        userCertificate.toString("hex").should.eql(userIdentityToken.certificateData.toString("hex"));

        const statusCode = await verifyX509UserIdentity1(
          serverCertificate,
          serverNonce,
          securityPolicy,
          userTokenPolicy,
          userIdentityToken,
          activateSessionRequest.userTokenSignature);
        if (doDebug) {
            console.log("statusCode = ", statusCode.toString());
        }
        statusCode.should.eql(StatusCodes.Good);

    }
开发者ID:node-opcua,项目名称:node-opcua,代码行数:61,代码来源:test_x509_signature.ts

示例5: _load_certificate

function _load_certificate(certificateFilename: string): Certificate {
    const der =  readCertificate(certificateFilename);
    return der;
}
开发者ID:node-opcua,项目名称:node-opcua,代码行数:4,代码来源:opcua_secure_object.ts

示例6: describe

describe("Testing Session with user certificate", () => {

    before(startServer);
    after(endServer);

    const certificateFolder = path.join(__dirname, "../../../node-opcua-samples/certificates");

    const clientPrivateKeyFilename = path.join(certificateFolder, "client_key_2048.pem");
    const privateKey: PrivateKeyPEM = crypto_utils.readPrivateKeyPEM(clientPrivateKeyFilename);

    const wrongClientPrivateKeyFilename = path.join(certificateFolder, "server_key_2048.pem");
    const wrongPrivateKey: PrivateKeyPEM = crypto_utils.readPrivateKeyPEM(wrongClientPrivateKeyFilename);

    const clientCertificateFilename = path.join(certificateFolder, "client_cert_2048.pem");
    const clientCertificate: Certificate = crypto_utils.readCertificate(clientCertificateFilename);
    const invalidClientCertificateFilename = path.join(certificateFolder, "client_cert_2048_outofdate.pem");
    const invalidClientCertificate: Certificate = crypto_utils.readCertificate(invalidClientCertificateFilename);
    const notActiveClientCertificateFilename = path.join(certificateFolder, "client_cert_2048_not_active_yet.pem");
    const notActiveClientCertificate: Certificate = crypto_utils.readCertificate(notActiveClientCertificateFilename);

    let client: OPCUAClient|null = null;

    beforeEach(async () => {
        client = OPCUAClient.create({});
        await client.connect(endpointUrl);

        // make sure all certificates are "trusted"
        await server.userCertificateManager.trustCertificate(clientCertificate);
        await server.userCertificateManager.trustCertificate(invalidClientCertificate);
        await server.userCertificateManager.trustCertificate(notActiveClientCertificate);

    });

    afterEach(async () => {
        await server.userCertificateManager.trustCertificate(clientCertificate);
        await server.userCertificateManager.trustCertificate(invalidClientCertificate);
        await server.userCertificateManager.trustCertificate(notActiveClientCertificate);
        await client!.disconnect();
        client = null;
    });

    it("should create a session with a valid client certificates", async () => {

        const userIdentity: UserIdentityInfoX509 = {
            certificateData: clientCertificate,
            privateKey,
            type: UserTokenType.Certificate,
        };
        const session = await client!.createSession(userIdentity);
        await session.close();

    });

    it("should fail to create a session with a valid client certificate which is untrusted", async () => {

        await server.userCertificateManager.rejectCertificate(clientCertificate);

        const userIdentity: UserIdentityInfoX509 = {
            certificateData: clientCertificate,
            privateKey,
            type: UserTokenType.Certificate,
        };
        let exceptionCaught: Error|null = null;
        try {
            const session = await client!.createSession(userIdentity);
            await session.close();

        } catch (err) {
            exceptionCaught = err;
        }
        should(exceptionCaught).not.be.null();
    });


    it("should fail to create a session with a invalid client certificate (outofdate)", async () => {

        const userIdentity: UserIdentityInfoX509 = {
            certificateData: invalidClientCertificate,
            privateKey,
            type: UserTokenType.Certificate,
        };
        let exceptionCaught: Error|null = null;
        try {
            const session = await client!.createSession(userIdentity);
            await session.close();
        } catch (err) {
            exceptionCaught = err;
        }
        should(exceptionCaught).not.be.null();

    });

    it("should fail to create a session with a invalid client certificate (not_active_yet)", async () => {

        const userIdentity: UserIdentityInfoX509 = {
            certificateData: notActiveClientCertificate,
            privateKey,
            type: UserTokenType.Certificate,
        };
        let exceptionCaught: Error|null = null;
//.........这里部分代码省略.........
开发者ID:node-opcua,项目名称:node-opcua,代码行数:101,代码来源:test_e2e_session_with_X509IdentityToken.ts

示例7: require

    encryptBufferWithDerivedKeys,
    makeMessageChunkSignature,
    makeMessageChunkSignatureWithDerivedKeys,
    makeSHA1Thumbprint,
    publicEncrypt_long,
    readCertificate,
    readKeyPem,
    RSA_PKCS1_PADDING
} from "node-opcua-crypto";
import { AsymmetricAlgorithmSecurityHeader, SymmetricAlgorithmSecurityHeader } from "node-opcua-service-secure-channel";
import { SecureMessageChunkManager, SequenceNumberGenerator } from "../source";

// tslint:disable:no-var-requires
const getFixture = require("node-opcua-test-fixtures").getFixture;

const senderCertificate = readCertificate(getFixture("certs/client_cert_1024.pem"));
const senderPrivateKey = readKeyPem(getFixture("certs/client_key_1024.pem"));

const receiverCertificate =  readCertificate(getFixture("certs/server_cert_1024.pem"));
const receiverCertificateThumbprint = makeSHA1Thumbprint(receiverCertificate);

const receiverPublicKey = fs.readFileSync(getFixture("certs/server_public_key_1024.pub", "ascii")).toString();

const sequenceNumberGenerator = new SequenceNumberGenerator();

export type ChunkVisitorFunc = (err: Error | null, chunk?: Buffer) => void;

export function iterateOnSignedMessageChunks(buffer: Buffer, callback: ChunkVisitorFunc) {

    const params = {
        algorithm: "RSA-SHA1",
开发者ID:node-opcua,项目名称:node-opcua,代码行数:31,代码来源:fake_message_chunk_factory.ts


注:本文中的node-opcua-crypto.readCertificate函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。