package org.bouncycastle.crypto.tls; import com.google.common.primitives.UnsignedBytes; import java.io.IOException; import java.io.OutputStream; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.encodings.PKCS1Encoding; import org.bouncycastle.crypto.engines.RSABlindedEngine; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.bouncycastle.util.Arrays; /* loaded from: classes6.dex */ public class TlsRSAUtils { public static byte[] safeDecryptPreMasterSecret(TlsContext tlsContext, RSAKeyParameters rSAKeyParameters, byte[] bArr) { ProtocolVersion clientVersion = tlsContext.getClientVersion(); byte[] bArr2 = new byte[48]; tlsContext.getSecureRandom().nextBytes(bArr2); byte[] clone = Arrays.clone(bArr2); try { PKCS1Encoding pKCS1Encoding = new PKCS1Encoding(new RSABlindedEngine(), bArr2); pKCS1Encoding.init(false, new ParametersWithRandom(rSAKeyParameters, tlsContext.getSecureRandom())); clone = pKCS1Encoding.processBlock(bArr, 0, bArr.length); } catch (Exception unused) { } int majorVersion = (clientVersion.getMajorVersion() ^ (clone[0] & UnsignedBytes.MAX_VALUE)) | (clientVersion.getMinorVersion() ^ (clone[1] & UnsignedBytes.MAX_VALUE)); int i = majorVersion | (majorVersion >> 1); int i2 = i | (i >> 2); int i3 = ~(((i2 | (i2 >> 4)) & 1) - 1); for (int i4 = 0; i4 < 48; i4++) { clone[i4] = (byte) ((clone[i4] & (~i3)) | (bArr2[i4] & i3)); } return clone; } public static byte[] generateEncryptedPreMasterSecret(TlsContext tlsContext, RSAKeyParameters rSAKeyParameters, OutputStream outputStream) throws IOException { byte[] bArr = new byte[48]; tlsContext.getSecureRandom().nextBytes(bArr); TlsUtils.writeVersion(tlsContext.getClientVersion(), bArr, 0); PKCS1Encoding pKCS1Encoding = new PKCS1Encoding(new RSABlindedEngine()); pKCS1Encoding.init(true, new ParametersWithRandom(rSAKeyParameters, tlsContext.getSecureRandom())); try { byte[] processBlock = pKCS1Encoding.processBlock(bArr, 0, 48); if (TlsUtils.isSSL(tlsContext)) { outputStream.write(processBlock); } else { TlsUtils.writeOpaque16(processBlock, outputStream); } return bArr; } catch (InvalidCipherTextException e) { throw new TlsFatalAlert((short) 80, e); } } }