下面列出了java.security.Key#getAlgorithm ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static JsonWebSignature hmacSHA(Key symmetricKey, Value unprotectedHeader,
Value protectedHeader, Data payloadData) {
final String algorithm = symmetricKey.getAlgorithm();
final Mac mac;
try {
if ("HmacSHA256".equals(algorithm)) {
protectedHeader = protectedHeader.updatedSlot("alg", "HS256");
mac = Mac.getInstance("HmacSHA256");
} else if ("HmacSHA384".equals(algorithm)) {
protectedHeader = protectedHeader.updatedSlot("alg", "HS384");
mac = Mac.getInstance("HmacSHA384");
} else if ("HmacSHA512".equals(algorithm)) {
protectedHeader = protectedHeader.updatedSlot("alg", "HS512");
mac = Mac.getInstance("HmacSHA512");
} else {
throw new IllegalArgumentException("unsupported key size");
}
return hmacSHA(mac, symmetricKey, unprotectedHeader, protectedHeader, payloadData);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public static void validateAesWrappingKey(Key managementKey, String joseAlg, int expectedKeyByteLength) throws InvalidKeyException
{
KeyValidationSupport.notNull(managementKey);
String alg = managementKey.getAlgorithm();
if (!AesKey.ALGORITHM.equals(alg))
{
throw new InvalidKeyException("Invalid key for JWE " + joseAlg + ", expected an "
+ AesKey.ALGORITHM+ " key but an " + alg + " key was provided.");
}
if (managementKey.getEncoded() != null)
{
int managementKeyByteLength = managementKey.getEncoded().length;
if (managementKeyByteLength != expectedKeyByteLength)
{
throw new InvalidKeyException("Invalid key for JWE " + joseAlg + ", expected a "
+ ByteUtil.bitLength(expectedKeyByteLength)+ " bit key but a "
+ ByteUtil.bitLength(managementKeyByteLength) + " bit key was provided.");
}
}
}
private String getSignatureAlgorithm(String hash) throws Exception {
String signatureAlgorithm;
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream fileIn = new FileInputStream(config.mSignatureFile);
keyStore.load(fileIn, config.mStorePass.toCharArray());
Key key = keyStore.getKey(config.mStoreAlias, config.mKeyPass.toCharArray());
if (key == null) {
throw new RuntimeException("Can't get private key, please check if storepass storealias and keypass are correct");
}
String keyAlgorithm = key.getAlgorithm();
hash = formatHashAlgorithName(hash);
if (keyAlgorithm.equalsIgnoreCase("DSA")) {
keyAlgorithm = "DSA";
} else if (keyAlgorithm.equalsIgnoreCase("RSA")) {
keyAlgorithm = "RSA";
} else if (keyAlgorithm.equalsIgnoreCase("EC")) {
keyAlgorithm = "ECDSA";
} else {
throw new RuntimeException("private key is not a DSA or RSA key");
}
signatureAlgorithm = String.format("%swith%s", hash, keyAlgorithm);
return signatureAlgorithm;
}
@Test
public void simple() throws GeneralSecurityException {
DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
Key signingKey = eMat.getSigningKey();
assertNotNull(signingKey);
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(signingKey, dMat.getVerificationKey());
String expectedEncAlg = encryptionKey.getAlgorithm() + "/"
+ (encryptionKey.getEncoded().length * 8);
String expectedSigAlg = signingKey.getAlgorithm() + "/"
+ (signingKey.getEncoded().length * 8);
Map<String, String> kmsCtx = kms.getSingleEc();
assertEquals(expectedEncAlg,
kmsCtx.get("*" + WrappedRawMaterials.CONTENT_KEY_ALGORITHM + "*"));
assertEquals(expectedSigAlg, kmsCtx.get("*amzn-ddb-sig-alg*"));
}
@Test
public void simple() {
DirectKmsMaterialsProvider prov = new DirectKmsMaterialsProvider(kms, keyId);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
Key signingKey = eMat.getSigningKey();
assertNotNull(signingKey);
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(signingKey, dMat.getVerificationKey());
String expectedEncAlg = encryptionKey.getAlgorithm() + "/"
+ (encryptionKey.getEncoded().length * 8);
String expectedSigAlg = signingKey.getAlgorithm() + "/"
+ (signingKey.getEncoded().length * 8);
Map<String, String> kmsCtx = kms.getSingleEc();
assertEquals(expectedEncAlg,
kmsCtx.get("*" + WrappedRawMaterials.CONTENT_KEY_ALGORITHM + "*"));
assertEquals(expectedSigAlg, kmsCtx.get("*amzn-ddb-sig-alg*"));
}
private HFileContext createHFileContext(Path path,
FixedFileTrailer trailer, Configuration conf) throws IOException {
HFileContextBuilder builder = new HFileContextBuilder()
.withHBaseCheckSum(true)
.withHFileName(path.getName())
.withCompression(trailer.getCompressionCodec())
.withCellComparator(trailer.createComparator(trailer.getComparatorClassName()));
// Check for any key material available
byte[] keyBytes = trailer.getEncryptionKey();
if (keyBytes != null) {
Encryption.Context cryptoContext = Encryption.newContext(conf);
Key key = EncryptionUtil.unwrapKey(conf, keyBytes);
// Use the algorithm the key wants
Cipher cipher = Encryption.getCipher(conf, key.getAlgorithm());
if (cipher == null) {
throw new IOException("Cipher '" + key.getAlgorithm() + "' is not available"
+ ", path=" + path);
}
cryptoContext.setCipher(cipher);
cryptoContext.setKey(key);
builder.withEncryptionContext(cryptoContext);
}
HFileContext context = builder.build();
return context;
}
public static Cipher initCipher(Key secretKey, KeyProperties keyProps, int mode) throws SecurityException {
try {
String algorithm = keyProps != null && keyProps.getKeyAlgo() != null
? keyProps.getKeyAlgo() : secretKey.getAlgorithm();
Cipher c = Cipher.getInstance(algorithm);
if (keyProps == null || keyProps.getAlgoSpec() == null && keyProps.getSecureRandom() == null) {
c.init(mode, secretKey);
} else {
AlgorithmParameterSpec algoSpec = keyProps.getAlgoSpec();
SecureRandom random = keyProps.getSecureRandom();
if (algoSpec == null) {
c.init(mode, secretKey, random);
} else if (random == null) {
c.init(mode, secretKey, algoSpec);
} else {
c.init(mode, secretKey, algoSpec, random);
}
}
if (keyProps != null && keyProps.getAdditionalData() != null) {
c.updateAAD(keyProps.getAdditionalData());
}
return c;
} catch (Exception ex) {
throw new SecurityException(ex);
}
}
/**
* @param kek
* the key encrypting key, which is either an AES key or a public
* key
*/
String getKeyWrapAlgorithm(Key kek) {
String algorithm = kek.getAlgorithm();
if (COSCryptoScheme.AES.equals(algorithm)) {
return AESWrap;
}
if (COSCryptoScheme.RSA.equals(algorithm)) {
if (CryptoRuntime.isRsaKeyWrapAvailable())
return RSA_ECB_OAEPWithSHA256AndMGF1Padding;
}
throw new IllegalArgumentException("Unsupported key wrap algorithm " + algorithm);
}
/**
* Used to return the default signing algorithm for the given key type
*
* @param key
* @return
*/
public static String getSigningAlgorithm(final Key key) {
final String defaultAlgorithm;
if (key.getAlgorithm().equals("ECDSA")) {
defaultAlgorithm = CommonConfiguration.EC_SIGNATURE_ALGORITHM;
} else if (key.getAlgorithm().equals("EdDSA")) {
defaultAlgorithm = CommonConfiguration.ED_SIGNATURE_ALGORITHM;
} else if (key.getAlgorithm().equals("RSA")) {
defaultAlgorithm = CommonConfiguration.RSA_SIGNATURE_ALGORITHM;
} else {
throw new RuntimeException("Unknown key type: " + key.getAlgorithm());
}
return defaultAlgorithm;
}
/**
* @param kek
* the key encrypting key, which is either an AES key or a public
* key
*/
String getKeyWrapAlgorithm(Key kek) {
String algorithm = kek.getAlgorithm();
if (COSCryptoScheme.AES.equals(algorithm)) {
return AESWrap;
}
if (COSCryptoScheme.RSA.equals(algorithm)) {
if (CryptoRuntime.isRsaKeyWrapAvailable())
return RSA_ECB_OAEPWithSHA256AndMGF1Padding;
}
throw new IllegalArgumentException("Unsupported key wrap algorithm " + algorithm);
}
/** {@inheritDoc} */
public String getSignatureAlgorithmURI(Credential credential) {
Key key = SecurityHelper.extractSigningKey(credential);
if (key == null) {
log.debug("Could not extract signing key from credential, unable to map to algorithm URI");
return null;
} else if (key.getAlgorithm() == null) {
log.debug("Signing key algorithm value was not available, unable to map to algorithm URI");
return null;
}
return getSignatureAlgorithmURI(key.getAlgorithm());
}
/** {@inheritDoc} */
public String getDataEncryptionAlgorithmURI(Credential credential) {
Key key = SecurityHelper.extractEncryptionKey(credential);
if (key == null) {
log.debug("Could not extract data encryption key from credential, unable to map to algorithm URI");
return null;
} else if (key.getAlgorithm() == null){
log.debug("Data encryption key algorithm value was not available, unable to map to algorithm URI");
return null;
}
Integer length = SecurityHelper.getKeyLength(key);
return getDataEncryptionAlgorithmURI(key.getAlgorithm(), length);
}
/** {@inheritDoc} */
public String getKeyTransportEncryptionAlgorithmURI(Credential credential, String wrappedKeyAlgorithm) {
Key key = SecurityHelper.extractEncryptionKey(credential);
if (key == null) {
log.debug("Could not extract key transport encryption key from credential, unable to map to algorithm URI");
return null;
} else if (key.getAlgorithm() == null){
log.debug("Key transport encryption key algorithm value was not available, unable to map to algorithm URI");
return null;
}
Integer length = SecurityHelper.getKeyLength(key);
return getKeyTransportEncryptionAlgorithmURI(key.getAlgorithm(), length, wrappedKeyAlgorithm);
}
private String fullDisplayAlgName(Key key) {
String result = key.getAlgorithm();
if (key instanceof ECKey) {
ECParameterSpec paramSpec = ((ECKey) key).getParams();
if (paramSpec instanceof NamedCurve) {
result += " (" + paramSpec.toString().split(" ")[0] + ")";
}
}
return result;
}
/**
* @param kek
* the key encrypting key, which is either an AES key or a public
* key
*/
String getKeyWrapAlgorithm(Key kek) {
String algorithm = kek.getAlgorithm();
if (S3CryptoScheme.AES.equals(algorithm)) {
return AESWrap;
}
if (S3CryptoScheme.RSA.equals(algorithm)) {
if (CryptoRuntime.isRsaKeyWrapAvailable())
return RSA_ECB_OAEPWithSHA256AndMGF1Padding;
}
return null;
}
private static SignatureAlgorithm getSignatureAlgorithm(Key key) {
switch (key.getAlgorithm()) {
case "EC":
return SignatureAlgorithm.SHA512_WITH_ECDSA;
case "RSA":
return SignatureAlgorithm.SHA512_WITH_RSA;
default:
throw new RuntimeException("Unknown Key algorithm " + key.getAlgorithm());
}
}
/**
* Helper to create an encyption context.
*
* @param conf The current configuration.
* @param family The current column descriptor.
* @return The created encryption context.
* @throws IOException if an encryption key for the column cannot be unwrapped
*/
public static Encryption.Context createEncryptionContext(Configuration conf,
ColumnFamilyDescriptor family) throws IOException {
Encryption.Context cryptoContext = Encryption.Context.NONE;
String cipherName = family.getEncryptionType();
if (cipherName != null) {
Cipher cipher;
Key key;
byte[] keyBytes = family.getEncryptionKey();
if (keyBytes != null) {
// Family provides specific key material
key = unwrapKey(conf, keyBytes);
// Use the algorithm the key wants
cipher = Encryption.getCipher(conf, key.getAlgorithm());
if (cipher == null) {
throw new RuntimeException("Cipher '" + key.getAlgorithm() + "' is not available");
}
// Fail if misconfigured
// We use the encryption type specified in the column schema as a sanity check on
// what the wrapped key is telling us
if (!cipher.getName().equalsIgnoreCase(cipherName)) {
throw new RuntimeException("Encryption for family '" + family.getNameAsString()
+ "' configured with type '" + cipherName + "' but key specifies algorithm '"
+ cipher.getName() + "'");
}
} else {
// Family does not provide key material, create a random key
cipher = Encryption.getCipher(conf, cipherName);
if (cipher == null) {
throw new RuntimeException("Cipher '" + cipherName + "' is not available");
}
key = cipher.getRandomKey();
}
cryptoContext = Encryption.newContext(conf);
cryptoContext.setCipher(cipher);
cryptoContext.setKey(key);
}
return cryptoContext;
}
public SignatureKeyImpl(Key publicKey) {
this(publicKey.getEncoded(), publicKey.getAlgorithm(), publicKey.getFormat());
}
/**
*
* Retrieve the Crypto Context. This is borrowed from the DefaultCompactor logic.
*
* @return
* @throws IOException
*/
public Encryption.Context getCryptoContext() throws IOException {
// Crypto context for new store files
String cipherName = store.getColumnFamilyDescriptor().getEncryptionType();
if (cipherName != null) {
Cipher cipher;
Key key;
byte[] keyBytes = store.getColumnFamilyDescriptor().getEncryptionKey();
if (keyBytes != null) {
// Family provides specific key material
String masterKeyName = conf.get(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY,
User.getCurrent().getShortName());
try {
// First try the master key
key = EncryptionUtil.unwrapKey(conf, masterKeyName, keyBytes);
} catch (KeyException e) {
// If the current master key fails to unwrap, try the alternate, if
// one is configured
if (LOG.isDebugEnabled()) {
LOG.debug("Unable to unwrap key with current master key '" + masterKeyName + "'");
}
String alternateKeyName =
conf.get(HConstants.CRYPTO_MASTERKEY_ALTERNATE_NAME_CONF_KEY);
if (alternateKeyName != null) {
try {
key = EncryptionUtil.unwrapKey(conf, alternateKeyName, keyBytes);
} catch (KeyException ex) {
throw new IOException(ex);
}
} else {
throw new IOException(e);
}
}
// Use the algorithm the key wants
cipher = Encryption.getCipher(conf, key.getAlgorithm());
if (cipher == null) {
throw new RuntimeException("Cipher '" + key.getAlgorithm() + "' is not available");
}
// Fail if misconfigured
// We use the encryption type specified in the column schema as a sanity check on
// what the wrapped key is telling us
if (!cipher.getName().equalsIgnoreCase(cipherName)) {
throw new RuntimeException("Encryption for family '" + store.getColumnFamilyDescriptor().getNameAsString() +
"' configured with type '" + cipherName +
"' but key specifies algorithm '" + cipher.getName() + "'");
}
} else {
// Family does not provide key material, create a random key
cipher = Encryption.getCipher(conf, cipherName);
if (cipher == null) {
throw new RuntimeException("Cipher '" + cipherName + "' is not available");
}
key = cipher.getRandomKey();
}
Encryption.Context cryptoContext = Encryption.newContext(conf);
cryptoContext.setCipher(cipher);
cryptoContext.setKey(key);
return cryptoContext;
} else
return Encryption.Context.NONE;
}