Files
Assets
BuiltinAssets
CSAssets
Editor
Gizmos
Plugins
Android
Best HTTP
Source
Authentication
Caching
Connections
Cookies
Core
Decompression
Extensions
Forms
JSON
Logger
PlatformSupport
Proxies
SecureProtocol
asn1
cms
crmf
crypto
agreement
digests
ec
encodings
engines
AesEngine.cs
AesEngine.cs.meta
AesFastEngine.cs
AesFastEngine.cs.meta
AesLightEngine.cs
AesLightEngine.cs.meta
AesWrapEngine.cs
AesWrapEngine.cs.meta
BlowfishEngine.cs
BlowfishEngine.cs.meta
CamelliaEngine.cs
CamelliaEngine.cs.meta
CamelliaLightEngine.cs
CamelliaLightEngine.cs.meta
CamelliaWrapEngine.cs
CamelliaWrapEngine.cs.meta
Cast5Engine.cs
Cast5Engine.cs.meta
Cast6Engine.cs
Cast6Engine.cs.meta
ChaCha7539Engine.cs
ChaCha7539Engine.cs.meta
ChaChaEngine.cs
ChaChaEngine.cs.meta
DesEdeEngine.cs
DesEdeEngine.cs.meta
DesEdeWrapEngine.cs
DesEdeWrapEngine.cs.meta
DesEngine.cs
DesEngine.cs.meta
Dstu7624Engine.cs
Dstu7624Engine.cs.meta
Dstu7624WrapEngine.cs
Dstu7624WrapEngine.cs.meta
ElGamalEngine.cs
ElGamalEngine.cs.meta
GOST28147Engine.cs
GOST28147Engine.cs.meta
HC128Engine.cs
HC128Engine.cs.meta
HC256Engine.cs
HC256Engine.cs.meta
ISAACEngine.cs
ISAACEngine.cs.meta
IdeaEngine.cs
IdeaEngine.cs.meta
IesEngine.cs
IesEngine.cs.meta
NaccacheSternEngine.cs
NaccacheSternEngine.cs.meta
NoekeonEngine.cs
NoekeonEngine.cs.meta
NullEngine.cs
NullEngine.cs.meta
RC2Engine.cs
RC2Engine.cs.meta
RC2WrapEngine.cs
RC2WrapEngine.cs.meta
RC4Engine.cs
RC4Engine.cs.meta
RC532Engine.cs
RC532Engine.cs.meta
RC564Engine.cs
RC564Engine.cs.meta
RC6Engine.cs
RC6Engine.cs.meta
RFC3211WrapEngine.cs
RFC3211WrapEngine.cs.meta
RFC3394WrapEngine.cs
RFC3394WrapEngine.cs.meta
RSABlindedEngine.cs
RSABlindedEngine.cs.meta
RSABlindingEngine.cs
RSABlindingEngine.cs.meta
RSACoreEngine.cs
RSACoreEngine.cs.meta
RijndaelEngine.cs
RijndaelEngine.cs.meta
RsaEngine.cs
RsaEngine.cs.meta
SEEDEngine.cs
SEEDEngine.cs.meta
SEEDWrapEngine.cs
SEEDWrapEngine.cs.meta
SM2Engine.cs
SM2Engine.cs.meta
SM4Engine.cs
SM4Engine.cs.meta
Salsa20Engine.cs
Salsa20Engine.cs.meta
SerpentEngine.cs
SerpentEngine.cs.meta
SerpentEngineBase.cs
SerpentEngineBase.cs.meta
SkipjackEngine.cs
SkipjackEngine.cs.meta
TEAEngine.cs
TEAEngine.cs.meta
ThreefishEngine.cs
ThreefishEngine.cs.meta
TnepresEngine.cs
TnepresEngine.cs.meta
TwofishEngine.cs
TwofishEngine.cs.meta
VMPCEngine.cs
VMPCEngine.cs.meta
VMPCKSA3Engine.cs
VMPCKSA3Engine.cs.meta
XSalsa20Engine.cs
XSalsa20Engine.cs.meta
XTEAEngine.cs
XTEAEngine.cs.meta
generators
io
macs
modes
operators
paddings
parameters
prng
signers
tls
util
AsymmetricCipherKeyPair.cs
AsymmetricCipherKeyPair.cs.meta
AsymmetricKeyParameter.cs
AsymmetricKeyParameter.cs.meta
BufferedAeadBlockCipher.cs
BufferedAeadBlockCipher.cs.meta
BufferedAeadCipher.cs
BufferedAeadCipher.cs.meta
BufferedAsymmetricBlockCipher.cs
BufferedAsymmetricBlockCipher.cs.meta
BufferedBlockCipher.cs
BufferedBlockCipher.cs.meta
BufferedCipherBase.cs
BufferedCipherBase.cs.meta
BufferedIesCipher.cs
BufferedIesCipher.cs.meta
BufferedStreamCipher.cs
BufferedStreamCipher.cs.meta
Check.cs
Check.cs.meta
CipherKeyGenerator.cs
CipherKeyGenerator.cs.meta
CryptoException.cs
CryptoException.cs.meta
DataLengthException.cs
DataLengthException.cs.meta
IAsymmetricBlockCipher.cs
IAsymmetricBlockCipher.cs.meta
IAsymmetricCipherKeyPairGenerator.cs
IAsymmetricCipherKeyPairGenerator.cs.meta
IBasicAgreement.cs
IBasicAgreement.cs.meta
IBlockCipher.cs
IBlockCipher.cs.meta
IBlockResult.cs
IBlockResult.cs.meta
IBufferedCipher.cs
IBufferedCipher.cs.meta
ICipher.cs
ICipher.cs.meta
ICipherBuilder.cs
ICipherBuilder.cs.meta
ICipherBuilderWithKey.cs
ICipherBuilderWithKey.cs.meta
ICipherParameters.cs
ICipherParameters.cs.meta
IDSA.cs
IDSA.cs.meta
IDecryptorBuilderProvider.cs
IDecryptorBuilderProvider.cs.meta
IDerivationFunction.cs
IDerivationFunction.cs.meta
IDerivationParameters.cs
IDerivationParameters.cs.meta
IDigest.cs
IDigest.cs.meta
IDsaExt.cs
IDsaExt.cs.meta
IEntropySource.cs
IEntropySource.cs.meta
IEntropySourceProvider.cs
IEntropySourceProvider.cs.meta
IKeyUnwrapper.cs
IKeyUnwrapper.cs.meta
IKeyWrapper.cs
IKeyWrapper.cs.meta
IMac.cs
IMac.cs.meta
IMacDerivationFunction.cs
IMacDerivationFunction.cs.meta
IMacFactory.cs
IMacFactory.cs.meta
IRawAgreement.cs
IRawAgreement.cs.meta
IRsa.cs
IRsa.cs.meta
ISignatureFactory.cs
ISignatureFactory.cs.meta
ISigner.cs
ISigner.cs.meta
ISignerWithRecovery.cs
ISignerWithRecovery.cs.meta
IStreamCalculator.cs
IStreamCalculator.cs.meta
IStreamCipher.cs
IStreamCipher.cs.meta
IVerifier.cs
IVerifier.cs.meta
IVerifierFactory.cs
IVerifierFactory.cs.meta
IVerifierFactoryProvider.cs
IVerifierFactoryProvider.cs.meta
IWrapper.cs
IWrapper.cs.meta
IXof.cs
IXof.cs.meta
InvalidCipherTextException.cs
InvalidCipherTextException.cs.meta
KeyGenerationParameters.cs
KeyGenerationParameters.cs.meta
MaxBytesExceededException.cs
MaxBytesExceededException.cs.meta
OutputLengthException.cs
OutputLengthException.cs.meta
PbeParametersGenerator.cs
PbeParametersGenerator.cs.meta
Security.cs
Security.cs.meta
SimpleBlockResult.cs
SimpleBlockResult.cs.meta
StreamBlockCipher.cs
StreamBlockCipher.cs.meta
agreement.meta
digests.meta
ec.meta
encodings.meta
engines.meta
generators.meta
io.meta
macs.meta
modes.meta
operators.meta
paddings.meta
parameters.meta
prng.meta
signers.meta
tls.meta
util.meta
math
ocsp
openssl
pkcs
pkix
security
tsp
util
x509
License.txt
License.txt.meta
ReflectionHelpers.cs
ReflectionHelpers.cs.meta
asn1.meta
cms.meta
crmf.meta
crypto.meta
math.meta
ocsp.meta
openssl.meta
pkcs.meta
pkix.meta
security.meta
tsp.meta
util.meta
x509.meta
ServerSentEvents
SignalR
SignalRCore
SocketIO
WebSocket
Authentication.meta
Caching.meta
Connections.meta
Cookies.meta
Core.meta
Decompression.meta
Extensions.meta
Forms.meta
HTTPManager.cs
HTTPManager.cs.meta
HTTPMethods.cs
HTTPMethods.cs.meta
HTTPRange.cs
HTTPRange.cs.meta
HTTPRequest.cs
HTTPRequest.cs.meta
HTTPResponse.cs
HTTPResponse.cs.meta
HTTPUpdateDelegator.cs
HTTPUpdateDelegator.cs.meta
JSON.meta
Logger.meta
PlatformSupport.meta
Proxies.meta
SecureProtocol.meta
ServerSentEvents.meta
SignalR.meta
SignalRCore.meta
SocketIO.meta
WebSocket.meta
WebGL
BestHTTP.asmdef
BestHTTP.asmdef.meta
Documentation.txt
Documentation.txt.meta
ReleaseNotes.txt
ReleaseNotes.txt.meta
Source.meta
WebGL.meta
license.txt
license.txt.meta
link.xml
link.xml.meta
link_android_subset.xml
link_android_subset.xml.meta
Cinemachine
DOTween
Editor
Gizmos
Https
IOS
JsCode
Lib
LitJson
NativeGallery
NavMeshExtension
Pixelplacement
PostProcessing
Script
YunvaIMScript
x86
x86_64
xlua.bundle
Android.meta
Best HTTP.meta
Cinemachine.meta
DOTween.meta
Editor.meta
Gizmos.meta
Https.meta
IOS.meta
JsCode.meta
Lib.meta
LitJson.meta
NativeGallery.meta
NavMeshExtension.meta
Pixelplacement.meta
PostProcessing.meta
Script.meta
YunvaIMScript.meta
x86.meta
x86_64.meta
xlua.bundle.meta
Project
Project3D
Res_newMS
StreamingAssets
T4M
T4MOBJ
UnusedAssets
XLua
BuiltinAssets.meta
CSAssets.meta
Editor.meta
Gizmos.meta
Plugins.meta
Project.meta
Project3D.meta
Res_newMS.meta
StreamingAssets.meta
T4M.meta
T4MOBJ.meta
UnusedAssets.meta
XLua.meta
ChannelConfig
ExcelC#
ExcelExport
ExcelTexts
JjbbDll
ProjectSettings
Sdk
UnityPackageManager
UnusedAssets
.gitignore
README.md
JJBB/Assets/Plugins/Best HTTP/Source/SecureProtocol/crypto/engines/IesEngine.cs

