java类java.security.Key的实例源码

LoginCipher.java 文件源码 项目:netty-socketio-demo 阅读 40 收藏 0 点赞 0 评论 0
/** 加载key */
public static Key loadKey(String name) {
    try {
        URL url = ResouceUtil.findResource(name, LoginCipher.class);
        InputStream in = url.openStream();
        ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));

        try {
            return (Key) oin.readObject();
        } finally {
            oin.close();
        }
    } catch (Exception e) {
        logger.error("#login_cipher key " + name + " load error! " + e, e);
        return null;
    }
}
KeyFactorySpi.java 文件源码 项目:ipack 阅读 41 收藏 0 点赞 0 评论 0
protected Key engineTranslateKey(
    Key key)
    throws InvalidKeyException
{
    if (key instanceof DHPublicKey)
    {
        return new BCElGamalPublicKey((DHPublicKey)key);
    }
    else if (key instanceof DHPrivateKey)
    {
        return new BCElGamalPrivateKey((DHPrivateKey)key);
    }
    else if (key instanceof ElGamalPublicKey)
    {
        return new BCElGamalPublicKey((ElGamalPublicKey)key);
    }
    else if (key instanceof ElGamalPrivateKey)
    {
        return new BCElGamalPrivateKey((ElGamalPrivateKey)key);
    }

    throw new InvalidKeyException("key type unknown");
}
RSACipher.java 文件源码 项目:OpenJSharp 阅读 36 收藏 0 点赞 0 评论 0
protected byte[] engineWrap(Key key) throws InvalidKeyException,
        IllegalBlockSizeException {
    byte[] encoded = key.getEncoded(); // TODO - unextractable key
    if ((encoded == null) || (encoded.length == 0)) {
        throw new InvalidKeyException("Could not obtain encoded key");
    }
    if (encoded.length > buffer.length) {
        throw new InvalidKeyException("Key is too long for wrapping");
    }
    update(encoded, 0, encoded.length);
    try {
        return doFinal();
    } catch (BadPaddingException e) {
        // should not occur
        throw new InvalidKeyException("Wrapping failed", e);
    }
}
IntegrityHmac.java 文件源码 项目:openjdk-jdk10 阅读 36 收藏 0 点赞 0 评论 0
/**
 * 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);
    }
}
CryptManager.java 文件源码 项目:BaseClient 阅读 56 收藏 0 点赞 0 评论 0
/**
 * Creates the Cipher Instance.
 */
