當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。