### Run Dart Examples Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/examples/README.md Demonstrates how to execute various Dart example programs from the command line after installing dependencies. It shows commands for AES CBC, digest, and RSA demos. ```sh dart aes-cbc-direct.dart dart digest-direct.dart "foobar" dart rsa-demo.dart ``` -------------------------------- ### Using RSASigner with Registry Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Example of initializing an RSASigner using the library's registry with a predefined algorithm name like 'SHA-256/RSA'. This simplifies the process by automatically handling the correct algorithm identifier. ```Dart final signer = Signer('SHA-256/RSA'); ``` -------------------------------- ### Create RSA Public Key PEM String in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/asn1.md This example demonstrates how to construct an ASN.1 structure for a RSA Public Key and encode it into a Base64 string, formatted as a PEM file. It involves creating sequences, object identifiers, and bit strings to represent the key components. ```dart import 'package:asn1lib/asn1lib.dart'; import 'package:characters/characters.dart'; import 'dart:convert'; import 'dart:typed_data'; final BEGIN_PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----'; final END_PUBLIC_KEY = '-----END PUBLIC KEY-----'; // Assume publicKey is an object with modulus and exponent properties // For demonstration, we'll use placeholder values or assume it's initialized elsewhere. // var publicKey; // This would typically be obtained from an RSA key generation process. // Create a new RSA pulic key (placeholder for demonstration) var publicKey = _createDummyPublicKey(); // Create the top level sequence var topLevelSeq = ASN1Sequence(); // Create the sequence holding the algorithm information var algorithmSeq = ASN1Sequence(); var paramsAsn1Obj = ASN1Object.fromBytes(Uint8List.fromList([0x5, 0x0])); // NULL algorithmSeq.add(ASN1ObjectIdentifier.fromComponentString('1.2.840.113549.1.1.1')); // rsaEncryption algorithmSeq.add(paramsAsn1Obj); // Create the constructed ASN1BitString var modulus = ASN1Integer(publicKey.modulus); var exponent = ASN1Integer(publicKey.exponent); var publicKeySeqBitString = ASN1BitString(elements : [modulus, exponent], tag: ASN1Tags.BIT_STRING_CONSTRUCTED); // Add ASN1 objects to the top level sequence topLevelSeq.add(algorithmSeq); topLevelSeq.add(publicKeySeqBitString); // Encode base64 var dataBase64 = base64.encode(topLevelSeq.encodedBytes); var chunks = dataBase64.characters.chunks(64).toList(); print('$BEGIN_PUBLIC_KEY\n${chunks.join('\n')}\n$END_PUBLIC_KEY'); // Dummy function to simulate a publicKey object Object _createDummyPublicKey() { return type('', '', BigInt.parse('165804177387087149617220457493747588873959131224426853644136343567339'), BigInt.parse('65537')); } // Dummy type to hold modulus and exponent Type type(String modulus, String exponent, BigInt mod, BigInt exp) { return _DummyPublicKey(mod, exp); } class _DummyPublicKey { BigInt modulus; BigInt exponent; _DummyPublicKey(this.modulus, this.exponent); } ``` -------------------------------- ### Instantiate HMAC without Registry in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/hmac.md Provides examples of instantiating HMac objects directly without using the registry. It requires specifying the digest implementation and the correct block length for the algorithm. ```dart final hmacSha256 = HMac(SHA256Digest(), 64); // for HMAC SHA-256, block length must be 64 final hmacSha1 = HMac(SHA1Digest(), 64); // for HMAC SHA-1, block length must be 64 final hmacSha512 = HMac(SHA512Digest(), 128); // for HMAC SHA-512, block length must be 128 final hmacMd2 = HMac(MD2Digest(), 16); // for HMAC MD2, block length must be 16 final hmacMd5 = HMac(MD5Digest(), 64); // for HMAC MD5, block length must be 64 ``` -------------------------------- ### Dart: Process Blocks Sequentially Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/aes-cbc.md Demonstrates the sequential processing of data blocks using the `processBlock` method. The example shows how to allocate destination space, iterate through blocks, and update an offset. It assumes the `processBlock` method returns the number of bytes processed. ```dart final destination = Uint8List(source.length); // allocate space var offset = 0; while (offset < paddedPlaintext.length) { offset += cbc.processBlock(source, offset, destination, offset); } assert(offset == source.length); ``` -------------------------------- ### Process Progressive Data for Digest in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/digest.md Illustrates how to compute a digest by providing data in chunks or individual bytes. It uses `updateByte` for single bytes and `update` for byte arrays, followed by `doFinal` to get the digest. ```dart final chunk1 = utf8.encode('cellophane'); final chunk2 = utf8.encode('world'); d.updateByte(0x48); // 'H' d.updateByte(0x65); // 'e' d.update(chunk1, 1, 4); d.updateByte(0x20); // ' ' d.update(chunk2, 0, chunk2.length); d.updateByte(0x21); // '!' final hash = Uint8List(d.digestSize); // create a destination for storing the hash d.doFinal(hash, 0); // hash of "Hello world!" ``` -------------------------------- ### Dart HMAC Reset Example Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/hmac.md This Dart code snippet illustrates the effect of the `reset` method on HMAC calculations. It shows how calling `reset` discards previously updated data, leading to a different final HMAC output. ```dart final part1 = utf8.encode('Hello '); final part2 = utf8.encode('world!'); final result = Uint8List(hmac.macSize); // Without reset hmac.update(part1, 0, part1.length); hmac.update(part2, 0, part2.length); hmac.doFinal(result, 0); // result contains HMAC of "Hello world!" // With reset hmac.update(part1, 0, part1.length); hmac.reset(); // *** reset discards the data from part1 hmac.update(part2, 0, part2.length); hmac.doFinal(result, 0); // result contains HMAC of "world!" ``` -------------------------------- ### Dart SHA256Digest: Resetting for Progressive Hashing Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/digest.md This Dart code snippet illustrates the behavior of SHA256Digest when data is processed progressively. It shows how calling the `reset` method discards previously updated data, leading to a different final hash compared to sequential updates without a reset. This is useful when processing data in chunks and needing to start a new hash calculation from a specific point. ```dart final part1 = utf8.encode('Hello '); final part2 = utf8.encode('world!'); final d = SHA256Digest(); final hash = Uint8List(d.digestSize); // Without reset d.update(part1, 0, part1.length); d.update(part2, 0, part2.length); d.doFinal(hash, 0); // hash of "Hello world!" // With reset d.update(part1, 0, part1.length); d.reset(); d.update(part2, 0, part2.length); d.doFinal(hash, 0); // hash of "world!" ``` -------------------------------- ### Initialize Algorithm with Parameters in Dart Source: https://github.com/bcgit/pc-dart/blob/master/README.md Demonstrates the general process of instantiating and initializing an algorithm in PointyCastle using its parameters. This involves obtaining an algorithm instance, creating the appropriate parameter object, and then calling the init method. ```Dart var algorithmVar = /* instantiate algorithm using registry here */ ; var parameter = /* instantiate relevant parameter class here */ ; algorithmVar.init(parameter); ``` -------------------------------- ### Import export.dart for Full Access (Dart) Source: https://github.com/bcgit/pc-dart/blob/master/README.md Demonstrates importing the 'export.dart' file, which includes the high-level API, interface implementations, and all algorithm implementation classes. This import allows for both registry usage and direct instantiation of any algorithm class. ```dart import "package:pointycastle/export.dart"; final sha256 = Digest("SHA-256"); final md5 = MD5Digest(); final p = Padding("PKCS7"); final s = FortunaRandom(); ``` -------------------------------- ### Instantiate Algorithms Directly (Dart) Source: https://github.com/bcgit/pc-dart/blob/master/README.md Shows how to instantiate cryptographic algorithms by directly calling their constructors without using the registry. This approach requires explicit instantiation of each component class and is useful when avoiding the potential increase in compiled size from importing all algorithms via the registry. ```dart final sha256 = SHA256Digest(); final sha1 = SHA1Digest(); final md5 = MD5Digest(); final hmacSha256 = HMac(SHA256Digest(), 64); final hmacSha512 = HMac(SHA512Digest(), 128); final hmacMd5 = HMac(MD5Digest(), 64); final derivator = PBKDF2KeyDerivator(HMac(SHA256Digest(), 64)); final signer = RSASigner(SHA256Digest(), '0609608648016503040201'); ``` -------------------------------- ### Import pointycastle.dart for Registry Usage (Dart) Source: https://github.com/bcgit/pc-dart/blob/master/README.md Illustrates importing the main 'pointycastle.dart' file, which provides the high-level API and interface implementations. With this import, only the registry can be used to instantiate algorithm classes, as direct instantiation of implementation classes is not available. ```dart import "package:pointycastle/pointycastle.dart"; final sha256 = Digest("SHA-256"); // final md5 = MD5Digest(); // not available final p = Padding("PKCS7"); // final s = FortunaRandom(); // not available ``` -------------------------------- ### Instantiate Algorithms with Registry (Dart) Source: https://github.com/bcgit/pc-dart/blob/master/README.md Demonstrates how to use the registry to instantiate various cryptographic algorithms like digests, Message Authentication Codes (MACs), key derivators, and signers by providing their string names. This method simplifies the instantiation process for algorithms composed of multiple implementation classes. ```dart final sha256 = Digest("SHA-256"); final sha1 = Digest("SHA-1"); final md5 = Digest("MD5"); final hmacSha256 = Mac("SHA-256/HMAC"); final hmacSha1 = Mac("SHA-1/HMAC"); final hmacMd5 = Mac("MD5/HMAC"); final derivator = KeyDerivator("SHA-1/HMAC/PBKDF2"); final signer = Signer("SHA-256/RSA"); ``` -------------------------------- ### Initialize OAEPEncoding with RSAEngine Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Demonstrates initializing OAEPEncoding with an RSAEngine instance when the registry is not used. This is the first step before performing encryption or decryption operations. ```dart final p = OAEPEncoding(RSAEngine()); // final p = PKCS1Encoding(RSAEngine()); ``` -------------------------------- ### Instantiate Digest using Registry in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/digest.md Demonstrates how to instantiate a digest algorithm, such as SHA-256, by using the registry provided by the Pointy Castle package. This method is suitable for algorithms that do not require special constructor parameters. ```dart final d = Digest("SHA-256"); ``` -------------------------------- ### Initialize RSA Key Generator (Registry) Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Demonstrates initializing an RSA key generator using the registry by invoking the `KeyGenerator` factory with the algorithm name 'RSA'. ```dart final keyGen = KeyGenerator('RSA'); ``` -------------------------------- ### Import api.dart with Individual Libraries (Dart) Source: https://github.com/bcgit/pc-dart/blob/master/README.md Shows importing 'api.dart' along with specific algorithm implementation libraries. This approach provides the high-level API and allows direct instantiation of only the explicitly imported implementation classes, while also supporting registry usage. ```dart import "package:pointycastle/api.dart"; // additional imports will be needed import "package:pointycastle/digests/sha256.dart"; import "package:pointycastle/digests/md5.dart"; import 'package:pointycastle/paddings/pkcs7.dart'; final sha256 = Digest("SHA-256"); final md5 = MD5Digest(); final p = Padding("PKCS7"); // final s = FortunaRandom(); // not available without 'package:pointycastle/random/fortuna_random.dart' ``` -------------------------------- ### Accepting Warranty or Additional Liability for /bcgit/pc-dart Source: https://github.com/bcgit/pc-dart/blob/master/licenses/LICENSE-scrypt.txt Describes that users may offer support, warranty, indemnity, or other liability obligations consistent with the License when redistributing the Work or Derivative Works. It emphasizes acting solely on one's own behalf and responsibility. -------------------------------- ### Disclaimer of Warranty for /bcgit/pc-dart Source: https://github.com/bcgit/pc-dart/blob/master/licenses/LICENSE-scrypt.txt States that the Work and Contributions are provided on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. It clarifies that the user is responsible for determining the appropriateness of use and assumes associated risks. -------------------------------- ### Specifying Generic Types for PrivateKeyParameter in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/tips.md Illustrates the correct way to initialize a signer with a PrivateKeyParameter. It shows that simply passing a RSAPrivateKey to a generic PrivateKeyParameter can fail at runtime, and the correct approach is to explicitly specify the generic type, e.g., PrivateKeyParameter. ```dart RSAPrivateKey pvtKey = ... // RSAPrivateKey implements PrivateKey RSASigner signer = ... // PrivateKeyParameter is defined as: // // class PrivateKeyParameter // extends AsymmetricKeyParameter { // PrivateKeyParameter(PrivateKey key) : super(key); // } // This is type correct, but won't work: signer.init(true, PrivateKeyParameter(pvtKey)); // incorrect: fails at runtime // This works: signer.init(true, PrivateKeyParameter(pvtKey)); // correct ``` -------------------------------- ### Redistribution Conditions for /bcgit/pc-dart Source: https://github.com/bcgit/pc-dart/blob/master/licenses/LICENSE-scrypt.txt Details the conditions for reproducing and distributing copies of the Work or Derivative Works in any medium. It specifies requirements for providing the license, indicating file modifications, retaining notices, and including NOTICE file content. -------------------------------- ### Submission of Contributions Policy for /bcgit/pc-dart Source: https://github.com/bcgit/pc-dart/blob/master/licenses/LICENSE-scrypt.txt Explains that contributions submitted for inclusion in the Work are under the terms of the license, unless explicitly stated otherwise. It clarifies that this does not supersede separate license agreements for contributions. -------------------------------- ### Instantiate Digest without Registry in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/digest.md Shows how to directly instantiate a digest algorithm, like SHA256Digest, without using the registry. This approach is necessary for digest implementations that require specific parameters during instantiation. ```dart final d = SHA256Digest(); // SHA-256 ``` -------------------------------- ### Initialize AES-CBC Block Cipher using Registry Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/aes-cbc.md Demonstrates how to initialize an AES-CBC block cipher by using the Pointy Castle registry. This is a convenient way to obtain cipher instances by their algorithm name. ```dart final aesCbc = BlockCipher('AES/CBC'); ``` -------------------------------- ### Initialize RSA Key Generator (No Registry) Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Shows how to initialize an RSA key generator without using the registry by directly invoking the `RSAKeyGenerator` constructor. ```dart final keyGen = RSAKeyGenerator(); ``` -------------------------------- ### Trademark Usage Guidelines for /bcgit/pc-dart Source: https://github.com/bcgit/pc-dart/blob/master/licenses/LICENSE-scrypt.txt Outlines that the license does not grant permission to use the Licensor's trade names, trademarks, service marks, or product names, except for reasonable and customary use in describing the origin of the Work and reproducing NOTICE file content. -------------------------------- ### Type Casting for Key Types in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/tips.md Demonstrates how to cast generic PublicKey and PrivateKey types to specific RSA types (RSAPublicKey, RSAPrivateKey) after generating a key pair. This is necessary because the generateKeyPair method returns abstract types. ```dart final pair = keyGen.generateKeyPair(); // returns AsymmetricKeyPair final pub = pair.publicKey; // PublicKey - not very useful final pvt = pair.privateKey; // PrivateKey - not very useful final rsaPub = pair.publicKey as RSAPublicKey; final rsaPvt = pair.privateKey as RSAPrivateKey; ``` -------------------------------- ### Create Constructed ASN1UTF8String Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/asn1.md Shows how to create a constructed ASN1UTF8String object by providing child elements and manually setting the constructed tag. ```dart var e1 = ASN1UTF8String(utf8StringValue: 'Hello'); var e2 = ASN1UTF8String(utf8StringValue: ' World'); varar asn1Object = ASN1UTF8String(elements: [e1, e2], tag: ASN1Tags.UTF8_STRING_CONSTRUCTED); ``` -------------------------------- ### Create ASN1UTF8String Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/asn1.md Demonstrates creating an ASN1UTF8String object with a string value using the default constructor. ```dart var asn1Object = ASN1UTF8String(utf8StringValue: 'Hello World'); ``` -------------------------------- ### Initialize Signer and Verifier in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Initializes a signer with a private key for signing and a verifier with a public key for verification. The first parameter indicates the operation mode (signing or verifying), and the second parameter is the RSA key. ```dart signer.init(true, PrivateKeyParameter(privateKey)); ``` ```dart verifier.init(false, PublicKeyParameter(publicKey)); ``` -------------------------------- ### Configure RSA Key Generation Parameters Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Illustrates configuring the RSA key generator by creating `RSAKeyGeneratorParameters` with a public exponent, bit strength, and certainty factor, then combining it with a `SecureRandom` instance using `ParametersWithRandom`. ```dart SecureRandom mySecureRandom = ... final rsaParams = RSAKeyGeneratorParameters(BigInt.parse('65537'), 2048, 64); final paramsWithRnd = ParametersWithRandom(rsaParams, mySecureRandom); keyGen.init(paramsWithRnd); ``` -------------------------------- ### Instantiate AsymmetricBlockCipher using Registry in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Demonstrates how to instantiate an AsymmetricBlockCipher using the registry with cipher names like 'RSA/OAEP' or 'RSA/PKCS1'. ```dart final p = AsymmetricBlockCipher('RSA/OAEP'); // final p = AsymmetricBlockCipher('RSA/PKCS1); ``` -------------------------------- ### Using RSASigner without Registry Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Illustrates how to instantiate an RSASigner directly by providing a digest implementation object (e.g., SHA256Digest()) and the corresponding hexadecimal OID string for the signing algorithm. This requires manual specification of the correct OID. ```Dart final signer = RSASigner(SHA256Digest(), '0609608648016503040201'); ``` -------------------------------- ### RSA Signing and Verification with SHA-256 Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Demonstrates how to sign data using an RSAPrivateKey and verify a signature using an RSAPublicKey with the SHA-256 digest algorithm in Dart. It initializes the RSASigner for signing and verification, generates a signature, and verifies it. ```Dart import "package:pointycastle/export.dart"; Uint8List rsaSign(RSAPrivateKey privateKey, Uint8List dataToSign) { //final signer = Signer('SHA-256/RSA'); // Get using registry final signer = RSASigner(SHA256Digest(), '0609608648016503040201'); // initialize with true, which means sign signer.init(true, PrivateKeyParameter(privateKey)); final sig = signer.generateSignature(dataToSign); return sig.bytes; } bool rsaVerify( RSAPublicKey publicKey, Uint8List signedData, Uint8List signature) { //final signer = Signer('SHA-256/RSA'); // Get using registry final sig = RSASignature(signature); final verifier = RSASigner(SHA256Digest(), '0609608648016503040201'); // initialize with false, which means verify verifier.init(false, PublicKeyParameter(publicKey)); try { return verifier.verifySignature(signedData, sig); } on ArgumentError { return false; // for Pointy Castle 1.0.2 when signature has been modified } } ``` -------------------------------- ### Initialize AES-CBC Block Cipher without Registry Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/aes-cbc.md Shows how to initialize an AES-CBC block cipher directly by instantiating the CBCBlockCipher class and passing the AESEngine as a parameter. This method is used when not utilizing the Pointy Castle registry. ```dart final aesCbc = CBCBlockCipher(AESEngine()); ``` -------------------------------- ### Initialize for Encryption Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Initializes the asymmetric block cipher for encryption using the 'init' method. It requires a boolean 'true' to indicate encryption and the public key. ```dart p.init(true, PublicKeyParameter(myPublic)); ``` -------------------------------- ### Initialize AES-CBC for Encryption Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/aes-cbc.md Initializes an AES-CBC block cipher for encryption. It requires setting the cipher to encrypt mode (true) and providing the key and initialization vector (IV) using ParametersWithIV. ```dart aesCbc.init(true, ParametersWithIV(KeyParameter(key), iv)); // true=encrypt ``` -------------------------------- ### Instantiate HMAC using Registry in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/hmac.md Shows how to obtain an HMAC instance by using the Pointy Castle registry. The algorithm name is formed by appending "/HMAC" to the digest algorithm name. ```dart final hmac = Mac("SHA-256/HMAC"); ``` -------------------------------- ### Process Complete Data for Digest in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/digest.md Explains how to compute a digest when all input data is available as a single Uint8List. The `process` method takes the data and returns the calculated digest. ```dart final Uint8List dataToDigest = ... final hash = d.process(dataToDigest); ``` -------------------------------- ### Initialize HMac with Key in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/hmac.md Demonstrates how to initialize an HMac object with a secret key using the `KeyParameter` class before processing data. ```dart Uint8List keyBytes = ... hmac.init(KeyParameter(keyBytes)); ``` -------------------------------- ### Initialize for Decryption Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Initializes the asymmetric block cipher for decryption using the 'init' method. It requires a boolean 'false' to indicate decryption and the private key. ```dart p.init(false, PrivateKeyParameter(myPrivate)); ``` -------------------------------- ### Initialize AES-CBC for Decryption Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/aes-cbc.md Initializes an AES-CBC block cipher for decryption. It requires setting the cipher to decrypt mode (false) and providing the key and initialization vector (IV) using ParametersWithIV. ```dart aesCbc.init(false, ParametersWithIV(KeyParameter(key), iv)); // false=decrypt ``` -------------------------------- ### Generate and Cast RSA Key Pair Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Explains how to generate an RSA key pair by invoking the `generateKeyPair` method on an initialized `RSAKeyGenerator`. The resulting abstract `PublicKey` and `PrivateKey` need to be cast to `RSAPublicKey` and `RSAPrivateKey` respectively. ```dart final pair = keyGen.generateKeyPair(); final myPublic = pair.publicKey as RSAPublicKey; final myPrivate = pair.privateKey as RSAPrivateKey; ``` -------------------------------- ### Limitation of Liability for /bcgit/pc-dart Source: https://github.com/bcgit/pc-dart/blob/master/licenses/LICENSE-scrypt.txt Specifies that in no event shall any Contributor be liable for damages arising from the use or inability to use the Work, including direct, indirect, special, incidental, or consequential damages, even if advised of the possibility of such damages. -------------------------------- ### Generate RSA Key Pair in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Generates an RSA key pair using the Pointy Castle package. It requires a `SecureRandom` instance and allows specifying the key bit length. The generated keys are cast to `RSAPublicKey` and `RSAPrivateKey`. ```dart import 'dart:math'; import 'dart:typed_data'; import 'package:pointycastle/src/platform_check/platform_check.dart'; import "package:pointycastle/export.dart"; AsymmetricKeyPair generateRSAkeyPair( SecureRandom secureRandom, { int bitLength = 2048}) { // Create an RSA key generator and initialize it // final keyGen = KeyGenerator('RSA'); // Get using registry final keyGen = RSAKeyGenerator(); keyGen.init(ParametersWithRandom( RSAKeyGeneratorParameters(BigInt.parse('65537'), bitLength, 64), secureRandom)); // Use the generator final pair = keyGen.generateKeyPair(); // Cast the generated key pair into the RSA key types final myPublic = pair.publicKey as RSAPublicKey; final myPrivate = pair.privateKey as RSAPrivateKey; return AsymmetricKeyPair(myPublic, myPrivate); } SecureRandom exampleSecureRandom() { final secureRandom = SecureRandom('Fortuna') ..seed(KeyParameter( Platform.instance.platformEntropySource().getBytes(32))); return secureRandom; } ... ``` -------------------------------- ### RSA Encryption and Decryption in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Provides functions for RSA encryption and decryption using OAEP encoding with an RSAEngine. It includes a helper function to process data in blocks. ```dart import "package:pointycastle/export.dart"; Uint8List rsaEncrypt(RSAPublicKey myPublic, Uint8List dataToEncrypt) { final encryptor = OAEPEncoding(RSAEngine()) ..init(true, PublicKeyParameter(myPublic)); // true=encrypt return _processInBlocks(encryptor, dataToEncrypt); } Uint8List rsaDecrypt(RSAPrivateKey myPrivate, Uint8List cipherText) { final decryptor = OAEPEncoding(RSAEngine()) ..init(false, PrivateKeyParameter(myPrivate)); // false=decrypt return _processInBlocks(decryptor, cipherText); } Uint8List _processInBlocks(AsymmetricBlockCipher engine, Uint8List input) { final numBlocks = input.length ~/ engine.inputBlockSize + ((input.length % engine.inputBlockSize != 0) ? 1 : 0); final output = Uint8List(numBlocks * engine.outputBlockSize); var inputOffset = 0; var outputOffset = 0; while (inputOffset < input.length) { final chunkSize = (inputOffset + engine.inputBlockSize <= input.length) ? engine.inputBlockSize : input.length - inputOffset; outputOffset += engine.processBlock( input, inputOffset, chunkSize, output, outputOffset); inputOffset += chunkSize; } return (output.length == outputOffset) ? output : output.sublist(0, outputOffset); } ``` -------------------------------- ### Calculate HMAC SHA-256 in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/hmac.md Demonstrates calculating an HMAC SHA-256 using the Pointy Castle package. It initializes the HMac with a key and processes the data to produce the HMAC value. ```dart import 'dart:convert'; import 'dart:typed_data'; import "package:pointycastle/export.dart"; Uint8List hmacSha256(Uint8List hmacKey, Uint8List data) { final hmac = HMac(SHA256Digest(), 64) // HMAC SHA-256: block must be 64 bytes ..init(KeyParameter(hmacKey)); return hmac.process(data); } void main(List args) { final key = utf8.encode(args[0]); // first argument is the key final data = utf8.encode(args[1]); // second argument is the data final hmacValue = hmacSha256(key, data); print('HMAC SHA-256: $hmacValue'); } ``` -------------------------------- ### Process Complete Data for HMAC in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/hmac.md Illustrates processing a complete sequence of bytes to calculate the HMAC. The input data must be a `Uint8List`, and the result is returned as a `Uint8List`. ```dart final Uint8List data = ... final hmacValue = hmac.process(data); ``` -------------------------------- ### Verify RSA Signature in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Verifies an RSA signature against the original data. The verifySignature method returns true if the signature is valid, and false otherwise. Includes handling for ArgumentError in older Pointy Castle versions. ```dart final sig = RSASignature(signatureBytes); final sigOk = verifier.verifySignature(signedData, sig); ``` ```dart final sig = RSASignature(signatureBytes); bool sigOk; try { sigOk = verifier.verifySignature(signedData, sig); } on ArgumentError { sigOk = false; // required for Pointy Castle 1.0.2 and earlier } ``` -------------------------------- ### AES-CBC Encryption Function Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/aes-cbc.md Encrypts data using AES-CBC mode. Requires a key, initialization vector (IV), and padded plaintext. The key must be 128, 192, or 256 bits, and the IV must be 128 bits. The plaintext must be a multiple of the 128-bit block size. ```dart import 'dart:convert'; import 'dart:math'; import 'dart:typed_data'; import "package:pointycastle/export.dart"; Uint8List aesCbcEncrypt( Uint8List key, Uint8List iv, Uint8List paddedPlaintext) { assert([128, 192, 256].contains(key.length * 8)); assert(128 == iv.length * 8); assert(0 == paddedPlaintext.length % 16); // Create a CBC block cipher with AES, and initialize with key and IV final cbc = CBCBlockCipher(AESEngine()) ..init(true, ParametersWithIV(KeyParameter(key), iv)); // true=encrypt // Encrypt the plaintext block-by-block final cipherText = Uint8List(paddedPlaintext.length); // allocate space var offset = 0; while (offset < paddedPlaintext.length) { offset += cbc.processBlock(paddedPlaintext, offset, cipherText, offset); } assert(offset == paddedPlaintext.length); return cipherText; } ``` -------------------------------- ### Generate RSA Signature in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/rsa.md Generates an RSA signature for given data using the signer. The signature is returned as an RSASignature object, from which the raw bytes can be accessed via the 'bytes' getter. ```dart Uint8List dataToSign = ...; final sig = signer.generateSignature(dataToSign); final signatureBytes = sig.bytes; ``` -------------------------------- ### AES-CBC Decryption Function Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/aes-cbc.md Decrypts data using AES-CBC mode. Requires a key, initialization vector (IV), and ciphertext. The key must be 128, 192, or 256 bits, and the IV must be 128 bits. The ciphertext must be a multiple of the 128-bit block size. ```dart import 'dart:convert'; import 'dart:math'; import 'dart:typed_data'; import "package:pointycastle/export.dart"; Uint8List aesCbcDecrypt(Uint8List key, Uint8List iv, Uint8List cipherText) { assert([128, 192, 256].contains(key.length * 8)); assert(128 == iv.length * 8); assert(0 == cipherText.length % 16); // Create a CBC block cipher with AES, and initialize with key and IV final cbc = CBCBlockCipher(AESEngine()) ..init(false, ParametersWithIV(KeyParameter(key), iv)); // false=decrypt // Decrypt the cipherText block-by-block final paddedPlainText = Uint8List(cipherText.length); // allocate space var offset = 0; while (offset < cipherText.length) { offset += cbc.processBlock(cipherText, offset, paddedPlainText, offset); } assert(offset == cipherText.length); return paddedPlainText; } ``` -------------------------------- ### Process Data Progressively for HMAC in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/hmac.md Shows how to process data for HMAC calculation in chunks or byte by byte. It uses `updateByte` for single bytes and `update` for byte arrays, finishing with `doFinal`. ```dart final chunk1 = utf8.encode('cellophane'); final chunk2 = utf8.encode('world'); hmac.updateByte(0x48); // 'H' hmac.updateByte(0x65); // 'e' hmac.update(chunk1, 1, 4); hmac.updateByte(0x20); // ' ' hmac.update(chunk2, 0, chunk2.length); hmac.updateByte(0x21); // '!' final hmacValue = Uint8List(hmac.macSize); // create a destination for storing the HMAC hmac.doFinal(hmacValue, 0); // HMAC of "Hello world!" ``` -------------------------------- ### Parse ASN1 Data from Base64 String in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/asn1.md This snippet shows how to decode a Base64 encoded string representing an ASN.1 structure into a Dart byte list and then parse it using the ASN1Parser. It iterates through the parsed elements, extracting object identifiers and string values. ```dart import 'package:asn1lib/asn1lib.dart'; // Base64 encoded string that represents the above structure var base64String = 'MFwxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xGzAZBgNVBAMTElRoYXd0ZSBSU0EgQ0EgMjAxOA=='; // Convert to byte list var bytes = base64.decode(base64String); // Pass the byte list to the ASN1Parser var parser = ASN1Parser(bytes); // Grab the first element by calling nextObject() and cast it to ASN1Sequence var sequence = parser.nextObject() as ASN1Sequence; // Iterate over each element sequence.elements.forEach((element) { var asn1Set = element as ASN1Set; var seq = asn1Set.elements.elementAt(0) as ASN1Sequence; var objectIdentifier = seq.elements.elementAt(0) as ASN1ObjectIdentifier; var printableString = seq.elements.elementAt(1) as ASN1PrintableString; print('${objectIdentifier.objectIdentifierAsString} = ${printableString.stringValue}'); }); ``` -------------------------------- ### Calculate SHA-256 Digest in Dart Source: https://github.com/bcgit/pc-dart/blob/master/tutorials/digest.md Calculates the SHA-256 digest of a given Uint8List using the Pointy Castle library. This function processes the input data and returns the resulting digest. ```dart import 'dart:convert'; import 'dart:typed_data'; import "package:pointycastle/export.dart"; Uint8List sha256Digest(Uint8List dataToDigest) { final d = SHA256Digest(); return d.process(dataToDigest); } void main(List args) { final valuesToDigest = (args.isNotEmpty) ? args : ['Hello world!']; for (final data in valuesToDigest) { print('Data: "$data"'); final hash = sha256Digest(utf8.encode(data) as Uint8List); print('SHA-256: $hash'); print('SHA-256: ${bin2hex(hash)}'); // output in hexadecimal } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.