private static Cipher createTheCipherInstance(int opMode, String transformation, Key key)
{
    try
    {
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(opMode, key);
        return cipher;
    }
    catch (InvalidKeyException invalidkeyexception)
    {
        invalidkeyexception.printStackTrace();
    }
    catch (NoSuchAlgorithmException nosuchalgorithmexception)
    {
        nosuchalgorithmexception.printStackTrace();
    }
    catch (NoSuchPaddingException nosuchpaddingexception)
    {
        nosuchpaddingexception.printStackTrace();
    }

    LOGGER.error("Cipher creation failed!");
    return null;
}
DisabledAlgorithmConstraints.java 文件源码 项目:openjdk-jdk10 阅读 49 收藏 0 点赞 0 评论 0
private boolean permitsImpl(Key key) {
    // Verify this constraint is for this public key algorithm
    if (algorithm.compareToIgnoreCase(key.getAlgorithm()) != 0) {
        return true;
    }

    int size = KeyUtil.getKeySize(key);
    if (size == 0) {
        return false;    // we don't allow any key of size 0.
    } else if (size > 0) {
        return !((size < minSize) || (size > maxSize) ||
            (prohibitedSize == size));
    }   // Otherwise, the key size is not accessible. Conservatively,
        // please don't disable such keys.

    return true;
}
KeyFactorySpi.java 文件源码 项目:ipack 阅读 31 收藏 0 点赞 0 评论 0
protected Key engineTranslateKey(
    Key key)
    throws InvalidKeyException
{
    if (key instanceof RSAPublicKey)
    {
        return new BCRSAPublicKey((RSAPublicKey)key);
    }
    else if (key instanceof RSAPrivateCrtKey)
    {
        return new BCRSAPrivateCrtKey((RSAPrivateCrtKey)key);
    }
    else if (key instanceof java.security.interfaces.RSAPrivateKey)
    {
        return new BCRSAPrivateKey((java.security.interfaces.RSAPrivateKey)key);
    }

    throw new InvalidKeyException("key type unknown");
}
ConstructKeys.java 文件源码 项目:jdk8u-jdk 阅读 38 收藏 0 点赞 0 评论 0
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;
}
EvaluableKeyAlgorithmCredentialCriteria.java 文件源码 项目:lams 阅读 48 收藏 0 点赞 0 评论 0
/** {@inheritDoc} */
public Boolean evaluate(Credential target) {
    if (target == null) {
        log.error("Credential target was null");
        return null;
    }
    Key key = getKey(target);
    if (key == null) {
        log.info("Could not evaluate criteria, credential contained no key");
        return null;
    }
    String algorithm = DatatypeHelper.safeTrimOrNullString(key.getAlgorithm());
    if (algorithm == null) {
        log.info("Could not evaluate criteria, key does not specify an algorithm via getAlgorithm()");
        return null;
    }

    Boolean result = keyAlgorithm.equals(algorithm);
    return result;
}
DefaultEncryptionServivceImpl.java 文件源码 项目:sunbird-utils 阅读 47 收藏 0 点赞 0 评论 0
/**
 * this method is used to encrypt the password.
 * 
 * @param value String password
 * @param encryption_key
 * @return encrypted password.
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
@SuppressWarnings("restriction")
public static String encrypt(String value) throws NoSuchAlgorithmException,
    NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
  encryption_key = getSalt();
  Key key = generateKey();
  Cipher c = Cipher.getInstance(ALGORITHM);
  c.init(Cipher.ENCRYPT_MODE, key);

  String valueToEnc = null;
  String eValue = value;
  for (int i = 0; i < ITERATIONS; i++) {
    valueToEnc = encryption_key + eValue;
    byte[] encValue = c.doFinal(valueToEnc.getBytes());
    eValue = new sun.misc.BASE64Encoder().encode(encValue);
  }
  return eValue;
}
SigningUtil.java 文件源码 项目:lams 阅读 32 收藏 0 点赞 0 评论 0
/**
 * Compute the signature or MAC value over the supplied input.
 * 
 * It is up to the caller to ensure that the specified algorithm ID and isMAC flag are consistent with the type of
 * signing key supplied in the signing credential.
 * 
 * @param signingCredential the credential containing the signing key
 * @param jcaAlgorithmID the Java JCA algorithm ID to use
 * @param isMAC flag indicating whether the operation to be performed is a signature or MAC computation
 * @param input the input over which to compute the signature
 * @return the computed signature or MAC value
 * @throws SecurityException throw if the computation process results in an error
 */
