The PSI protocol (Private Set Intersection) is used to determine whether a target element exists in the other party's dataset without revealing the elements or the content of the dataset. It applies to scenarios where two parties cannot exchange plaintext sets, such as contact matching and friend recommendation.
Performing private set intersection through the PSI protocol involves three steps: generating a privacy target genPrivacyTarget, performing a privacy search privacySearch, and obtaining the search result getSearchResult. The PSI protocol returns only whether there is a match, without any additional value. To retrieve the additional value of a matched item, use the PIR protocol.
Import the modules required by the APIs.
import { privacyComputation } from '@kit.DataProtectionKit'; The initiator generates the privacy target.
Construct TargetElement (the original data of the target element and the hash algorithm) and PrivacyProtocol (set the protocol type to PSI_PROTOCOL), and call genPrivacyTarget to generate the privacy target.
const targetElement: privacyComputation.TargetElement = {
elemData: new Uint8Array([0x01, 0x02, 0x03]),
hashAlg: privacyComputation.HashAlg.SHA256
};
const privacyProtocol: privacyComputation.PrivacyProtocol = {
dataSetSize: privacyComputation.DataSetSize.SIZE_512,
protocolType: privacyComputation.ProtocolType.PSI_PROTOCOL
};
const privacyTarget: Uint8Array = await privacyComputation.genPrivacyTarget(targetElement, privacyProtocol); The responder performs the privacy search.
Construct an array of Element (dataset elements, including keys and hash algorithms), and call privacySearch together with the privacy target and protocol configuration to perform the privacy search.
const elements: privacyComputation.Element[] = [
{ elemKey: new Uint8Array([0x01, 0x02, 0x03]), hashAlg: privacyComputation.HashAlg.SHA256 },
{ elemKey: new Uint8Array([0x07, 0x08, 0x09]), hashAlg: privacyComputation.HashAlg.SHA256 }
];
const searchResult: privacyComputation.PrivacySearchResult =
await privacyComputation.privacySearch(privacyTarget, elements, privacyProtocol); The initiator obtains the final result.
Pass the result returned by privacySearch to getSearchResult, and decrypt it to obtain SearchResult. matchedResult indicates whether the target element exists in the dataset.
const result: privacyComputation.SearchResult =
await privacyComputation.getSearchResult(searchResult, privacyProtocol);
console.info('matched: ' + result.matchedResult);