/// <summary> /// Decrypt the encryptedData using the keyBits according the encrypt params. /// </summary> /// /// <param name="keyBits">The key value.</param> /// <param name="encryptedData">The data to decrypt.</param> /// <param name="params"></param> /// <returns>The decrypted data.</returns> public static Blob decrypt(Blob keyBits, Blob encryptedData, EncryptParams paras) { if (paras.getAlgorithmType() == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesEcb) { Cipher cipher = javax.crypto.Cipher.getInstance("AES/ECB/PKCS5PADDING"); cipher.init(javax.crypto.Cipher.DECRYPT_MODE, new SecretKeySpec(keyBits.getImmutableArray(), "AES")); return new Blob(cipher.doFinal(encryptedData.getImmutableArray()), false); } else if (paras.getAlgorithmType() == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc) { if (paras.getInitialVector().size() != BLOCK_SIZE) throw new Exception("incorrect initial vector size"); Cipher cipher_0 = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher_0.init(javax.crypto.Cipher.DECRYPT_MODE, new SecretKeySpec(keyBits.getImmutableArray(), "AES"), new IvParameterSpec(paras.getInitialVector() .getImmutableArray())); return new Blob(cipher_0.doFinal(encryptedData.getImmutableArray()), false); } else throw new Exception("unsupported encryption mode"); }
/// <summary> /// Decrypt the encryptedData using the keyBits according the encrypt params. /// </summary> /// /// <param name="keyBits">The key value (PKCS8-encoded private key).</param> /// <param name="encryptedData">The data to decrypt.</param> /// <param name="params">This decrypts according to params.getAlgorithmType().</param> /// <returns>The decrypted data.</returns> public static Blob decrypt(Blob keyBits, Blob encryptedData, EncryptParams paras) { PrivateKey privateKey = keyFactory_ .generatePrivate(new PKCS8EncodedKeySpec(keyBits .getImmutableArray())); String transformation; if (paras.getAlgorithmType() == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaPkcs) transformation = "RSA/ECB/PKCS1Padding"; else if (paras.getAlgorithmType() == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep) transformation = "RSA/ECB/OAEPWithSHA-1AndMGF1Padding"; else throw new Exception("unsupported padding scheme"); Cipher cipher = javax.crypto.Cipher.getInstance(transformation); cipher.init(javax.crypto.Cipher.DECRYPT_MODE, privateKey); return new Blob(cipher.doFinal(encryptedData.getImmutableArray()), false); }
/// <summary> /// Add a new member with the given key named keyName into a schedule named /// scheduleName. The member's identity name is keyName.getPrefix(-1). /// </summary> /// /// <param name="scheduleName">The schedule name.</param> /// <param name="keyName">The name of the key.</param> /// <param name="key">A Blob of the public key DER.</param> /// <exception cref="GroupManagerDb.Error">If there's no schedule named scheduleName, ifthe member's identity name already exists, or other database error.</exception> public override void addMember(String scheduleName, Name keyName, Blob key) { int scheduleId = getScheduleId(scheduleName); if (scheduleId == -1) throw new GroupManagerDb.Error("The schedule does not exist"); // Needs to be changed in the future. Name memberName = keyName.getPrefix(-1); try { PreparedStatement statement = database_ .prepareStatement(net.named_data.jndn.encrypt.Sqlite3GroupManagerDbBase.INSERT_addMember); statement.setInt(1, scheduleId); statement.setBytes(2, memberName.wireEncode(net.named_data.jndn.encoding.TlvWireFormat.get()) .getImmutableArray()); statement.setBytes(3, keyName.wireEncode(net.named_data.jndn.encoding.TlvWireFormat.get()) .getImmutableArray()); statement.setBytes(4, key.getImmutableArray()); try { statement.executeUpdate(); } finally { statement.close(); } } catch (SQLException exception) { throw new GroupManagerDb.Error( "Sqlite3GroupManagerDb.addMember: SQLite error: " + exception); } }
/// <summary> /// Verify the RSA signature on the SignedBlob using the given public key. /// </summary> /// /// <param name="signature">The signature bits.</param> /// <param name="signedBlob">the SignedBlob with the signed portion to verify.</param> /// <param name="publicKeyDer">The DER-encoded public key used to verify the signature.</param> /// <returns>true if the signature verifies, false if not.</returns> protected internal static bool verifySha256WithRsaSignature(Blob signature, SignedBlob signedBlob, Blob publicKeyDer) { KeyFactory keyFactory = null; try { keyFactory = System.KeyFactory.getInstance("RSA"); } catch (Exception exception) { // Don't expect this to happen. throw new SecurityException("RSA is not supported: " + exception.Message); } System.SecurityPublicKey publicKey = null; try { publicKey = keyFactory.generatePublic(new X509EncodedKeySpec( publicKeyDer.getImmutableArray())); } catch (InvalidKeySpecException exception_0) { // Don't expect this to happen. throw new SecurityException("X509EncodedKeySpec is not supported: " + exception_0.Message); } System.SecuritySignature rsaSignature = null; try { rsaSignature = System.SecuritySignature.getInstance("SHA256withRSA"); } catch (Exception e) { // Don't expect this to happen. throw new SecurityException( "SHA256withRSA algorithm is not supported"); } try { rsaSignature.initVerify(publicKey); } catch (InvalidKeyException exception_1) { throw new SecurityException("InvalidKeyException: " + exception_1.Message); } try { rsaSignature.update(signedBlob.signedBuf()); return rsaSignature.verify(signature.getImmutableArray()); } catch (SignatureException exception_2) { throw new SecurityException("SignatureException: " + exception_2.Message); } }
/// <summary> /// Verify the DigestSha256 signature on the SignedBlob by verifying that the /// digest of SignedBlob equals the signature. /// </summary> /// /// <param name="signature">The signature bits.</param> /// <param name="signedBlob">the SignedBlob with the signed portion to verify.</param> /// <returns>true if the signature verifies, false if not.</returns> protected internal static bool verifyDigestSha256Signature(Blob signature, SignedBlob signedBlob) { // Set signedPortionDigest to the digest of the signed portion of the signedBlob. byte[] signedPortionDigest = net.named_data.jndn.util.Common .digestSha256(signedBlob.signedBuf()); return ILOG.J2CsMapping.Collections.Arrays.Equals(signedPortionDigest,signature.getImmutableArray()); }
/// <summary> /// Compute a new HmacWithSha256 for the data packet and verify it against the /// signature value. /// </summary> /// /// @note This method is an experimental feature. The API may change. /// <param name="data">The Data packet to verify.</param> /// <param name="key">The key for the HmacWithSha256.</param> /// <param name="wireFormat">A WireFormat object used to encode the data packet.</param> /// <returns>True if the signature verifies, otherwise false.</returns> public static bool verifyDataWithHmacWithSha256(Data data, Blob key, WireFormat wireFormat) { // wireEncode returns the cached encoding if available. SignedBlob encoding = data.wireEncode(wireFormat); byte[] newSignatureBytes = net.named_data.jndn.util.Common.computeHmacWithSha256( key.getImmutableArray(), encoding.signedBuf()); return ILOG.J2CsMapping.NIO.ByteBuffer.wrap(newSignatureBytes).equals( data.getSignature().getSignature().buf()); }
/// <summary> /// Wire encode the data packet, compute an HmacWithSha256 and update the /// signature value. /// </summary> /// /// @note This method is an experimental feature. The API may change. /// <param name="data">The Data object to be signed. This updates its signature.</param> /// <param name="key">The key for the HmacWithSha256.</param> /// <param name="wireFormat">A WireFormat object used to encode the data packet.</param> public static void signWithHmacWithSha256(Data data, Blob key, WireFormat wireFormat) { // Encode once to get the signed portion. SignedBlob encoding = data.wireEncode(wireFormat); byte[] signatureBytes = net.named_data.jndn.util.Common.computeHmacWithSha256( key.getImmutableArray(), encoding.signedBuf()); data.getSignature().setSignature(new Blob(signatureBytes, false)); }
/// <summary> /// Add the key with keyName and keyBlob to the database. /// </summary> /// /// <param name="keyName">The key name.</param> /// <param name="keyBlob">The encoded key.</param> /// <exception cref="ConsumerDb.Error">if a key with the same keyName already exists inthe database, or other database error.</exception> public override void addKey(Name keyName, Blob keyBlob) { try { PreparedStatement statement = database_ .prepareStatement(net.named_data.jndn.encrypt.Sqlite3ConsumerDbBase.INSERT_addKey); statement.setBytes(1, keyName.wireEncode(net.named_data.jndn.encoding.TlvWireFormat.get()) .getImmutableArray()); statement.setBytes(2, keyBlob.getImmutableArray()); try { statement.executeUpdate(); } finally { statement.close(); } } catch (SQLException exception) { throw new ConsumerDb.Error( "Sqlite3ConsumerDb.addKey: SQLite error: " + exception); } }
/// <summary> /// Add key as the content key for the hour covering timeSlot. /// </summary> /// /// <param name="timeSlot">The time slot as milliseconds since Jan 1, 1970 UTC.</param> /// <param name="key">The encoded key.</param> /// <exception cref="ProducerDb.Error">if a key for the same hour already exists in thedatabase, or other database error.</exception> public override void addContentKey(double timeSlot, Blob key) { int fixedTimeSlot = net.named_data.jndn.encrypt.ProducerDb.getFixedTimeSlot(timeSlot); try { PreparedStatement statement = database_ .prepareStatement(net.named_data.jndn.encrypt.Sqlite3ProducerDbBase.INSERT_addContentKey); statement.setInt(1, fixedTimeSlot); statement.setBytes(2, key.getImmutableArray()); try { statement.executeUpdate(); } finally { statement.close(); } } catch (SQLException exception) { throw new ProducerDb.Error( "Sqlite3ProducerDb.addContentKey: SQLite error: " + exception); } }
/// <summary> /// Create a new PublicKey by decoding the keyDer. Set the key type from the /// decoding. /// </summary> /// /// <param name="keyDer">The blob of the SubjectPublicKeyInfo DER.</param> /// <exception cref="UnrecognizedKeyFormatException">if can't decode the key DER.</exception> public PublicKey(Blob keyDer) { keyDer_ = keyDer; // Get the public key OID. String oidString = null; try { DerNode parsedNode = net.named_data.jndn.encoding.der.DerNode.parse(keyDer.buf(), 0); IList rootChildren = parsedNode.getChildren(); IList algorithmIdChildren = net.named_data.jndn.encoding.der.DerNode.getSequence(rootChildren, 0) .getChildren(); oidString = "" + ((DerNode) algorithmIdChildren[0]).toVal(); } catch (DerDecodingException ex) { throw new UnrecognizedKeyFormatException( "PublicKey: Error decoding the public key: " + ex.Message); } // Verify that the we can decode. if (oidString.equals(RSA_ENCRYPTION_OID)) { keyType_ = net.named_data.jndn.security.KeyType.RSA; KeyFactory keyFactory = null; try { keyFactory = System.KeyFactory.getInstance("RSA"); } catch (Exception exception) { // Don't expect this to happen. throw new UnrecognizedKeyFormatException( "RSA is not supported: " + exception.Message); } try { keyFactory.generatePublic(new X509EncodedKeySpec(keyDer .getImmutableArray())); } catch (InvalidKeySpecException exception_0) { // Don't expect this to happen. throw new UnrecognizedKeyFormatException( "X509EncodedKeySpec is not supported for RSA: " + exception_0.Message); } } else if (oidString.equals(EC_ENCRYPTION_OID)) { keyType_ = net.named_data.jndn.security.KeyType.ECDSA; KeyFactory keyFactory_1 = null; try { keyFactory_1 = System.KeyFactory.getInstance("EC"); } catch (Exception exception_2) { // Don't expect this to happen. throw new UnrecognizedKeyFormatException( "EC is not supported: " + exception_2.Message); } try { keyFactory_1.generatePublic(new X509EncodedKeySpec(keyDer .getImmutableArray())); } catch (InvalidKeySpecException exception_3) { // Don't expect this to happen. throw new UnrecognizedKeyFormatException( "X509EncodedKeySpec is not supported for EC: " + exception_3.Message); } } else throw new UnrecognizedKeyFormatException( "PublicKey: Unrecognized OID " + oidString); }
/// <summary> /// Add a public key to the identity storage. Also call addIdentity to ensure /// that the identityName for the key exists. However, if the key already /// exists, do nothing. /// </summary> /// /// <param name="keyName">The name of the public key to be added.</param> /// <param name="keyType">Type of the public key to be added.</param> /// <param name="publicKeyDer">A blob of the public key DER to be added.</param> public override sealed void addKey(Name keyName, KeyType keyType, Blob publicKeyDer) { if (keyName.size() == 0) return; if (doesKeyExist(keyName)) return; String keyId = keyName.get(-1).toEscapedString(); Name identityName = keyName.getPrefix(-1); addIdentity(identityName); try { PreparedStatement statement = database_ .prepareStatement("INSERT INTO Key (identity_name, key_identifier, key_type, public_key) values (?, ?, ?, ?)"); statement.setString(1, identityName.toUri()); statement.setString(2, keyId); statement.setInt(3, keyType.getNumericType()); statement.setBytes(4, publicKeyDer.getImmutableArray()); try { statement.executeUpdate(); } finally { statement.close(); } } catch (SQLException exception) { throw new SecurityException("BasicIdentityStorage: SQLite error: " + exception); } }