public static byte[] sign(Credential signingCredential, String jcaAlgorithmID, boolean isMAC, byte[] input)
        throws SecurityException {
    Logger log = getLogger();

    Key signingKey = SecurityHelper.extractSigningKey(signingCredential);
    if (signingKey == null) {
        log.error("No signing key supplied in signing credential for signature computation");
        throw new SecurityException("No signing key supplied in signing credential");
    }

    if (isMAC) {
        return signMAC(signingKey, jcaAlgorithmID, input);
    } else if (signingKey instanceof PrivateKey) {
        return sign((PrivateKey) signingKey, jcaAlgorithmID, input);
    } else {
        log.error("No PrivateKey present in signing credential for signature computation");
        throw new SecurityException("No PrivateKey supplied for signing");
    }
}
CustomKeySigner.java 文件源码 项目:mobile-store 阅读 39 收藏 0 点赞 0 评论 0
/** KeyStore-type agnostic.  This method will sign the zip file, automatically handling JKS or BKS keystores. */
public static void signZip( ZipSigner zipSigner,
                     String keystorePath,
                     char[] keystorePw,
                     String certAlias,
                     char[] certPw,
                     String signatureAlgorithm,
                     String inputZipFilename,
                     String outputZipFilename)
    throws Exception
{
    zipSigner.issueLoadingCertAndKeysProgressEvent();
    KeyStore keystore = KeyStoreFileManager.loadKeyStore( keystorePath, keystorePw);
    Certificate cert = keystore.getCertificate(certAlias);
    X509Certificate publicKey = (X509Certificate)cert;
    Key key = keystore.getKey(certAlias, certPw);
    PrivateKey privateKey = (PrivateKey)key;

    zipSigner.setKeys( "custom", publicKey, privateKey, signatureAlgorithm, null);
    zipSigner.signZip( inputZipFilename, outputZipFilename);
}
KeyGenerationTester.java 文件源码 项目:shared-ledger-simulator 阅读 37 收藏 0 点赞 0 评论 0
public static void main(String[] args){
    KeyPairGenerator kpg = null;
    try{
        kpg = KeyPairGenerator.getInstance("RSA");
    } catch(NoSuchAlgorithmException ex){
        log.error(ex, ex);
        throw new RuntimeException(ex);
    }
    kpg.initialize(1024);
    KeyPair keyPair = kpg.generateKeyPair();
    Key privateKey = keyPair.getPrivate();
    Key publicKey = keyPair.getPublic();

    Base64.Encoder encoder = Base64.getEncoder();
    String privateKeyBase64Str = encoder.encodeToString(privateKey.getEncoded());
    log.info("Private key in Base64 format:\n" + privateKeyBase64Str);//it creates 1623 chars or 1620 chars

    Base64.Decoder decoder = Base64.getDecoder();
    byte[] privateKeyBytes = decoder.decode(privateKeyBase64Str);
    log.info("The private Key is " + privateKeyBytes.length + " bytes long");
    String privateKeyHex = String.format("%040x", new BigInteger(1, privateKeyBytes));
    log.info("The private key in hexadecimal digits:\n" + privateKeyHex);


    String publicKeyBase64Str = encoder.encodeToString(publicKey.getEncoded());
    log.info("Public key in Base64 format:\n" + publicKeyBase64Str);//it creates 392 chars and again 392 chars for 2048 bits
                                                                    //it creates 162 bytes for 1024 bits, an Ethereum address is 20 bytes (40 hexadecimal digits/characters long)
                                                                    //324 hexadecimal characters, and we use the last 40 as the Ethereum address
    byte[] publicKeyBytes = decoder.decode(publicKeyBase64Str);
    log.info("The public Key is " + publicKeyBytes.length + " bytes long");
    String publicKeyHex = String.format("%040x", new BigInteger(1, publicKeyBytes));
    log.info("The public key in hexadecimal digits:\n" + publicKeyHex);
}
JwtServiceImpl.java 文件源码 项目:users-service 阅读 55 收藏 0 点赞 0 评论 0
@Override
public Claims validate(JwtToken token) {
    final Key signingKey = EncryptionUtil.getPublicKey(
        env.getProperty("service.jwt.public"));

    return Jwts.parser()
        .setSigningKey(signingKey)
        .parseClaimsJws(token.getToken())
        .getBody();
}
LoginValidator.java 文件源码 项目:JungleTree 阅读 45 收藏 0 点赞 0 评论 0
private boolean validatePublicKey(JWSObject jwsToken, Key key) {
    JWSVerifier verifier;
    try {
        verifier = VERIFIER_FACTORY.createJWSVerifier(jwsToken.getHeader(), key);
    } catch (JOSEException ex) {
        return false;
    }

    try {
        return jwsToken.verify(verifier);
    } catch (JOSEException e) {
        return false;
    }
}
JWTGenerator.java 文件源码 项目:edge-jwt-sample 阅读 46 收藏 0 点赞 0 评论 0
private Key getJWEKey(String key, String algo) throws Exception {
    if ("A128GCMKW".equals(algo) || "A192GCMKW".equals(algo) || "A256GCMKW".equals(algo)) {
        return new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
    } else if ("A128KW".equals(algo) || "A192KW".equals(algo) || "A256KW".equals(algo)) {
        return new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
    } else if ("RSA_OAEP".equals(algo) || "RSA1_5".equals(algo)) {
        return getDERPublicKeyFromPEM(key);
    }
    // TODO other AES, RSA and EC variants

    return null;
}
RSAUtils.java 文件源码 项目:RLibrary 阅读 36 收藏 0 点赞 0 评论 0
/**
     * <P>
     * 私钥解密
     * </p>
     *
     * @param encryptedData 已加密数据
     * @param privateKey    私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
            throws Exception {
        byte[] keyBytes = Base64Utils.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
//        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

        cipher.init(Cipher.DECRYPT_MODE, privateK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密  
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }
Codec.java 文件源码 项目:GitHub 阅读 42 收藏 0 点赞 0 评论 0
/**
 * 用私钥解密
 *
 * @param data
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] decryptByPrivateKey(byte[] data, String key)
        throws Exception {
    byte[] keyBytes = BASE64.decode(key);   // 对密钥解密

    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);   // 取得私钥
    KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());
    Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

    // 对数据解密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    return cipher.doFinal(data);
}
JWTUtil.java 文件源码 项目:edge-jwt-sample 阅读 42 收藏 0 点赞 0 评论 0
private static String jweDecrypt(Key key, String jwt) throws Exception {
    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setAlgorithmConstraints(
        new AlgorithmConstraints(
            ConstraintType.WHITELIST, 
            KeyManagementAlgorithmIdentifiers.RSA_OAEP));
    jwe.setContentEncryptionAlgorithmConstraints(
        new AlgorithmConstraints(
            ConstraintType.WHITELIST, 
            ContentEncryptionAlgorithmIdentifiers.AES_256_CBC_HMAC_SHA_512));
    jwe.setCompactSerialization(jwt);
    jwe.setKey(key);
    return jwe.getPlaintextString();
}
JceGenericKey.java 文件源码 项目:ipack 阅读 38 收藏 0 点赞 0 评论 0
/**
 * Attempt to simplify the key representation if possible.
 *
 * @param key a provider based key
 * @return the byte encoding if one exists, key object otherwise.
 */
