本文整理汇总了C#中Org.BouncyCastle.Security.SecureRandom.NextBytes方法的典型用法代码示例。如果您正苦于以下问题:C# SecureRandom.NextBytes方法的具体用法?C# SecureRandom.NextBytes怎么用?C# SecureRandom.NextBytes使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Org.BouncyCastle.Security.SecureRandom
的用法示例。
在下文中一共展示了SecureRandom.NextBytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Encrypt
public string Encrypt(string data)
{
SecureRandom random = new SecureRandom();
// Generate 256-bits AES key
byte[] aesKey = new byte[32];
random.NextBytes(aesKey);
// Generate Initialization Vector
byte[] IV = new byte[12];
random.NextBytes(IV);
// Apply RSA/None/PKCS1Padding encryption to the AES key
byte[] encyptedAESKey = rsaCipher.DoFinal(aesKey);
// Apply AES/CCM/NoPadding encryption to the data
byte[] cipherText = System.Text.Encoding.UTF8.GetBytes(data);
var ccmParameters = new CcmParameters(new KeyParameter(aesKey), 64, IV, new byte[] { });
aesCipher = new CcmBlockCipher(new AesFastEngine());
aesCipher.Init(true, ccmParameters);
var encrypted = new byte[aesCipher.GetOutputSize(cipherText.Length)];
var res = aesCipher.ProcessBytes(cipherText, 0, cipherText.Length, encrypted, 0);
aesCipher.DoFinal(encrypted, res);
// Merge 'IV' and 'encrypted' to 'result'
byte[] result = new byte[IV.Length + encrypted.Length];
System.Buffer.BlockCopy(IV, 0, result, 0, IV.Length);
System.Buffer.BlockCopy(encrypted, 0, result, IV.Length, encrypted.Length);
// Return encrypted data
return Prefix + Version + Separator + System.Convert.ToBase64String(encyptedAESKey) + Separator + System.Convert.ToBase64String(result);
}
示例2: EscrowCodeSet
/// <summary>
/// Default constructor. Creates a new matched pair of escrow invitation codes.
/// </summary>
public EscrowCodeSet()
{
SecureRandom sr = new SecureRandom();
byte[] x = new byte[32];
byte[] y = new byte[32];
sr.NextBytes(x);
sr.NextBytes(y);
// Force x to be even
// Force y to be odd
x[31] &= 0xFE;
y[31] |= 0x01;
KeyPair kx = new KeyPair(x, true);
KeyPair ky = new KeyPair(y, true);
BigInteger xi = new BigInteger(1, x);
BigInteger yi = new BigInteger(1, y);
ECPoint Gx = kx.GetECPoint();
byte[] bytesGx = Gx.GetEncoded();
ECPoint Gy = ky.GetECPoint();
byte[] bytesGy = Gy.GetEncoded();
ECPoint Gxy = Gx.Multiply(yi);
byte[] bytesGxy = Gxy.GetEncoded();
Sha256Digest sha256 = new Sha256Digest();
byte[] hashGxy = new byte[32];
sha256.BlockUpdate(bytesGxy, 0, bytesGxy.Length);
sha256.DoFinal(hashGxy, 0);
sha256.BlockUpdate(hashGxy, 0, 32);
sha256.DoFinal(hashGxy, 0);
int identifier30 = ((hashGxy[0] & 0x3f) << 24) + (hashGxy[1] << 16) + (hashGxy[2] << 8) + hashGxy[3];
byte[] invitationA = new byte[74];
byte[] invitationB = new byte[74];
long headA = headbaseA + (long)identifier30;
long headB = headbaseB + (long)identifier30;
// turn headA and headB into bytes
for (int i = 7; i >= 0; i--) {
invitationA[i] = (byte)(headA & 0xFF);
invitationB[i] = (byte)(headB & 0xFF);
headA >>= 8;
headB >>= 8;
}
Array.Copy(x, 0, invitationA, 8 + 1, 32);
Array.Copy(y, 0, invitationB, 8 + 1, 32);
Array.Copy(bytesGy, 0, invitationA, 8 + 1 + 32, 33);
Array.Copy(bytesGx, 0, invitationB, 8 + 1 + 32, 33);
EscrowInvitationCodeA = Util.ByteArrayToBase58Check(invitationA);
EscrowInvitationCodeB = Util.ByteArrayToBase58Check(invitationB);
}
示例3: RandomTest
private void RandomTest(SecureRandom random)
{
byte[] key = new byte[16];
random.NextBytes(key);
int length = 1 + random.Next(1024);
byte[] input = new byte[length];
random.NextBytes(input);
SipHash mac = new SipHash();
mac.Init(new KeyParameter(key));
UpdateMac(mac, input, UPDATE_BYTES);
long result1 = mac.DoFinal();
UpdateMac(mac, input, UPDATE_FULL);
long result2 = mac.DoFinal();
UpdateMac(mac, input, UPDATE_MIX);
long result3 = mac.DoFinal();
if (result1 != result2 || result1 != result3)
{
Fail("Inconsistent results in random test");
}
}
示例4: Test
public static void Test()
{
Console.Out.WriteLine("Begin Example_060.");
// Create the AES Service
AESService aes = new AESService();
string password = "password";
SecureRandom random = new SecureRandom();
byte[] salt = new byte[AESService.SALT_SIZE];
random.NextBytes(salt);
// Create the AES Key using password and salt.
aes.GenerateKey(password, salt);
// Encode and Decode a string then compare to verify they are the same.
string clear_text = "This is a test";
byte[] enc_bytes = aes.Encode(UTF8Encoding.UTF8.GetBytes(clear_text));
byte[] dec_bytes = aes.Decode(enc_bytes);
string dec_text = UTF8Encoding.UTF8.GetString(dec_bytes);
/**
* Compare the original and decrypted files.
*/
if (Compare.SafeEquals(UTF8Encoding.UTF8.GetBytes(clear_text), UTF8Encoding.UTF8.GetBytes(dec_text)))
{
Console.Out.WriteLine("Original and Decrypted are the same!");
}
else
{
Console.Out.WriteLine("Original and Decrypted are NOT the same!");
}
Console.Out.WriteLine("End Example_060.");
}
示例5: Generate
public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
{
byte[] keyBytes = contentEncryptionKey.GetKey();
string rfc3211WrapperName = Helper.GetRfc3211WrapperName(keyEncryptionKeyOID);
IWrapper keyWrapper = Helper.CreateWrapper(rfc3211WrapperName);
// Note: In Java build, the IV is automatically generated in JCE layer
int ivLength = Platform.StartsWith(rfc3211WrapperName, "DESEDE") ? 8 : 16;
byte[] iv = new byte[ivLength];
random.NextBytes(iv);
ICipherParameters parameters = new ParametersWithIV(keyEncryptionKey, iv);
keyWrapper.Init(true, new ParametersWithRandom(parameters, random));
Asn1OctetString encryptedKey = new DerOctetString(
keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));
DerSequence seq = new DerSequence(
new DerObjectIdentifier(keyEncryptionKeyOID),
new DerOctetString(iv));
AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier(
PkcsObjectIdentifiers.IdAlgPwriKek, seq);
return new RecipientInfo(new PasswordRecipientInfo(
keyDerivationAlgorithm, keyEncryptionAlgorithm, encryptedKey));
}
示例6: GenerateEncryptedPreMasterSecret
public static byte[] GenerateEncryptedPreMasterSecret(SecureRandom random,
RsaKeyParameters rsaServerPublicKey, Stream output)
{
/*
* Choose a PremasterSecret and send it encrypted to the server
*/
byte[] premasterSecret = new byte[48];
random.NextBytes(premasterSecret);
TlsUtilities.WriteVersion(premasterSecret, 0);
Pkcs1Encoding encoding = new Pkcs1Encoding(new RsaBlindedEngine());
encoding.Init(true, new ParametersWithRandom(rsaServerPublicKey, random));
try
{
byte[] keData = encoding.ProcessBlock(premasterSecret, 0, premasterSecret.Length);
TlsUtilities.WriteOpaque16(keData, output);
}
catch (InvalidCipherTextException)
{
/*
* This should never happen, only during decryption.
*/
throw new TlsFatalAlert(AlertDescription.internal_error);
}
return premasterSecret;
}
示例7: DoTestClientServer
private static void DoTestClientServer(bool fragment)
{
SecureRandom secureRandom = new SecureRandom();
TlsClientProtocol clientProtocol = new TlsClientProtocol(secureRandom);
TlsServerProtocol serverProtocol = new TlsServerProtocol(secureRandom);
clientProtocol.Connect(new MockTlsClient(null));
serverProtocol.Accept(new MockTlsServer());
// pump handshake
bool hadDataFromServer = true;
bool hadDataFromClient = true;
while (hadDataFromServer || hadDataFromClient)
{
hadDataFromServer = PumpData(serverProtocol, clientProtocol, fragment);
hadDataFromClient = PumpData(clientProtocol, serverProtocol, fragment);
}
// send data in both directions
byte[] data = new byte[1024];
secureRandom.NextBytes(data);
WriteAndRead(clientProtocol, serverProtocol, data, fragment);
WriteAndRead(serverProtocol, clientProtocol, data, fragment);
// close the connection
clientProtocol.Close();
PumpData(clientProtocol, serverProtocol, fragment);
CheckClosed(serverProtocol);
CheckClosed(clientProtocol);
}
示例8: MakeSeedAndPayload
private void MakeSeedAndPayload(out byte[] seed, out byte[] payload)
{
var rnd = new SecureRandom();
var priv = new byte[32];
rnd.NextBytes(priv);
payload = MontgomeryCurve25519.GetPublicKey(priv);
seed = MontgomeryCurve25519.KeyExchange(MY_PUBLIC, priv);
}
示例9: Encrypt
public JObject Encrypt(string key, JObject blob, string adata)
{
var result = new JObject();
var random = new SecureRandom();
var iv = new byte[32];
var salt = new byte[8];
random.NextBytes(salt);
random.NextBytes(iv);
try
{
byte[] plainBytes = Encoding.UTF8.GetBytes(blob.ToString());
byte[] adataBytes = Encoding.UTF8.GetBytes(adata);
byte[] nonce = ComputeNonce(iv, plainBytes);
KeyParameter keyParam = CreateKey(key, salt, _iter, _ks);
var ccm = new AeadParameters(keyParam, MacSize(_ts), nonce, adataBytes);
var aes = new CcmBlockCipher(new AesFastEngine());
aes.Init(true, ccm);
var enc = new byte[aes.GetOutputSize(plainBytes.Length)];
int res = aes.ProcessBytes(plainBytes, 0, plainBytes.Length, enc, 0);
aes.DoFinal(enc, res);
result.Add("ct", Base64.ToBase64String(enc));
result.Add("iv", Base64.ToBase64String(iv));
result.Add("salt", Base64.ToBase64String(salt));
result.Add("adata", EncodeAdata(adata));
result.Add("mode", Mode);
result.Add("ks", _ks);
result.Add("iter", _iter);
result.Add("ts", _ts);
return result;
}
catch (Exception e)
{
throw new ApplicationException("Json encryption failed.", e);
}
}
示例10: Bip38Intermediate
/// <summary>
/// Create an intermediate from a passphrase or intermediate code
/// </summary>
public Bip38Intermediate(string fromstring, Interpretation interpretation)
{
if (interpretation == Interpretation.IntermediateCode) {
createFromCode(fromstring);
} else {
_ownersalt = new byte[8];
// Get 8 random bytes to use as salt
SecureRandom sr = new SecureRandom();
sr.NextBytes(_ownersalt);
createFromPassphrase(fromstring, _ownersalt);
}
}
示例11: AbstractTlsContext
internal AbstractTlsContext(SecureRandom secureRandom, SecurityParameters securityParameters)
{
IDigest d = TlsUtilities.CreateHash(HashAlgorithm.sha256);
byte[] seed = new byte[d.GetDigestSize()];
secureRandom.NextBytes(seed);
this.mNonceRandom = new DigestRandomGenerator(d);
mNonceRandom.AddSeedMaterial(NextCounterValue());
mNonceRandom.AddSeedMaterial(Times.NanoTime());
mNonceRandom.AddSeedMaterial(seed);
this.mSecureRandom = secureRandom;
this.mSecurityParameters = securityParameters;
}
示例12: Bip38Intermediate
/// <summary>
/// Create an intermediate from a passphrase or intermediate code
/// </summary>
public Bip38Intermediate(string fromstring, Interpretation interpretation, int startingSequenceNumber = 0)
{
if (interpretation == Interpretation.IntermediateCode) {
createFromCode(fromstring);
} else {
_ownerentropy = new byte[8];
// Get 8 random bytes to use as salt
SecureRandom sr = new SecureRandom();
sr.NextBytes(_ownerentropy);
// set lot number between 100000 and 999999, and sequence number to 1
long x = (sr.NextLong () % 900000L + 100000L) * 4096L + (long)startingSequenceNumber;
for (int i=7; i>=4; i--) {
_ownerentropy[i] = (byte)(x & 0xFF);
x >>= 8;
}
createFromPassphrase(fromstring, _ownerentropy, true);
}
}
示例13: Test
public static void Test()
{
Console.Out.WriteLine("Begin Example_070.");
string password = "password1";
string secret_key = "secret-shared-key";
string content = "Lorem ipsum dolor sit amet, duo cu nobis epicurei hendrerit, mei agam elit an.";
string hmac = HMAC.Sha256(content, secret_key);
Console.Out.WriteLine("HMAC_sha256: " + hmac);
string hex_string = Hex.Encode(UTF8Encoding.UTF8.GetBytes(content));
Console.Out.WriteLine("Content Hex String: " + hex_string);
SecureRandom random = new SecureRandom();
byte[] salt = new byte[AESService.SALT_SIZE];
random.NextBytes(salt);
hmac = HMAC.Sha256(content, password);
Console.Out.WriteLine("HMAC_sha256: " + hmac);
Console.Out.WriteLine("End Example_070.");
}
示例14: TestClientServer
public void TestClientServer()
{
SecureRandom secureRandom = new SecureRandom();
PipedStream clientPipe = new PipedStream();
PipedStream serverPipe = new PipedStream(clientPipe);
TlsClientProtocol clientProtocol = new TlsClientProtocol(clientPipe, secureRandom);
TlsServerProtocol serverProtocol = new TlsServerProtocol(serverPipe, secureRandom);
Server server = new Server(serverProtocol);
Thread serverThread = new Thread(new ThreadStart(server.Run));
serverThread.Start();
MockSrpTlsClient client = new MockSrpTlsClient(null, MockSrpTlsServer.TEST_IDENTITY, MockSrpTlsServer.TEST_PASSWORD);
clientProtocol.Connect(client);
// NOTE: Because we write-all before we read-any, this length can't be more than the pipe capacity
int length = 1000;
byte[] data = new byte[length];
secureRandom.NextBytes(data);
Stream output = clientProtocol.Stream;
output.Write(data, 0, data.Length);
byte[] echo = new byte[data.Length];
int count = Streams.ReadFully(clientProtocol.Stream, echo);
Assert.AreEqual(count, data.Length);
Assert.IsTrue(Arrays.AreEqual(data, echo));
output.Close();
serverThread.Join();
}
示例15: CreatePemObject
// private string GetHexEncoded(byte[] bytes)
// {
// bytes = Hex.Encode(bytes);
//
// char[] chars = new char[bytes.Length];
//
// for (int i = 0; i != bytes.Length; i++)
// {
// chars[i] = (char)bytes[i];
// }
//
// return new string(chars);
// }
private PemObject CreatePemObject(
object obj,
string algorithm,
char[] password,
SecureRandom random)
{
if (obj == null)
throw new ArgumentNullException("obj");
if (algorithm == null)
throw new ArgumentNullException("algorithm");
if (password == null)
throw new ArgumentNullException("password");
if (random == null)
throw new ArgumentNullException("random");
if (obj is AsymmetricCipherKeyPair)
{
return CreatePemObject(((AsymmetricCipherKeyPair)obj).Private, algorithm, password, random);
}
string type = null;
byte[] keyData = null;
if (obj is AsymmetricKeyParameter)
{
AsymmetricKeyParameter akp = (AsymmetricKeyParameter) obj;
if (akp.IsPrivate)
{
string keyType;
keyData = EncodePrivateKey(akp, out keyType);
type = keyType + " PRIVATE KEY";
}
}
if (type == null || keyData == null)
{
// TODO Support other types?
throw new PemGenerationException("Object type not supported: " + obj.GetType().FullName);
}
string dekAlgName = algorithm.ToUpper(CultureInfo.InvariantCulture);
// Note: For backward compatibility
if (dekAlgName == "DESEDE")
{
dekAlgName = "DES-EDE3-CBC";
}
int ivLength = dekAlgName.StartsWith("AES-") ? 16 : 8;
byte[] iv = new byte[ivLength];
random.NextBytes(iv);
byte[] encData = PemUtilities.Crypt(true, keyData, password, dekAlgName, iv);
IList headers = Platform.CreateArrayList(2);
headers.Add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
headers.Add(new PemHeader("DEK-Info", dekAlgName + "," + Hex.ToHexString(iv)));
return new PemObject(type, headers, encData);
}