-
Notifications
You must be signed in to change notification settings - Fork 282
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Rework HPKE into JCA Provider model. #1174
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
96d3768
WIP
prbprbprb b5e30f6
Some tidy-ups and fixes.
prbprbprb 644de88
Brain freeze!
prbprbprb d8aa425
Add duck typing for SPIs.
prbprbprb d90c49a
Visibility fixes.
prbprbprb 83ab130
Visibility for testing.
prbprbprb 5f20334
Go back to no-arg constructors for SPI instances.
prbprbprb fa9576b
Fixup Javadoc, licenses, code style etc.
prbprbprb 198aa1e
Put back accidentally omitted code to validate encapsulated length.
prbprbprb 4e19c58
Fix Exception type for invalid enc length.
prbprbprb 30779f3
Refactor init() methods.
prbprbprb 8d5e94d
Update key validation to throw correct exception.
prbprbprb bec9fae
Unused imports......
prbprbprb 5b9f6ce
Minor review fixes.
prbprbprb ef77017
Add duck typing for SPIs.
prbprbprb 54c687e
Resolve merge conflicts.
prbprbprb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
125 changes: 125 additions & 0 deletions
125
common/src/main/java/org/conscrypt/DuckTypedHpkeSpi.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
/* | ||
* Copyright (C) 2023 The Android Open Source Project | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License | ||
*/ | ||
|
||
package org.conscrypt; | ||
|
||
import java.lang.reflect.InvocationTargetException; | ||
import java.lang.reflect.Method; | ||
import java.security.GeneralSecurityException; | ||
import java.security.InvalidKeyException; | ||
import java.security.PrivateKey; | ||
import java.security.PublicKey; | ||
import java.util.HashMap; | ||
import java.util.Map; | ||
|
||
/** | ||
* Duck typed implementation of {@link HpkeSpi}. | ||
* <p> | ||
* Will wrap any Object which implements all of the methods in HpkeSpi and delegate to them | ||
* by reflection. | ||
*/ | ||
@Internal | ||
public class DuckTypedHpkeSpi implements HpkeSpi { | ||
private final Object delegate; | ||
private final Map<String, Method> methods = new HashMap<>(); | ||
|
||
private DuckTypedHpkeSpi(Object delegate) throws NoSuchMethodException { | ||
this.delegate = delegate; | ||
|
||
Class<?> sourceClass = delegate.getClass(); | ||
for (Method targetMethod : HpkeSpi.class.getMethods()) { | ||
if (targetMethod.isSynthetic()) { | ||
continue; | ||
} | ||
|
||
Method sourceMethod = | ||
sourceClass.getMethod(targetMethod.getName(), targetMethod.getParameterTypes()); | ||
// Check that the return types match too. | ||
Class<?> sourceReturnType = sourceMethod.getReturnType(); | ||
Class<?> targetReturnType = targetMethod.getReturnType(); | ||
if (!targetReturnType.isAssignableFrom(sourceReturnType)) { | ||
throw new NoSuchMethodException(sourceMethod + " return value (" + sourceReturnType | ||
+ ") incompatible with target return value (" + targetReturnType + ")"); | ||
} | ||
methods.put(sourceMethod.getName(), sourceMethod); | ||
} | ||
} | ||
|
||
public static DuckTypedHpkeSpi newInstance(Object delegate) { | ||
try { | ||
return new DuckTypedHpkeSpi(delegate); | ||
} catch (Exception ignored) { | ||
return null; | ||
} | ||
} | ||
|
||
private Object invoke(String methodName, Object... args) { | ||
Method method = methods.get(methodName); | ||
if (method == null) { | ||
throw new IllegalStateException("DuckTypedHpkSpi internal error"); | ||
} | ||
try { | ||
return method.invoke(delegate, args); | ||
} catch (InvocationTargetException | IllegalAccessException e) { | ||
throw new IllegalStateException("DuckTypedHpkSpi internal error", e); | ||
} | ||
} | ||
|
||
// Visible for testing | ||
public Object getDelegate() { | ||
return delegate; | ||
} | ||
|
||
@Override | ||
public void engineInitSender( | ||
PublicKey recipientKey, byte[] info, PrivateKey senderKey, byte[] psk, byte[] psk_id) | ||
throws InvalidKeyException { | ||
invoke("engineInitSender", recipientKey, info, senderKey, psk, psk_id); | ||
} | ||
|
||
@Override | ||
public void engineInitSenderForTesting(PublicKey recipientKey, byte[] info, PrivateKey senderKey, | ||
byte[] psk, byte[] psk_id, byte[] sKe) throws InvalidKeyException { | ||
invoke("engineInitSenderForTesting", | ||
recipientKey, info, senderKey, psk, psk_id, sKe); | ||
} | ||
|
||
@Override | ||
public void engineInitRecipient(byte[] encapsulated, PrivateKey key, byte[] info, | ||
PublicKey senderKey, byte[] psk, byte[] psk_id) throws InvalidKeyException { | ||
invoke("engineInitRecipient", encapsulated, key, info, senderKey, psk, psk_id); | ||
} | ||
|
||
@Override | ||
public byte[] engineSeal(byte[] plaintext, byte[] aad) { | ||
return (byte[]) invoke("engineSeal", plaintext, aad); | ||
} | ||
|
||
@Override | ||
public byte[] engineExport(int length, byte[] exporterContext) { | ||
return (byte[]) invoke("engineExport", length, exporterContext); | ||
} | ||
|
||
@Override | ||
public byte[] engineOpen(byte[] ciphertext, byte[] aad) throws GeneralSecurityException { | ||
return (byte[]) invoke("engineOpen", ciphertext, aad); | ||
} | ||
|
||
@Override | ||
public byte[] getEncapsulated() { | ||
return (byte[]) invoke("getEncapsulated"); | ||
} | ||
} |
prbprbprb marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
/* | ||
* Copyright (C) 2023 The Android Open Source Project | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License | ||
*/ | ||
|
||
package org.conscrypt; | ||
|
||
import java.security.NoSuchAlgorithmException; | ||
import java.security.NoSuchProviderException; | ||
import java.security.Provider; | ||
import java.security.Security; | ||
|
||
/** | ||
* Hybrid Public Key Encryption (HPKE) sender APIs. | ||
* | ||
* @see <a href="https://www.rfc-editor.org/rfc/rfc9180.html#hpke-export">HPKE RFC 9180</a> | ||
* <p> | ||
* Base class for HPKE sender and recipient contexts. | ||
* <p> | ||
* This is the client API for HPKE usage, all operations are delegated to an implementation | ||
* class implementing {@link HpkeSpi} which is located using the JCA {@link Provider} | ||
* mechanism. | ||
* <p> | ||
* The implementation maintains the context for an HPKE exchange, including the key schedule | ||
* to use for seal and open operations. | ||
* | ||
* Secret key material based on the context may also be generated and exported as per RFC 9180. | ||
*/ | ||
public abstract class HpkeContext { | ||
protected final HpkeSpi spi; | ||
|
||
protected HpkeContext(HpkeSpi spi) { | ||
this.spi = spi; | ||
} | ||
|
||
/** | ||
* Exports secret key material from this HpkeContext as described in RFC 9180. | ||
* | ||
* @param length expected output length | ||
* @param context optional context string, may be null or empty | ||
* @return exported value | ||
* @throws IllegalArgumentException if the length is not valid for the KDF in use | ||
* @throws IllegalStateException if this HpkeContext has not been initialised | ||
* | ||
*/ | ||
public byte[] export(int length, byte[] context) { | ||
return spi.engineExport(length, context); | ||
} | ||
|
||
/** | ||
* Returns the {@link HpkeSpi} being used by this HpkeContext. | ||
* | ||
* @return the SPI | ||
*/ | ||
public HpkeSpi getSpi() { | ||
return spi; | ||
} | ||
|
||
protected static HpkeSpi findSpi(String algorithm) throws NoSuchAlgorithmException { | ||
if (algorithm == null) { | ||
// Same behaviour as Cipher.getInstance | ||
throw new NoSuchAlgorithmException("null algorithm"); | ||
} | ||
return findSpi(algorithm, findFirstProvider(algorithm)); | ||
} | ||
|
||
private static Provider findFirstProvider(String algorithm) throws NoSuchAlgorithmException { | ||
for (Provider p : Security.getProviders()) { | ||
Provider.Service service = p.getService("ConscryptHpke", algorithm); | ||
if (service != null) { | ||
return service.getProvider(); | ||
} | ||
} | ||
throw new NoSuchAlgorithmException("No Provider found for: " + algorithm); | ||
} | ||
|
||
protected static HpkeSpi findSpi(String algorithm, String providerName) throws | ||
NoSuchAlgorithmException, IllegalArgumentException, NoSuchProviderException { | ||
if (providerName == null || providerName.isEmpty()) { | ||
// Same behaviour as Cipher.getInstance | ||
throw new IllegalArgumentException("Invalid provider name"); | ||
} | ||
Provider provider = Security.getProvider(providerName); | ||
if (provider == null) { | ||
throw new NoSuchProviderException("Unknown Provider: " + providerName); | ||
} | ||
return findSpi(algorithm, provider); | ||
} | ||
|
||
protected static HpkeSpi findSpi(String algorithm, Provider provider) throws | ||
NoSuchAlgorithmException, IllegalArgumentException { | ||
if (provider == null) { | ||
throw new IllegalArgumentException("null Provider"); | ||
} | ||
Provider.Service service = provider.getService("ConscryptHpke", algorithm); | ||
if (service == null) { | ||
throw new NoSuchAlgorithmException("Unknown algorithm"); | ||
} | ||
Object instance = service.newInstance(null); | ||
HpkeSpi spi = (instance instanceof HpkeSpi) ? (HpkeSpi) instance | ||
: DuckTypedHpkeSpi.newInstance(instance); | ||
if (spi != null) { | ||
return spi; | ||
} | ||
throw new IllegalStateException( | ||
String.format("Provider %s is providing incorrect instances", provider.getName())); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: I don't know how likely it is, but if a method from
HpkeSpi
is overloaded, this will be overridden. Should we check thatput
returns null?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think that's covered, as we do
and (as I found during refactorings :) that won't match unless the parameters match exactly.
I am a bit concerned about differing checked exceptions though....
Also, I'm going to move that
getClass()
outside the loop though seeing as there's another fix needs to go in