Java Code Examples for java.security.PublicKey#getEncoded()
The following examples show how to use
java.security.PublicKey#getEncoded() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KeyIdentifier.java From openjdk-jdk9 with GNU General Public License v2.0 | 7 votes |
/** * Creates a KeyIdentifier from a public-key value. * * <p>From RFC2459: Two common methods for generating key identifiers from * the public key are: * <ol> * <li>The keyIdentifier is composed of the 160-bit SHA-1 hash of the * value of the BIT STRING subjectPublicKey (excluding the tag, * length, and number of unused bits). * * <li>The keyIdentifier is composed of a four bit type field with * the value 0100 followed by the least significant 60 bits of the * SHA-1 hash of the value of the BIT STRING subjectPublicKey. * </ol> * <p>This method supports method 1. * * @param pubKey the public key from which to construct this KeyIdentifier * @throws IOException on parsing errors */ public KeyIdentifier(PublicKey pubKey) throws IOException { DerValue algAndKey = new DerValue(pubKey.getEncoded()); if (algAndKey.tag != DerValue.tag_Sequence) throw new IOException("PublicKey value is not a valid " + "X.509 public key"); AlgorithmId algid = AlgorithmId.parse(algAndKey.data.getDerValue()); byte[] key = algAndKey.data.getUnalignedBitString().toByteArray(); MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e3) { throw new IOException("SHA1 not supported"); } md.update(key); this.octetString = md.digest(); }
Example 2
Source File: SignedWitnessService.java From bisq with GNU Affero General Public License v3.0 | 6 votes |
public void signAccountAgeWitness(Coin tradeAmount, AccountAgeWitness accountAgeWitness, PublicKey peersPubKey) throws CryptoException { if (isSignedAccountAgeWitness(accountAgeWitness)) { log.warn("Trader trying to sign already signed accountagewitness {}", accountAgeWitness.toString()); return; } if (!isSufficientTradeAmountForSigning(tradeAmount)) { log.warn("Trader tried to sign account with too little trade amount"); return; } byte[] signature = Sig.sign(keyRing.getSignatureKeyPair().getPrivate(), accountAgeWitness.getHash()); SignedWitness signedWitness = new SignedWitness(SignedWitness.VerificationMethod.TRADE, accountAgeWitness.getHash(), signature, keyRing.getSignatureKeyPair().getPublic().getEncoded(), peersPubKey.getEncoded(), new Date().getTime(), tradeAmount.value); publishSignedWitness(signedWitness); log.info("Trader signed witness {}", signedWitness.toString()); }
Example 3
Source File: KeyIdentifier.java From j2objc with Apache License 2.0 | 6 votes |
/** * Creates a KeyIdentifier from a public-key value. * * <p>From RFC2459: Two common methods for generating key identifiers from * the public key are: * <ol> * <li>The keyIdentifier is composed of the 160-bit SHA-1 hash of the * value of the BIT STRING subjectPublicKey (excluding the tag, * length, and number of unused bits). * <p> * <li>The keyIdentifier is composed of a four bit type field with * the value 0100 followed by the least significant 60 bits of the * SHA-1 hash of the value of the BIT STRING subjectPublicKey. * </ol> * <p>This method supports method 1. * * @param pubKey the public key from which to construct this KeyIdentifier * @throws IOException on parsing errors */ public KeyIdentifier(PublicKey pubKey) throws IOException { DerValue algAndKey = new DerValue(pubKey.getEncoded()); if (algAndKey.tag != DerValue.tag_Sequence) throw new IOException("PublicKey value is not a valid " + "X.509 public key"); AlgorithmId algid = AlgorithmId.parse(algAndKey.data.getDerValue()); byte[] key = algAndKey.data.getUnalignedBitString().toByteArray(); MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e3) { throw new IOException("SHA1 not supported"); } md.update(key); this.octetString = md.digest(); }
Example 4
Source File: KeyIdentifier.java From Bytecoder with Apache License 2.0 | 6 votes |
/** * Creates a KeyIdentifier from a public-key value. * * <p>From RFC 5280: Two common methods for generating key identifiers from * the public key are: * <ol> * <li>The keyIdentifier is composed of the 160-bit SHA-1 hash of the * value of the BIT STRING subjectPublicKey (excluding the tag, * length, and number of unused bits). * * <li>The keyIdentifier is composed of a four bit type field with * the value 0100 followed by the least significant 60 bits of the * SHA-1 hash of the value of the BIT STRING subjectPublicKey. * </ol> * <p>This method supports method 1. * * @param pubKey the public key from which to construct this KeyIdentifier * @throws IOException on parsing errors */ public KeyIdentifier(PublicKey pubKey) throws IOException { DerValue algAndKey = new DerValue(pubKey.getEncoded()); if (algAndKey.tag != DerValue.tag_Sequence) throw new IOException("PublicKey value is not a valid " + "X.509 public key"); AlgorithmId algid = AlgorithmId.parse(algAndKey.data.getDerValue()); byte[] key = algAndKey.data.getUnalignedBitString().toByteArray(); MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e3) { throw new IOException("SHA1 not supported"); } md.update(key); this.octetString = md.digest(); }
Example 5
Source File: CipherStorageKeystoreRsaEcb.java From react-native-keychain with MIT License | 6 votes |
/** Clean code without try/catch's that encrypt username and password with a key specified by alias. */ @NonNull private EncryptionResult innerEncryptedCredentials(@NonNull final String alias, @NonNull final String password, @NonNull final String username, @NonNull final SecurityLevel level) throws GeneralSecurityException, IOException { final KeyStore store = getKeyStoreAndLoad(); // on first access create a key for storage if (!store.containsAlias(alias)) { generateKeyAndStoreUnderAlias(alias, level); } final KeyFactory kf = KeyFactory.getInstance(ALGORITHM_RSA); final Certificate certificate = store.getCertificate(alias); final PublicKey publicKey = certificate.getPublicKey(); final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey.getEncoded()); final PublicKey key = kf.generatePublic(keySpec); return new EncryptionResult( encryptString(key, username), encryptString(key, password), this); }
Example 6
Source File: KeyUtil.java From xipki with Apache License 2.0 | 5 votes |
public static AsymmetricKeyParameter generatePublicKeyParameter(PublicKey key) throws InvalidKeyException { Args.notNull(key, "key"); if (key instanceof RSAPublicKey) { RSAPublicKey rsaKey = (RSAPublicKey) key; return new RSAKeyParameters(false, rsaKey.getModulus(), rsaKey.getPublicExponent()); } else if (key instanceof ECPublicKey) { return ECUtil.generatePublicKeyParameter(key); } else if (key instanceof DSAPublicKey) { return DSAUtil.generatePublicKeyParameter(key); } else if (key instanceof XDHKey || key instanceof EdDSAKey) { byte[] encoded = key.getEncoded(); String algorithm = key.getAlgorithm().toUpperCase(); if (EdECConstants.X25519.equals(algorithm)) { return new X25519PublicKeyParameters(encoded, encoded.length - 32); } else if (EdECConstants.ED25519.equals(algorithm)) { return new Ed25519PublicKeyParameters(encoded, encoded.length - 32); } else if (EdECConstants.X448.equals(algorithm)) { return new X448PublicKeyParameters(encoded, encoded.length - 56); } else if (EdECConstants.ED448.equals(algorithm)) { return new Ed448PublicKeyParameters(encoded, encoded.length - 57); } else { throw new InvalidKeyException("unknown Edwards key " + algorithm); } } else { throw new InvalidKeyException("unknown key " + key.getClass().getName()); } }
Example 7
Source File: JsonXdhTest.java From wycheproof with Apache License 2.0 | 5 votes |
/** * An alternative way to generate an XDH key is to use specific names for the algorithm (i.e. * "X25519" or "X448"). These names fully specify key size and algorithm. * * <p>This test generates a key pair with such an algorithm name, serializes the keys, prints them * and the imports the keys back again. This allows to debug issues such as * https://bugs.openjdk.java.net/browse/JDK-8213493 */ public void testKeyGenerationWithName(String algorithmName) throws Exception { KeyPairGenerator kpg; try { kpg = KeyPairGenerator.getInstance(algorithmName); } catch (NoSuchAlgorithmException ex) { System.out.println(algorithmName + " is not supported"); return; } KeyPair kp = kpg.generateKeyPair(); PrivateKey priv = kp.getPrivate(); PublicKey pub = kp.getPublic(); // Encodings are a bit of a problem. byte[] privEncoded = priv.getEncoded(); System.out.println( algorithmName + " privat key format:" + priv.getFormat() + " encoded:" + TestUtil.bytesToHex(privEncoded)); byte[] pubEncoded = pub.getEncoded(); System.out.println( algorithmName + " public key format:" + pub.getFormat() + " encoded:" + TestUtil.bytesToHex(pubEncoded)); KeyFactory kf = KeyFactory.getInstance("XDH"); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privEncoded); PrivateKey unusedPrivKey2 = kf.generatePrivate(privKeySpec); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubEncoded); PublicKey unusedPubKey2 = kf.generatePublic(pubKeySpec); }
Example 8
Source File: OtrAndroidKeyManagerImpl.java From Zom-Android-XMPP with GNU General Public License v3.0 | 5 votes |
public void savePublicKey(SessionID sessionID, PublicKey pubKey) { X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKey.getEncoded()); // if (!Address.hasResource(sessionID.getRemoteUserId())) // return; String fullUserId = sessionID.getUserID(); this.store.setProperty(fullUserId + ".publicKey", x509EncodedKeySpec.getEncoded()); // Stash the associated fingerprint. This saves calculating it in the future // and is useful for transferring rosters to other apps. try { String fingerprintString = OtrCryptoEngine.getFingerprint(pubKey); String verifiedToken = buildPublicKeyVerifiedId(sessionID.getUserID(), fingerprintString); String fingerprintKey = fullUserId + ".fingerprint"; //if a fingerprint for this userid exists, then check if the key is verified if (this.store.hasProperty(fingerprintKey)) { if (!this.store.hasProperty(verifiedToken)) this.store.setProperty(verifiedToken, false); } else { //if there is no key, then we can "trust on first use"! this.store.setProperty(fingerprintKey, fingerprintString); this.store.setProperty(verifiedToken, true); } } catch (Exception e) { Log.e(ImApp.LOG_TAG,"otr error: " + e.getMessage(),e); } }
Example 9
Source File: X509CertSelector.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
/** * Sets the subjectPublicKey criterion. The * {@code X509Certificate} must contain the specified subject public * key. If {@code null}, no subjectPublicKey check will be done. * * @param key the subject public key to check for (or {@code null}) * @see #getSubjectPublicKey */ public void setSubjectPublicKey(PublicKey key) { if (key == null) { subjectPublicKey = null; subjectPublicKeyBytes = null; } else { subjectPublicKey = key; subjectPublicKeyBytes = key.getEncoded(); } }
Example 10
Source File: KeyCodecTest.java From UAF with Apache License 2.0 | 5 votes |
@Test public void pss() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, DataLengthException, CryptoException, InvalidKeyException, SignatureException, InvalidKeySpecException, IOException{ KeyPair keyPair = KeyCodec.getRSAKeyPair(); KeyPair keyPair2 = KeyCodec.getRSAKeyPair(); PrivateKey privKey = keyPair.getPrivate(); byte[] encodedPrivKey = privKey.getEncoded(); logger.info("priv=" + Base64.encodeBase64URLSafeString(encodedPrivKey)); PublicKey pubKey = keyPair.getPublic(); byte[] encodedPubKey = pubKey.getEncoded(); SubjectPublicKeyInfo spkInfo = SubjectPublicKeyInfo.getInstance(encodedPubKey); ASN1Primitive primitive = spkInfo.parsePublicKey(); PublicKey publicKey = KeyCodec.getRSAPublicKey(primitive.getEncoded()); logger.info("pub=" + Base64.encodeBase64URLSafeString(encodedPubKey)); logger.info("pub format=" + pubKey.getFormat()); logger.info("pub alg=" + pubKey.getAlgorithm()); byte[] slt = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776af"); //a random salt byte[] signed = RSA.signPSS(privKey, slt); assertTrue(signed.length>0); RSA rsa = new RSA(); Assert.assertTrue(rsa.verifyPSS(publicKey, slt, signed)); byte[] slt2 = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776aa"); //a random salt byte[] signed2 = RSA.signPSS(keyPair2.getPrivate(), slt2); Assert.assertFalse(rsa.verifyPSS(publicKey, slt2, signed2)); Assert.assertFalse(rsa.verifyPSS(keyPair2.getPublic(), slt, signed)); }
Example 11
Source File: DSASigner.java From ripple-lib-java with ISC License | 5 votes |
protected void engineInitVerify( PublicKey publicKey) throws InvalidKeyException { CipherParameters param; if (publicKey instanceof DSAKey) { param = DSAUtil.generatePublicKeyParameter(publicKey); } else { try { byte[] bytes = publicKey.getEncoded(); publicKey = new BCDSAPublicKey(SubjectPublicKeyInfo.getInstance(bytes)); if (publicKey instanceof DSAKey) { param = DSAUtil.generatePublicKeyParameter(publicKey); } else { throw new InvalidKeyException("can't recognise key type in DSA based signer"); } } catch (Exception e) { throw new InvalidKeyException("can't recognise key type in DSA based signer"); } } digest.reset(); signer.init(false, param); }
Example 12
Source File: CertId.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
public CertId(X500Principal issuerName, PublicKey issuerKey, SerialNumber serialNumber) throws IOException { // compute issuerNameHash MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException nsae) { throw new IOException("Unable to create CertId", nsae); } hashAlgId = SHA1_ALGID; md.update(issuerName.getEncoded()); issuerNameHash = md.digest(); // compute issuerKeyHash (remove the tag and length) byte[] pubKey = issuerKey.getEncoded(); DerValue val = new DerValue(pubKey); DerValue[] seq = new DerValue[2]; seq[0] = val.data.getDerValue(); // AlgorithmID seq[1] = val.data.getDerValue(); // Key byte[] keyBytes = seq[1].getBitString(); md.update(keyBytes); issuerKeyHash = md.digest(); certSerialNumber = serialNumber; if (debug) { HexDumpEncoder encoder = new HexDumpEncoder(); System.out.println("Issuer Name is " + issuerName); System.out.println("issuerNameHash is " + encoder.encodeBuffer(issuerNameHash)); System.out.println("issuerKeyHash is " + encoder.encodeBuffer(issuerKeyHash)); System.out.println("SerialNumber is " + serialNumber.getNumber()); } }
Example 13
Source File: X509CertSelector.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
/** * Sets the subjectPublicKey criterion. The * {@code X509Certificate} must contain the specified subject public * key. If {@code null}, no subjectPublicKey check will be done. * * @param key the subject public key to check for (or {@code null}) * @see #getSubjectPublicKey */ public void setSubjectPublicKey(PublicKey key) { if (key == null) { subjectPublicKey = null; subjectPublicKeyBytes = null; } else { subjectPublicKey = key; subjectPublicKeyBytes = key.getEncoded(); } }
Example 14
Source File: X509CertSelector.java From jdk-1.7-annotated with Apache License 2.0 | 5 votes |
/** * Sets the subjectPublicKey criterion. The * <code>X509Certificate</code> must contain the specified subject public * key. If <code>null</code>, no subjectPublicKey check will be done. * * @param key the subject public key to check for (or <code>null</code>) * @see #getSubjectPublicKey */ public void setSubjectPublicKey(PublicKey key) { if (key == null) { subjectPublicKey = null; subjectPublicKeyBytes = null; } else { subjectPublicKey = key; subjectPublicKeyBytes = key.getEncoded(); } }
Example 15
Source File: DNSSECWithBC.java From dnsjava with BSD 2-Clause "Simplified" License | 5 votes |
private static byte[] fromEdDSAPublicKey(PublicKey key) { DNSOutput out = new DNSOutput(); byte[] encoded = key.getEncoded(); // subtract the X.509 prefix length out.writeByteArray(encoded, 12, encoded.length - 12); return out.toByteArray(); }
Example 16
Source File: X509CertSelector.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
/** * Sets the subjectPublicKey criterion. The * {@code X509Certificate} must contain the specified subject public * key. If {@code null}, no subjectPublicKey check will be done. * * @param key the subject public key to check for (or {@code null}) * @see #getSubjectPublicKey */ public void setSubjectPublicKey(PublicKey key) { if (key == null) { subjectPublicKey = null; subjectPublicKeyBytes = null; } else { subjectPublicKey = key; subjectPublicKeyBytes = key.getEncoded(); } }
Example 17
Source File: PublicKeyAuthenticator.java From Bukkit-SSHD with Apache License 2.0 | 5 votes |
@Override public boolean authenticate(String username, PublicKey key, ServerSession session) { byte[] keyBytes = key.getEncoded(); File keyFile = new File(authorizedKeysDir, username); if (keyFile.exists()) { try { FileReader fr = new FileReader(keyFile); PemDecoder pd = new PemDecoder(fr); PublicKey k = pd.getPemBytes(); pd.close(); if (k != null) { if (ArrayUtils.isEquals(key.getEncoded(), k.getEncoded())) { return true; } } else { SshdPlugin.instance.getLogger().severe("Failed to parse PEM file. " + keyFile.getAbsolutePath()); } } catch (Exception e) { SshdPlugin.instance.getLogger() .severe("Failed to process public key " + keyFile.getAbsolutePath() + ". " + e.getMessage()); } } else { SshdPlugin.instance.getLogger().warning("Could not locate public key for " + username + ". Make sure the user's key is named the same as their user name " + "without a file extension."); } return false; }
Example 18
Source File: ApkSignerTool.java From Xpatch with Apache License 2.0 | 4 votes |
/** * Prints details from the provided certificate to stdout. * * @param cert the certificate to be displayed. * @param name the name to be used to identify the certificate. * @param verbose boolean indicating whether public key details from the certificate should be * displayed. * * @throws NoSuchAlgorithmException if an instance of MD5, SHA-1, or SHA-256 cannot be * obtained. * @throws CertificateEncodingException if an error is encountered when encoding the * certificate. */ public static void printCertificate(X509Certificate cert, String name, boolean verbose) throws NoSuchAlgorithmException, CertificateEncodingException { if (cert == null) { throw new NullPointerException("cert == null"); } if (sha256 == null || sha1 == null || md5 == null) { sha256 = MessageDigest.getInstance("SHA-256"); sha1 = MessageDigest.getInstance("SHA-1"); md5 = MessageDigest.getInstance("MD5"); } System.out.println(name + " certificate DN: " + cert.getSubjectDN()); byte[] encodedCert = cert.getEncoded(); System.out.println(name + " certificate SHA-256 digest: " + HexEncoding.encode( sha256.digest(encodedCert))); System.out.println(name + " certificate SHA-1 digest: " + HexEncoding.encode( sha1.digest(encodedCert))); System.out.println( name + " certificate MD5 digest: " + HexEncoding.encode(md5.digest(encodedCert))); if (verbose) { PublicKey publicKey = cert.getPublicKey(); System.out.println(name + " key algorithm: " + publicKey.getAlgorithm()); int keySize = -1; if (publicKey instanceof RSAKey) { keySize = ((RSAKey) publicKey).getModulus().bitLength(); } else if (publicKey instanceof ECKey) { keySize = ((ECKey) publicKey).getParams() .getOrder().bitLength(); } else if (publicKey instanceof DSAKey) { // DSA parameters may be inherited from the certificate. We // don't handle this case at the moment. DSAParams dsaParams = ((DSAKey) publicKey).getParams(); if (dsaParams != null) { keySize = dsaParams.getP().bitLength(); } } System.out.println( name + " key size (bits): " + ((keySize != -1) ? String.valueOf(keySize) : "n/a")); byte[] encodedKey = publicKey.getEncoded(); System.out.println(name + " public key SHA-256 digest: " + HexEncoding.encode( sha256.digest(encodedKey))); System.out.println(name + " public key SHA-1 digest: " + HexEncoding.encode( sha1.digest(encodedKey))); System.out.println( name + " public key MD5 digest: " + HexEncoding.encode(md5.digest(encodedKey))); } }
Example 19
Source File: EncryptionUtil.java From tomcat-vault with Apache License 2.0 | 4 votes |
public byte[] encrypt(byte[] data, PublicKey publicKey, SecretKey key) throws Exception { // Get the KeyGenerator KeyGenerator kgen = KeyGenerator.getInstance(this.encryptionAlgorithm); kgen.init(keySize); byte[] publicKeyEncoded = publicKey.getEncoded(); SecretKeySpec skeySpec = new SecretKeySpec(key.getEncoded(), encryptionAlgorithm); // Instantiate the cipher Cipher cipher = Cipher.getInstance(encryptionAlgorithm); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(data); return encrypted; }
Example 20
Source File: ServerCrypto.java From carbon-identity with Apache License 2.0 | 4 votes |
@Override /** * @see org.apache.ws.security.components.crypto.Crypto#getSKIBytesFromCert(java.security.cert.X509Certificate) */ public byte[] getSKIBytesFromCert(X509Certificate cert) throws WSSecurityException { /* * Gets the DER-encoded OCTET string for the extension value (extnValue) * identified by the passed-in oid String. The oid string is represented * by a set of positive whole numbers separated by periods. */ byte[] derEncodedValue = cert.getExtensionValue(SKI_OID); if (cert.getVersion() < 3 || derEncodedValue == null) { PublicKey key = cert.getPublicKey(); if (!(key instanceof RSAPublicKey)) { throw new WSSecurityException(1, "noSKIHandling", new Object[]{"Support for RSA key only"}); } byte[] encoded = key.getEncoded(); // remove 22-byte algorithm ID and header byte[] value = new byte[encoded.length - 22]; System.arraycopy(encoded, 22, value, 0, value.length); MessageDigest sha; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { throw new WSSecurityException(1, "noSKIHandling", new Object[]{"Wrong certificate version (<3) and no " + "SHA1 message digest availabe"}); } sha.reset(); sha.update(value); return sha.digest(); } /** * Strip away first four bytes from the DerValue (tag and length of * ExtensionValue OCTET STRING and KeyIdentifier OCTET STRING) */ byte abyte0[] = new byte[derEncodedValue.length - 4]; System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length); return abyte0; }