下面列出了java.security.spec.InvalidParameterSpecException#java.security.Key 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* DES算法,加密
* @param data 待加密字符串
* @param key 加密私钥,长度不能够小于8位
* @return 加密后的字节数组,一般结合Base64编码使用
* @throws Exception
*/
public static String encode(String key, String data) {
if (data == null)
return null;
try {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// key的长度不能够小于8位字节
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
byte[] bytes = cipher.doFinal(data.getBytes());
return byte2String(bytes);
} catch (Exception e) {
e.printStackTrace();
return data;
}
}
/** @inheritDoc */
protected void engineInitSign(Key privateKey) throws XMLSignatureException {
if (!(privateKey instanceof PrivateKey)) {
String supplied = privateKey.getClass().getName();
String needed = PrivateKey.class.getName();
Object exArgs[] = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
this.signatureAlgorithm.initSign((PrivateKey) privateKey);
} catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/**
* Wrap a key.
*
* @param key the key to be wrapped.
*
* @return the wrapped key.
*
* @exception IllegalBlockSizeException if this cipher is a block
* cipher, no padding has been requested, and the length of the
* encoding of the key to be wrapped is not a
* multiple of the block size.
*
* @exception InvalidKeyException if it is impossible or unsafe to
* wrap the key with this cipher (e.g., a hardware protected key is
* being passed to a software only cipher).
*/
protected final byte[] engineWrap(Key key)
throws IllegalBlockSizeException, InvalidKeyException
{
byte[] result = null;
try {
byte[] encodedKey = key.getEncoded();
if ((encodedKey == null) || (encodedKey.length == 0)) {
throw new InvalidKeyException("Cannot get an encoding of " +
"the key to be wrapped");
}
result = engineDoFinal(encodedKey, 0, encodedKey.length);
} catch (BadPaddingException e) {
// Should never happen
}
return result;
}
public KeyStoreLoader load() throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(getClass().getClassLoader().getResourceAsStream("example-keystore.pfx"), PASSWORD);
Key serverPrivateKey = keyStore.getKey(SERVER_ALIAS, PASSWORD);
if (serverPrivateKey instanceof PrivateKey) {
serverCertificate = (X509Certificate) keyStore.getCertificate(SERVER_ALIAS);
PublicKey serverPublicKey = serverCertificate.getPublicKey();
serverKeyPair = new KeyPair(serverPublicKey, (PrivateKey) serverPrivateKey);
}
Key clientPrivateKey = keyStore.getKey(CLIENT_ALIAS, PASSWORD);
if (clientPrivateKey instanceof PrivateKey) {
clientCertificate = (X509Certificate) keyStore.getCertificate(CLIENT_ALIAS);
PublicKey clientPublicKey = clientCertificate.getPublicKey();
clientKeyPair = new KeyPair(clientPublicKey, (PrivateKey) clientPrivateKey);
}
return this;
}
/**
* Method engineInitSign
*
* @param secretKey
* @throws XMLSignatureException
*/
protected void engineInitSign(Key secretKey) throws XMLSignatureException {
if (!(secretKey instanceof SecretKey)) {
String supplied = secretKey.getClass().getName();
String needed = SecretKey.class.getName();
Object exArgs[] = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
this.macAlgorithm.init(secretKey);
} catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/**
* Encrypts the given str with AES. The password is first converted using SHA-256.
* @param password
* @param str
* @return The base64 encoded result (url safe).
*/
public static String encrypt(final String password, final String data)
{
initialize();
try {
// AES is sometimes not part of Java, therefore use bouncy castle provider:
final Cipher cipher = Cipher.getInstance(CRYPTO_ALGORITHM);
final byte[] keyValue = getPassword(password);
final Key key = new SecretKeySpec(keyValue, "AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
final byte[] encVal = cipher.doFinal(data.getBytes("UTF-8"));
final String encryptedValue = Base64.encodeBase64URLSafeString(encVal);
return encryptedValue;
} catch (final Exception ex) {
log.error("Exception encountered while trying to encrypt with Algorithm 'AES' and the given password: " + ex.getMessage(), ex);
return null;
}
}
/**
* 加密
*
* @param data
* 待加密数据
* @param key
* 密钥
*
* @return byte[] 加密数据
*
* @throws Exception
*/
public static byte[] encrypt(byte[] data, byte[] key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
// 还原密钥
Key k = toKey(key);
/*
* 实例化 使用PKCS7Padding填充方式,按如下方式实现 Cipher.getInstance(CIPHER_ALGORITHM,
* "BC");
*/
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
// 初始化,设置为加密模式
cipher.init(Cipher.ENCRYPT_MODE, k);
// 执行操作
return cipher.doFinal(data);
}
/** @inheritDoc */
protected void engineInitSign(Key privateKey) throws XMLSignatureException {
if (!(privateKey instanceof PrivateKey)) {
String supplied = privateKey.getClass().getName();
String needed = PrivateKey.class.getName();
Object exArgs[] = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
this.signatureAlgorithm.initSign((PrivateKey) privateKey);
} catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/**
* Seals the given cleartext key, using the password provided at
* construction time
*/
SealedObject seal(Key key)
throws Exception
{
// create a random salt (8 bytes)
byte[] salt = new byte[8];
SunJCE.getRandom().nextBytes(salt);
// create PBE parameters from salt and iteration count
PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);
// create PBE key from password
PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
pbeKeySpec.clearPassword();
// seal key
Cipher cipher;
PBEWithMD5AndTripleDESCipher cipherSpi;
cipherSpi = new PBEWithMD5AndTripleDESCipher();
cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
"PBEWithMD5AndTripleDES");
cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
return new SealedObjectForKeyProtector(key, cipher);
}
public boolean verifyMac(Key symmetricKey) {
final String algorithm = algorithm();
try {
if ("HS256".equals(algorithm)) {
return verifyMac(Mac.getInstance("HmacSHA256"), symmetricKey);
} else if ("HS384".equals(algorithm)) {
return verifyMac(Mac.getInstance("HmacSHA384"), symmetricKey);
} else if ("HS512".equals(algorithm)) {
return verifyMac(Mac.getInstance("HmacSHA512"), symmetricKey);
} else {
return false;
}
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
/**
* 根据PBE密码生成一把密钥
*
* @param password
* 生成密钥时所使用的密码
* @return Key PBE算法密钥
* */
private static Key getPBEKey(String password) {
// 实例化使用的算法
SecretKeyFactory keyFactory;
SecretKey secretKey = null;
try {
keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
// 设置PBE密钥参数
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
// 生成密钥
secretKey = keyFactory.generateSecret(keySpec);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return secretKey;
}
/**
* Changes a key password.
*/
private void doChangeKeyPasswd(String alias) throws Exception
{
if (alias == null) {
alias = keyAlias;
}
Pair<Key,char[]> objs = recoverKey(alias, storePass, keyPass);
Key privKey = objs.fst;
if (keyPass == null) {
keyPass = objs.snd;
}
if (keyPassNew == null) {
MessageFormat form = new MessageFormat
(rb.getString("key.password.for.alias."));
Object[] source = {alias};
keyPassNew = getNewPasswd(form.format(source), keyPass);
}
keyStore.setKeyEntry(alias, privKey, keyPassNew,
keyStore.getCertificateChain(alias));
}
/**
* Test method for {@link EncryptionServiceImpl#decrypt(byte[])}.
*
* @throws Exception if an error occurred
*/
@Test
public void testDecrypt(@Mocked final Key key, @Mocked final Cipher cipher)
throws Exception {
final String toDecrypt = "ADEF0985C";
EncryptionServiceImpl asymetricCrypting = new EncryptionServiceImpl("alias", null, key);
asymetricCrypting.decrypt(toDecrypt.getBytes());
new Verifications() {
{
cipher.doFinal(toDecrypt.getBytes());
times = 1;
}
};
}
@Override
public boolean permits(Set<CryptoPrimitive> primitives, Key key) {
boolean permitted = true;
if (peerAlgConstraints != null) {
permitted = peerAlgConstraints.permits(primitives, key);
}
if (permitted && userAlgConstraints != null) {
permitted = userAlgConstraints.permits(primitives, key);
}
if (permitted) {
permitted = tlsDisabledAlgConstraints.permits(primitives, key);
}
if (permitted && enabledX509DisabledAlgConstraints) {
permitted = x509DisabledAlgConstraints.permits(primitives, key);
}
return permitted;
}
static final Key constructKey(byte[] encoding, String keyAlgorithm,
int keyType)
throws InvalidKeyException, NoSuchAlgorithmException {
Key result = null;
switch (keyType) {
case Cipher.SECRET_KEY:
result = ConstructKeys.constructSecretKey(encoding,
keyAlgorithm);
break;
case Cipher.PRIVATE_KEY:
result = ConstructKeys.constructPrivateKey(encoding,
keyAlgorithm);
break;
case Cipher.PUBLIC_KEY:
result = ConstructKeys.constructPublicKey(encoding,
keyAlgorithm);
break;
}
return result;
}
private static String createToken(Key key, JsonObject jsonClaims) {
JwtClaims claims = new JwtClaims();
claims.setSubject(jsonClaims.toString());
claims.setIssuedAtToNow();
claims.setExpirationTime(NumericDate.fromSeconds(NumericDate.now().getValue() + JWT_TOKEN_EXPIRES_TIME));
JsonWebSignature jws = new JsonWebSignature();
jws.setDoKeyValidation(false);
jws.setPayload(claims.toJson());
jws.setKey(key);
jws.setAlgorithmHeaderValue(ALG);
try {
return jws.getCompactSerialization();
} catch (JoseException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
return null;
}
static Key getSigningKeyFromConfig(String kid) {
String keyLocation = JwtBuildUtils.getConfigProperty("smallrye.jwt.sign.key-location", String.class);
if (keyLocation != null) {
try {
return KeyUtils.readSigningKey(keyLocation, kid);
} catch (Exception ex) {
throw ImplMessages.msg.signingKeyCanNotBeLoadedFromLocation(keyLocation);
}
} else {
throw ImplMessages.msg.signKeyLocationNotConfigured();
}
}
private Key getPrivateKey(String tenantDomain, int tenantId) throws IdentityOAuth2Exception {
if (tenantDomain == null) {
tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
}
if (tenantId == 0) {
tenantId = OAuth2Util.getTenantId(tenantDomain);
}
Key privateKey = null;
if (!(privateKeys.containsKey(tenantId))) {
// get tenant's key store manager
KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
// derive key store name
String ksName = tenantDomain.trim().replace(".", "-");
String jksName = ksName + ".jks";
// obtain private key
privateKey = tenantKSM.getPrivateKey(jksName, tenantDomain);
} else {
try {
privateKey = tenantKSM.getDefaultPrivateKey();
} catch (Exception e) {
log.error("Error while obtaining private key for super tenant", e);
}
}
if (privateKey != null) {
privateKeys.put(tenantId, privateKey);
}
} else {
privateKey = privateKeys.get(tenantId);
}
return privateKey;
}
private void run(KeyStore inputKeyStore, KeyStore outputKeyStore,
String inKeyPass, String outKeyPass) throws Exception {
Enumeration<String> e = inputKeyStore.aliases();
String alias;
while (e.hasMoreElements()) {
alias = e.nextElement();
Certificate[] certs = inputKeyStore.getCertificateChain(alias);
boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
// Test KeyStore only contain key pair entries.
if (isCertEntry == true) {
throw new RuntimeException(
"inputKeystore should not be certEntry because test"
+ " keystore only contain key pair entries"
+ " for alias:" + alias);
}
boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
Key key = null;
if (isKeyEntry) {
key = inputKeyStore.getKey(alias, inKeyPass.toCharArray());
} else {
throw new RuntimeException("Entry type unknown for alias:"
+ alias);
}
outputKeyStore.setKeyEntry(alias, key, outKeyPass.toCharArray(),
certs);
}
}
private static void doTest(String provider, String algo) throws Exception {
SecretKey key;
SecretKey keyToWrap;
// init a secret Key
KeyGenerator kg = KeyGenerator.getInstance(AES, PROVIDER);
kg.init(KEY_LENGTH);
key = kg.generateKey();
keyToWrap = kg.generateKey();
// initialization
Cipher cipher = Cipher.getInstance(algo, provider);
cipher.init(Cipher.WRAP_MODE, key);
AlgorithmParameters params = cipher.getParameters();
// wrap the key
byte[] keyWrapper = cipher.wrap(keyToWrap);
try {
// check if we can't wrap it again with the same key/IV
keyWrapper = cipher.wrap(keyToWrap);
throw new RuntimeException(
"FAILED: expected IllegalStateException hasn't "
+ "been thrown ");
} catch (IllegalStateException ise) {
System.out.println(ise.getMessage());
System.out.println("Expected exception");
}
// unwrap the key
cipher.init(Cipher.UNWRAP_MODE, key, params);
cipher.unwrap(keyWrapper, algo, Cipher.SECRET_KEY);
// check if we can unwrap second time
Key unwrapKey = cipher.unwrap(keyWrapper, algo, Cipher.SECRET_KEY);
if (!Arrays.equals(keyToWrap.getEncoded(), unwrapKey.getEncoded())) {
throw new RuntimeException(
"FAILED: original and unwrapped keys are not equal");
}
}
public Key engineGetKey(
String alias,
char[] password)
throws NoSuchAlgorithmException, UnrecoverableKeyException
{
if (alias == null)
{
throw new IllegalArgumentException("null alias passed to getKey.");
}
return (Key)keys.get(alias);
}
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;
}
@Override
public void checkKeyType(Key key) throws InvalidKeyException {
System.err.println("Checking key of type " + key.getClass().getName());
if (!(key instanceof MockKey2)) {
throw new InvalidKeyException("Must be MockKey2!");
}
}
/**
* Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param secretKey
* @throws XMLSignatureException
*/
protected void engineInitVerify(Key secretKey) throws XMLSignatureException {
if (!(secretKey instanceof SecretKey)) {
String supplied = secretKey.getClass().getName();
String needed = SecretKey.class.getName();
Object exArgs[] = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
this.macAlgorithm.init(secretKey);
} catch (InvalidKeyException ex) {
// reinstantiate Mac object to work around bug in JDK
// see: http://bugs.sun.com/view_bug.do?bug_id=4953555
Mac mac = this.macAlgorithm;
try {
this.macAlgorithm = Mac.getInstance(macAlgorithm.getAlgorithm());
} catch (Exception e) {
// this shouldn't occur, but if it does, restore previous Mac
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Mac:" + e);
}
this.macAlgorithm = mac;
}
throw new XMLSignatureException("empty", ex);
}
}
@Test
public void testSessionKeyEncryptionDecryption() throws Exception {
Key key = CertificateGenEncryptUtil.generateSingleKey();
KeyPair kp = CertificateGenEncryptUtil.generateKeyPair();
Key privateKey = kp.getPrivate();
byte[] encryptedKey = CertificateGenEncryptUtil.encodeKeyForTransmission( privateKey, key );
Key key1 = CertificateGenEncryptUtil.decodeTransmittedKey( kp.getPublic().getEncoded(), encryptedKey, false );
assertTrue( key.equals( key1 ) );
}
public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose,
AlgorithmMethod method, XMLCryptoContext context)
throws KeySelectorException {
return new KeySelectorResult() {
public Key getKey() {
return key;
}
};
}
private Key generateKey() {
try {
KeyGenerator kgen = KeyGenerator.getInstance(CIPHER_ALGORITHM);
kgen.init(128, new SecureRandom());
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
return new SecretKeySpec(enCodeFormat, CIPHER_ALGORITHM);
} catch (Exception e) {
LOG.warn("Cannot generate key for decryption", e);
}
return null;
}
public static String createAuthToken(Key key, UserGroupMapping userGroupMapping) {
JsonObjectBuilder subjectBuilder = Json.createObjectBuilder();
subjectBuilder.add(SUBJECT_LOGIN, userGroupMapping.getLogin());
subjectBuilder.add(SUBJECT_GROUP_NAME, userGroupMapping.getGroupName());
JsonObject build = subjectBuilder.build();
return createToken(key, build);
}
private PrivateKey resolveX509SKI(XMLX509SKI x509SKI) throws XMLSecurityException, KeyStoreException {
log.log(java.util.logging.Level.FINE, "Can I resolve X509SKI?");
Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (keyStore.isKeyEntry(alias)) {
Certificate cert = keyStore.getCertificate(alias);
if (cert instanceof X509Certificate) {
XMLX509SKI certSKI = new XMLX509SKI(x509SKI.getDocument(), (X509Certificate) cert);
if (certSKI.equals(x509SKI)) {
log.log(java.util.logging.Level.FINE, "match !!! ");
try {
Key key = keyStore.getKey(alias, password);
if (key instanceof PrivateKey) {
return (PrivateKey) key;
}
} catch (Exception e) {
log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
// Keep searching
}
}
}
}
}
return null;
}
/**
* <p>
* 公钥加密
* </p>
* @param data 源数据
* @param publicKey 公钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}