248 lines
8.1 KiB
C#
Raw Normal View History

2024-08-23 15:49:34 +08:00
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
#pragma warning disable
using System;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
{
/**
* support class for constructing intergrated encryption ciphers
* for doing basic message exchanges on top of key agreement ciphers
*/
public class IesEngine
{
private readonly IBasicAgreement agree;
private readonly IDerivationFunction kdf;
private readonly IMac mac;
private readonly BufferedBlockCipher cipher;
private readonly byte[] macBuf;
private bool forEncryption;
private ICipherParameters privParam, pubParam;
private IesParameters param;
/**
* set up for use with stream mode, where the key derivation function
* is used to provide a stream of bytes to xor with the message.
*
* @param agree the key agreement used as the basis for the encryption
* @param kdf the key derivation function used for byte generation
* @param mac the message authentication code generator for the message
*/
public IesEngine(
IBasicAgreement agree,
IDerivationFunction kdf,
IMac mac)
{
this.agree = agree;
this.kdf = kdf;
this.mac = mac;
this.macBuf = new byte[mac.GetMacSize()];
// this.cipher = null;
}
/**
* set up for use in conjunction with a block cipher to handle the
* message.
*
* @param agree the key agreement used as the basis for the encryption
* @param kdf the key derivation function used for byte generation
* @param mac the message authentication code generator for the message
* @param cipher the cipher to used for encrypting the message
*/
public IesEngine(
IBasicAgreement agree,
IDerivationFunction kdf,
IMac mac,
BufferedBlockCipher cipher)
{
this.agree = agree;
this.kdf = kdf;
this.mac = mac;
this.macBuf = new byte[mac.GetMacSize()];
this.cipher = cipher;
}
/**
* Initialise the encryptor.
*
* @param forEncryption whether or not this is encryption/decryption.
* @param privParam our private key parameters
* @param pubParam the recipient's/sender's public key parameters
* @param param encoding and derivation parameters.
*/
public virtual void Init(
bool forEncryption,
ICipherParameters privParameters,
ICipherParameters pubParameters,
ICipherParameters iesParameters)
{
this.forEncryption = forEncryption;
this.privParam = privParameters;
this.pubParam = pubParameters;
this.param = (IesParameters)iesParameters;
}
private byte[] DecryptBlock(
byte[] in_enc,
int inOff,
int inLen,
byte[] z)
{
byte[] M = null;
KeyParameter macKey = null;
KdfParameters kParam = new KdfParameters(z, param.GetDerivationV());
int macKeySize = param.MacKeySize;
kdf.Init(kParam);
// Ensure that the length of the input is greater than the MAC in bytes
if (inLen < mac.GetMacSize())
throw new InvalidCipherTextException("Length of input must be greater than the MAC");
inLen -= mac.GetMacSize();
if (cipher == null) // stream mode
{
byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8));
M = new byte[inLen];
for (int i = 0; i != inLen; i++)
{
M[i] = (byte)(in_enc[inOff + i] ^ Buffer[i]);
}
macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8));
}
else
{
int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize;
byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8));
cipher.Init(false, new KeyParameter(Buffer, 0, (cipherKeySize / 8)));
M = cipher.DoFinal(in_enc, inOff, inLen);
macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8));
}
byte[] macIV = param.GetEncodingV();
mac.Init(macKey);
mac.BlockUpdate(in_enc, inOff, inLen);
mac.BlockUpdate(macIV, 0, macIV.Length);
mac.DoFinal(macBuf, 0);
inOff += inLen;
byte[] T1 = Arrays.CopyOfRange(in_enc, inOff, inOff + macBuf.Length);
if (!Arrays.ConstantTimeAreEqual(T1, macBuf))
throw (new InvalidCipherTextException("Invalid MAC."));
return M;
}
private byte[] EncryptBlock(
byte[] input,
int inOff,
int inLen,
byte[] z)
{
byte[] C = null;
KeyParameter macKey = null;
KdfParameters kParam = new KdfParameters(z, param.GetDerivationV());
int c_text_length = 0;
int macKeySize = param.MacKeySize;
if (cipher == null) // stream mode
{
byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8));
C = new byte[inLen + mac.GetMacSize()];
c_text_length = inLen;
for (int i = 0; i != inLen; i++)
{
C[i] = (byte)(input[inOff + i] ^ Buffer[i]);
}
macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8));
}
else
{
int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize;
byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8));
cipher.Init(true, new KeyParameter(Buffer, 0, (cipherKeySize / 8)));
c_text_length = cipher.GetOutputSize(inLen);
byte[] tmp = new byte[c_text_length];
int len = cipher.ProcessBytes(input, inOff, inLen, tmp, 0);
len += cipher.DoFinal(tmp, len);
C = new byte[len + mac.GetMacSize()];
c_text_length = len;
Array.Copy(tmp, 0, C, 0, len);
macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8));
}
byte[] macIV = param.GetEncodingV();
mac.Init(macKey);
mac.BlockUpdate(C, 0, c_text_length);
mac.BlockUpdate(macIV, 0, macIV.Length);
//
// return the message and it's MAC
//
mac.DoFinal(C, c_text_length);
return C;
}
private byte[] GenerateKdfBytes(
KdfParameters kParam,
int length)
{
byte[] buf = new byte[length];
kdf.Init(kParam);
kdf.GenerateBytes(buf, 0, buf.Length);
return buf;
}
public virtual byte[] ProcessBlock(
byte[] input,
int inOff,
int inLen)
{
agree.Init(privParam);
BigInteger z = agree.CalculateAgreement(pubParam);
byte[] zBytes = BigIntegers.AsUnsignedByteArray(agree.GetFieldSize(), z);
try
{
return forEncryption
? EncryptBlock(input, inOff, inLen, zBytes)
: DecryptBlock(input, inOff, inLen, zBytes);
}
finally
{
Array.Clear(zBytes, 0, zBytes.Length);
}
}
}
}
#pragma warning restore
#endif