private static Object getRepresentation(Key key)
{
    byte[] keyBytes = key.getEncoded();

    if (keyBytes != null)
    {
        return keyBytes;
    }

    return key;
}
MacHashFunctionTest.java 文件源码 项目:googles-monorepo-demo 阅读 48 收藏 0 点赞 0 评论 0
public void testNulls() {
  NullPointerTester tester = new NullPointerTester()
      .setDefault(String.class, "HmacMD5")
      .setDefault(Key.class, MD5_KEY);
  tester.testAllPublicConstructors(MacHashFunction.class);
  tester.testAllPublicInstanceMethods(new MacHashFunction("HmacMD5", MD5_KEY, "toString"));
}
KeyStoreTestUtil.java 文件源码 项目:hadoop 阅读 36 收藏 0 点赞 0 评论 0
public static void createKeyStore(String filename,
    String password, String alias,
    Key privateKey, Certificate cert)
    throws GeneralSecurityException, IOException {
  KeyStore ks = createEmptyKeyStore();
  ks.setKeyEntry(alias, privateKey, password.toCharArray(),
      new Certificate[]{cert});
  saveKeyStore(ks, filename, password);
}
S3KeyWrapScheme.java 文件源码 项目:ibm-cos-sdk-java 阅读 43 收藏 0 点赞 0 评论 0
/**
 * @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;
}
McEliecePKCSCipherSpi.java 文件源码 项目:ipack 阅读 46 收藏 0 点赞 0 评论 0
protected void initCipherDecrypt(Key key, AlgorithmParameterSpec params)
    throws InvalidKeyException, InvalidAlgorithmParameterException
{
    CipherParameters param;
    param = McElieceKeysToParams.generatePrivateKeyParameter((PrivateKey)key);

    digest.reset();
    cipher.init(false, param);
    this.maxPlainTextSize = cipher.maxPlainTextSize;
    this.cipherTextSize = cipher.cipherTextSize;
}
CipherSpi.java 文件源码 项目:ipack 阅读 43 收藏 0 点赞 0 评论 0
protected void engineInit(
    int                 opmode,
    Key                 key,
    AlgorithmParameters params,
    SecureRandom        random) 
throws InvalidKeyException, InvalidAlgorithmParameterException
{
    throw new InvalidAlgorithmParameterException("can't handle parameters in ElGamal");
}
NoteEncryptionServiceImpl.java 文件源码 项目:poppynotes 阅读 39 收藏 0 点赞 0 评论 0
private Key createKey(String key, String principalName) {
    byte[] keyBytes = decodeBase64(key);
    byte[] principalBytes = getPrincipalWithoutEmailTail(principalName).getBytes(UTF_8);

    if(principalBytes.length > MAX_KEY_SIZE_BYTES){
        principalBytes = ArrayUtils.subarray(principalBytes, 0, MAX_KEY_SIZE_BYTES);
    }
    keyBytes = concatenateByteArrays(keyBytes,principalBytes);
    return new SecretKeySpec(keyBytes, 0, keyBytes.length, ENCRYPTION_ALGORITHM);
}
InstagramHashing.java 文件源码 项目:RoboInsta 阅读 37 收藏 0 点赞 0 评论 0
public static String generateHash(String key, String string) {
    SecretKeySpec object = new SecretKeySpec(key.getBytes(), "HmacSHA256");
    try {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init((Key) object);
        byte[] byteArray = mac.doFinal(string.getBytes("UTF-8"));
        return new String(new Hex().encode(byteArray), "ISO-8859-1");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
NativeRSACipher.java 文件源码 项目:openjdk-jdk10 阅读 43 收藏 0 点赞 0 评论 0
@Override
protected synchronized void engineInit(int opmode, Key key, AlgorithmParameters params,
        SecureRandom random)
        throws InvalidKeyException, InvalidAlgorithmParameterException {
    if (params != null) {
        throw new InvalidAlgorithmParameterException("No Parameters can be specified");
    }
    engineInit(opmode, key, (AlgorithmParameterSpec) null, random);
}
Main.java 文件源码 项目:openjdk-jdk10 阅读 44 收藏 0 点赞 0 评论 0
private void checkWeak(String label, String sigAlg, Key key) {

        if (sigAlg != null && !DISABLED_CHECK.permits(
                SIG_PRIMITIVE_SET, sigAlg, null)) {
            weakWarnings.add(String.format(
                    rb.getString("whose.sigalg.risk"), label, sigAlg));
        }
        if (key != null && !DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) {
            weakWarnings.add(String.format(
                    rb.getString("whose.key.risk"),
                    label,
                    String.format(rb.getString("key.bit"),
                            KeyUtil.getKeySize(key), key.getAlgorithm())));
        }
    }
Context.java 文件源码 项目:ditb 阅读 51 收藏 0 点赞 0 评论 0
public Context setKey(Key key) {
  Preconditions.checkNotNull(cipher, "Context does not have a cipher");
  // validate the key length
  byte[] encoded = key.getEncoded();
  if (encoded.length != cipher.getKeyLength()) {
    throw new RuntimeException("Illegal key length, have=" + encoded.length +
      ", want=" + cipher.getKeyLength());
  }
  this.key = key;
  this.keyHash = MD5Hash.getMD5AsHex(encoded);
  return this;
}


问题


面经


文章

微信
公众号

扫码关注公众号